diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 4857902b8cc..f97d4aa94ee 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -255,6 +255,12 @@ if ($action == 'update' && !empty($permissiontoadd)) { $result = $object->update($user); if ($result > 0) { $action = 'view'; + $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist; + $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation + if ($urltogo) { + header("Location: " . $urltogo); + exit; + } } else { $error++; // Creation KO diff --git a/htdocs/core/ajax/row.php b/htdocs/core/ajax/row.php index 97a74e74916..383f9a0c041 100644 --- a/htdocs/core/ajax/row.php +++ b/htdocs/core/ajax/row.php @@ -95,6 +95,8 @@ if (GETPOST('roworder', 'alpha', 3) && GETPOST('table_element_line', 'aZ09', 3) $perm = 1; } elseif ($table_element_line == 'facture_fourn_det_rec' && $user->rights->fournisseur->facture->creer) { $perm = 1; + } elseif ($table_element_line == 'product_attribute_value' && $fk_element == 'fk_product_attribute' && ($user->rights->produit->lire || $user->rights->service->lire)) { + $perm = 1; } elseif ($table_element_line == 'ecm_files') { // Used when of page "documents.php" if (!empty($user->rights->ecm->creer)) { $perm = 1; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 51bfc09d44d..d76d39230ab 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -2931,15 +2931,20 @@ abstract class CommonObject return -1; } + $fieldposition = 'rang'; // @todo Rename 'rang' into 'position' + if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { + $fieldposition = 'position'; + } + // Count number of lines to reorder (according to choice $renum) $nl = 0; $sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line; $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); if (!$renum) { - $sql .= ' AND rang = 0'; + $sql .= " AND " . $fieldposition . " = 0"; } if ($renum) { - $sql .= ' AND rang <> 0'; + $sql .= " AND " . $fieldposition . " <> 0"; } dol_syslog(get_class($this)."::line_order", LOG_DEBUG); @@ -2960,7 +2965,7 @@ abstract class CommonObject if ($fk_parent_line) { $sql .= ' AND fk_parent_line IS NULL'; } - $sql .= " ORDER BY rang ASC, rowid ".$rowidorder; + $sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder; dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG); $resql = $this->db->query($sql); @@ -3001,12 +3006,17 @@ abstract class CommonObject */ public function getChildrenOfLine($id, $includealltree = 0) { + $fieldposition = 'rang'; // @todo Rename 'rang' into 'position' + if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { + $fieldposition = 'position'; + } + $rows = array(); $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line; $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); $sql .= ' AND fk_parent_line = '.((int) $id); - $sql .= ' ORDER BY rang ASC'; + $sql .= " ORDER BY " . $fieldposition . " ASC"; dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG); $resql = $this->db->query($sql); @@ -3077,7 +3087,7 @@ abstract class CommonObject { global $hookmanager; $fieldposition = 'rang'; // @todo Rename 'rang' into 'position' - if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) { + if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { $fieldposition = 'position'; } @@ -3123,13 +3133,13 @@ abstract class CommonObject { if ($rang > 1) { $fieldposition = 'rang'; - if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) { + if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { $fieldposition = 'position'; } $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang); $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= ' AND rang = '.((int) ($rang - 1)); + $sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1)); if ($this->db->query($sql)) { $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1)); $sql .= ' WHERE rowid = '.((int) $rowid); @@ -3154,13 +3164,13 @@ abstract class CommonObject { if ($rang < $max) { $fieldposition = 'rang'; - if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) { + if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { $fieldposition = 'position'; } $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang); $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= ' AND rang = '.((int) ($rang + 1)); + $sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1)); if ($this->db->query($sql)) { $sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1)); $sql .= ' WHERE rowid = '.((int) $rowid); @@ -3181,7 +3191,12 @@ abstract class CommonObject */ public function getRangOfLine($rowid) { - $sql = "SELECT rang FROM ".$this->db->prefix().$this->table_element_line; + $fieldposition = 'rang'; + if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { + $fieldposition = 'position'; + } + + $sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line; $sql .= " WHERE rowid = ".((int) $rowid); dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); @@ -3200,9 +3215,14 @@ abstract class CommonObject */ public function getIdOfLine($rang) { + $fieldposition = 'rang'; + if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) { + $fieldposition = 'position'; + } + $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line; $sql .= " WHERE ".$this->fk_element." = ".((int) $this->id); - $sql .= " AND rang = ".((int) $rang); + $sql .= " AND " . $fieldposition . " = ".((int) $rang); $resql = $this->db->query($sql); if ($resql) { $row = $this->db->fetch_row($resql); @@ -3221,7 +3241,7 @@ abstract class CommonObject { // phpcs:enable $positionfield = 'rang'; - if ($this->table_element == 'bom_bom') { + if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) { $positionfield = 'position'; } diff --git a/htdocs/core/modules/modVariants.class.php b/htdocs/core/modules/modVariants.class.php index a6c88afc03d..049377a561f 100644 --- a/htdocs/core/modules/modVariants.class.php +++ b/htdocs/core/modules/modVariants.class.php @@ -73,10 +73,10 @@ class modVariants extends DolibarrModules $this->module_parts = array(); // Data directories to create when module is enabled. - // Example: this->dirs = array("/mymodule/temp"); + // Example: this->dirs = array("/variants/temp"); $this->dirs = array(); - // Config pages. Put here list of php page, stored into mymodule/admin directory, to use to setup module. + // Config pages. Put here list of php page, stored into variants/admin directory, to use to setup module. $this->config_page_url = array('admin.php@variants'); // Dependencies @@ -97,9 +97,9 @@ class modVariants extends DolibarrModules ); // Dictionaries - if (!isset($conf->mymodule->enabled)) { - $conf->mymodule = new stdClass(); - $conf->mymodule->enabled = 0; + if (!isset($conf->variants->enabled)) { + $conf->variants = new stdClass(); + $conf->variants->enabled = 0; } $this->dictionaries = array(); diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang index 86d11ec59ea..0ace8e10d52 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -279,6 +279,8 @@ ErrorExecIdFailed=Can't execute command "id" ErrorBadCharIntoLoginName=Unauthorized character in the login name ErrorRequestTooLarge=Error, request too large ErrorNotApproverForHoliday=You are not the approver for leave %s +ErrorAttributeIsUsedIntoProduct=This attribute is used in one or more product variants +ErrorAttributeValueIsUsedIntoProduct=This attribute value is used in one or more product variants # Warnings WarningParamUploadMaxFileSizeHigherThanPostMaxSize=Your PHP parameter upload_max_filesize (%s) is higher than PHP parameter post_max_size (%s). This is not a consistent setup. diff --git a/htdocs/variants/ajax/getCombinations.php b/htdocs/variants/ajax/getCombinations.php index 9c670fa07cc..2559ed6169c 100644 --- a/htdocs/variants/ajax/getCombinations.php +++ b/htdocs/variants/ajax/getCombinations.php @@ -1,6 +1,7 @@ + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -36,8 +37,6 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; -$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; - // Security check if (empty($conf->variants->enabled)) { accessforbidden('Module not enabled'); @@ -45,8 +44,7 @@ if (empty($conf->variants->enabled)) { if ($user->socid > 0) { // Protection if external user accessforbidden(); } -//$result = restrictedArea($user, 'variant'); -if (!$permissiontoread) accessforbidden(); +$result = restrictedArea($user, 'variants'); /* diff --git a/htdocs/variants/ajax/get_attribute_values.php b/htdocs/variants/ajax/get_attribute_values.php index 1d4eab49773..4500db843e8 100644 --- a/htdocs/variants/ajax/get_attribute_values.php +++ b/htdocs/variants/ajax/get_attribute_values.php @@ -1,5 +1,6 @@ + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -36,8 +37,6 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php'; require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php'; -$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; - // Security check if (empty($conf->variants->enabled)) { accessforbidden('Module not enabled'); @@ -45,8 +44,7 @@ if (empty($conf->variants->enabled)) { if ($user->socid > 0) { // Protection if external user accessforbidden(); } -//$result = restrictedArea($user, 'variant'); -if (!$permissiontoread) accessforbidden(); +$result = restrictedArea($user, 'variants'); /* diff --git a/htdocs/variants/ajax/orderAttribute.php b/htdocs/variants/ajax/orderAttribute.php index 81632dc0164..9be6e69d852 100644 --- a/htdocs/variants/ajax/orderAttribute.php +++ b/htdocs/variants/ajax/orderAttribute.php @@ -1,6 +1,7 @@ + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -36,8 +37,7 @@ if (!defined('NOREQUIRETRAN')) { } require '../../main.inc.php'; - -$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; +require DOL_DOCUMENT_ROOT . '/variants/class/ProductAttribute.class.php'; // Security check if (empty($conf->variants->enabled)) { @@ -46,8 +46,7 @@ if (empty($conf->variants->enabled)) { if ($user->socid > 0) { // Protection if external user accessforbidden(); } -//$result = restrictedArea($user, 'variant'); -if (!$permissiontoread) accessforbidden(); +$result = restrictedArea($user, 'variants'); /* @@ -56,14 +55,15 @@ if (!$permissiontoread) accessforbidden(); top_httphead(); -// Registering the location of boxes -if (GETPOSTISSET('roworder')) { - $roworder = GETPOST('roworder', 'intcomma', 2); +print ''."\n"; - dol_syslog("AjaxOrderAttribute roworder=".$roworder, LOG_DEBUG); +// Registering the location of boxes +if (GETPOST('roworder', 'alpha', 3)) { + $roworder = GETPOST('roworder', 'alpha', 3); + + dol_syslog("AjaxOrderAttribute roworder=" . $roworder, LOG_DEBUG); $rowordertab = explode(',', $roworder); - $newrowordertab = array(); foreach ($rowordertab as $value) { if (!empty($value)) { @@ -71,7 +71,9 @@ if (GETPOSTISSET('roworder')) { } } - require DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php'; + $row = new ProductAttribute($db); - ProductAttribute::bulkUpdateOrder($db, $newrowordertab); + $row->attributesAjaxOrder($newrowordertab); // This update field rank or position in table row->table_element_line +} else { + print 'Bad parameters for orderAttribute.php'; } diff --git a/htdocs/variants/card.php b/htdocs/variants/card.php index ed70c6325e3..1ee1543b9e4 100644 --- a/htdocs/variants/card.php +++ b/htdocs/variants/card.php @@ -1,6 +1,7 @@ * Copyright (C) 2018 Frédéric France + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,27 +17,29 @@ * along with this program. If not, see . */ +/** + * \file htdocs/variants/card.php + * \ingroup variants + * \brief Page to show product attribute + */ + require '../main.inc.php'; require 'class/ProductAttribute.class.php'; require 'class/ProductAttributeValue.class.php'; +require 'lib/variants.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array('products')); $id = GETPOST('id', 'int'); -$valueid = GETPOST('valueid', 'alpha'); -$action = GETPOST('action', 'aZ09'); -$label = GETPOST('label', 'alpha'); $ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); - -$object = new ProductAttribute($db); -$objectval = new ProductAttributeValue($db); - -if ($object->fetch($id) < 1) { - dol_print_error($db, $langs->trans('ErrorRecordNotFound')); - exit(); -} - -$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'productattribute'; // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); +$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); +$lineid = GETPOST('lineid', 'alpha'); // Security check if (empty($conf->variants->enabled)) { @@ -45,84 +48,102 @@ if (empty($conf->variants->enabled)) { if ($user->socid > 0) { // Protection if external user accessforbidden(); } -//$result = restrictedArea($user, 'variant'); -if (!$permissiontoread) accessforbidden(); +$result = restrictedArea($user, 'variants'); + +$object = new ProductAttribute($db); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('productattributecard', 'globalcard')); + +$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; +$permissiontoadd = $user->rights->produit->lire || $user->rights->service->lire; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissiontoedit = $user->rights->produit->lire || $user->rights->service->lire; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissiontodelete = $user->rights->produit->lire || $user->rights->service->lire; + +$error = 0; /* * Actions */ -if ($cancel) { - $action = ''; + +$parameters = array(); +// Note that $action and $object may be modified by some hooks +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); } -if ($action) { - if ($action == 'update') { - $object->ref = $ref; - $object->label = $label; +if (empty($reshook)) { + $error = 0; - if ($object->update($user) < 1) { - setEventMessages($langs->trans('CoreErrorMessage'), $object->errors, 'errors'); - } else { - setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); - header('Location: '.dol_buildpath('/variants/card.php?id='.$id, 2)); - exit(); - } - } elseif ($action == 'update_value') { - if ($objectval->fetch($valueid) > 0) { - $objectval->ref = $ref; - $objectval->value = GETPOST('value', 'alpha'); + $backurlforlist = dol_buildpath('/variants/list.php', 1); - if (empty($objectval->ref)) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors'); - } - if (empty($objectval->value)) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - } - - if (!$error) { - if ($objectval->update($user) > 0) { - setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); - } else { - setEventMessage($langs->trans('CoreErrorMessage'), $objectval->errors, 'errors'); - } + if (empty($backtopage) || ($cancel && empty($id))) { + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/variants/card.php', 1).'?id='.((!empty($id) && $id > 0) ? $id : '__ID__'); } } + } - header('Location: '.dol_buildpath('/variants/card.php?id='.$object->id, 2)); + // Action to move up and down lines of object + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; + if ($cancel) { + if (!empty($backtopage)) { + header("Location: " . $backtopage); + exit; + } + $action = ''; + } + + // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; + + // Action to move up and down lines of object + if ($action == 'up' && $permissiontoedit) { + $object->line_up(GETPOST('rowid'), false); + + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('rowid')); + exit(); + } elseif ($action == 'down' && $permissiontoedit) { + $object->line_down(GETPOST('rowid'), false); + + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('rowid')); exit(); } -} -if ($confirm == 'yes') { - if ($action == 'confirm_delete') { - $db->begin(); + if ($action == 'addline' && $permissiontoedit) { + $line_ref = GETPOST('line_ref', 'alpha'); + $line_value = GETPOST('line_value', 'alpha'); - $res = $objectval->deleteByFkAttribute($object->id, $user); - - if ($res < 1 || ($object->delete($user) < 1)) { - $db->rollback(); - setEventMessages($langs->trans('CoreErrorMessage'), $object->errors, 'errors'); - header('Location: '.dol_buildpath('/variants/card.php?id='.$object->id, 2)); - } else { - $db->commit(); + $result = $object->addLine($line_ref, $line_value); + if ($result > 0) { setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); - header('Location: '.dol_buildpath('/variants/list.php', 2)); - } - exit(); - } elseif ($action == 'confirm_deletevalue') { - if ($objectval->fetch($valueid) > 0) { - if ($objectval->delete($user) < 1) { - setEventMessages($langs->trans('CoreErrorMessage'), $objectval->errors, 'errors'); - } else { - setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); - } - - header('Location: '.dol_buildpath('/variants/card.php?id='.$object->id, 2)); + header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $object->id); exit(); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $action = ''; + } + } elseif ($action == 'updateline' && $permissiontoedit) { + $line_ref = GETPOST('line_ref', 'alpha'); + $line_value = GETPOST('line_value', 'alpha'); + + $result = $object->updateLine($lineid, $line_ref, $line_value); + if ($result > 0) { + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); + header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $object->id); + exit(); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editline'; } } } @@ -132,171 +153,207 @@ if ($confirm == 'yes') { * View */ -$langs->load('products'); - -$help_url = 'EN:Module_Products#Variants'; - $title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label)); - +$help_url = 'EN:Module_Products#Variants'; llxHeader('', $title, $help_url); -//print load_fiche_titre($title); +// Part to create +if ($action == 'create') { + print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("ProductAttribute")), '', 'object_' . $object->picto); -$h = 0; -$head[$h][0] = DOL_URL_ROOT.'/variants/card.php?id='.$object->id; -$head[$h][1] = $langs->trans("ProductAttributeName"); -$head[$h][2] = 'variant'; -$h++; + print '
'; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } -print dol_get_fiche_head($head, 'variant', $langs->trans('ProductAttributeName'), -1, 'generic'); + print dol_get_fiche_head(array(), ''); -if ($action == 'edit') { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; -} + print '' . "\n"; + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; -if ($action != 'edit') { - print '
'; - print '
'; -} -print '
'; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''.$langs->trans('Label').''; -print ''; -print ''; + print '
'.$langs->trans('Ref').''; -if ($action == 'edit') { - print ''; -} else { - print dol_htmlentities($object->ref); -} -print '
'; -if ($action == 'edit') { - print ''; -} else { - print dol_htmlentities($object->label); -} -print '
' . "\n"; -print ''; + print dol_get_fiche_end(); - -if ($action != 'edit') { + print '
'; + print ''; + print '  '; + print ''; // Cancel for create does not post form if we don't know the backtopage print '
'; + + print '
'; + + dol_set_focus('input[name="label"]'); } -print dol_get_fiche_end(); +// Part to edit record +elseif (($id || $ref) && $action == 'edit') { + print load_fiche_titre($langs->trans("ProductAttribute"), '', 'object_' . $object->picto); -if ($action == 'edit') { - print '
'; - print '
'; - print ''; - print '   '; - print ''; - print '
'; - print '
'; -} else { - if ($action == 'delete') { - $form = new Form($db); - - print $form->formconfirm( - "card.php?id=".$object->id, - $langs->trans('Delete'), - $langs->trans('ProductAttributeDeleteDialog'), - "confirm_delete", - '', - 0, - 1 - ); - } elseif ($action == 'delete_value') { - if ($objectval->fetch($valueid) > 0) { - $form = new Form($db); - - print $form->formconfirm( - "card.php?id=".$object->id."&valueid=".$objectval->id, - $langs->trans('Delete'), - $langs->trans('ProductAttributeValueDeleteDialog', dol_htmlentities($objectval->value), dol_htmlentities($objectval->ref)), - "confirm_deletevalue", - '', - 0, - 1 - ); - } + print '
'; + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; } - ?> + print dol_get_fiche_head(); - + print '' . "\n"; + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; - trans("PossibleValues")); - - if ($action == 'edit_value') { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - - foreach ($objectval->fetchAllByProductAttribute($object->id) as $attrval) { - print ''; - if ($action == 'edit_value' && ($valueid == $attrval->id)) { - ?> - - - - - - - - '; - } print '
'.$langs->trans('Ref').''.$langs->trans('Value').'
- " class="button button-save"> -     - " class="button button-cancel"> - ref) ?>value) ?> - - -
'; - if ($action == 'edit_value') { - print '
'; + print dol_get_fiche_end(); + + print '
'; + print '   '; + print '
'; + + print ''; +} + +// Part to show record +elseif ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + $res = $object->fetch_optionals(); + + $head = productAttributePrepareHead($object); + print dol_get_fiche_head($head, 'card', $langs->trans("ProductAttribute"), -1, $object->picto); + + $formconfirm = ''; + + // Confirmation to delete + if ($action == 'delete') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMyObject'), $langs->trans('ProductAttributeDeleteDialog'), 'confirm_delete', '', 0, 1); + } elseif ($action == 'ask_deleteline') { + // Confirmation to delete line + $object_value = new ProductAttributeValue($db); + if ($object_value->fetch($lineid) > 0) { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteLine'), $langs->trans('ProductAttributeValueDeleteDialog', dol_htmlentities($object_value->value), dol_htmlentities($object_value->ref)), 'confirm_deleteline', '', 0, 1); + } } - print '
'; - print '
'; - print ''.$langs->trans('Create').''; + // Call Hook formConfirm + $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + // Object card + // ------------------------------------------------------------ + $backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT . '/variants/list.php?leftmenu=?restore_lastsearch_values=1'); + $linkback = '' . $langs->trans("BackToList") . ''; + + dol_banner_tab($object, 'id', $linkback); + + print '
'; + print '
'; + print '
'; + print '' . "\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + + print '
'; print '
'; print '
'; + + print '
'; + + print dol_get_fiche_end(); + + // Buttons for actions + if ($action != 'editline') { + print '
' . "\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + if (empty($reshook)) { + // Modify + print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=edit', '', $permissiontoedit); + + // Delete (need delete permission, or if draft, just need create/modify permission) + print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&action=delete', '', $permissiontodelete); + } + print '
' . "\n"; + } + + /* + * Lines + */ + if (!empty($object->table_element_line)) { + // Show object lines + $result = $object->getLinesArray(); + + print load_fiche_titre($langs->trans("PossibleValues") . (!empty($object->lines) ? ' (' . count($object->lines) . ')' : '')); + + print '
+ + + + + + '; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + if (!empty($conf->use_javascript_ajax)) { + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + } + + print '
'; + if (!empty($object->lines) || ($permissiontoedit && $action != 'selectlines' && $action != 'editline')) { + print ''; + } + + // Form to add new line + if ($permissiontoedit && $action != 'selectlines') { + if ($action != 'editline') { + // Add products/services form + + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if (empty($reshook)) + $object->formAddObjectLine(1, $mysoc, $soc); + } + } + + if (!empty($object->lines)) { + $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1); + } + + if (!empty($object->lines) || ($permissiontoedit && $action != 'selectlines' && $action != 'editline')) { + print '
'; + } + print '
'; + + print "
\n"; + } } // End of page diff --git a/htdocs/variants/class/ProductAttribute.class.php b/htdocs/variants/class/ProductAttribute.class.php index 1ba43a3f964..94aa87d6031 100644 --- a/htdocs/variants/class/ProductAttribute.class.php +++ b/htdocs/variants/class/ProductAttribute.class.php @@ -1,6 +1,7 @@ + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -28,115 +29,134 @@ class ProductAttribute extends CommonObject * @var DoliDB */ public $db; + /** + * @var string ID of module. + */ + public $module = 'variants'; /** - * Id of the product attribute - * @var int + * @var string ID to identify managed object. */ + public $element = 'productattribute'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'product_attribute'; + + /** + * @var string Name of sub table line + */ + public $table_element_line = 'product_attribute_value'; + + /** + * @var string Field with ID of parent key if this field has a parent or for child tables + */ + public $fk_element = 'fk_product_attribute'; + + /** + * @var int Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table + */ + public $ismultientitymanaged = 1; + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * @var string String with name of icon for conferenceorbooth. Must be the part after the 'object_' into object_conferenceorbooth.png + */ + public $picto = 'product'; + + /** + * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'picto' is code of a picto to show before value in forms + * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM) + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200' + * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1. + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"), + 'ref' => array('type'=>'varchar(255)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''), + 'ref_ext' => array('type' => 'varchar(255)', 'label' => 'ExternalRef', 'enabled' => 1, 'visible' => 0, 'position' => 20, 'searchall'=>1), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'help'=>"", 'showoncombobox'=>'1',), + 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>40, 'notnull'=>1,), + ); public $id; - - /** - * Ref of the product attribute - * @var string - */ public $ref; - - /** - * External ref of the product attribute - * @var string - */ public $ref_ext; - - /** - * Label of the product attribute - * @var string - */ public $label; + public $position; /** - * Order of attribute. - * Lower ones will be shown first and higher ones last - * @var int + * @var ProductAttributeValue[] */ - public $rang; - - public $position; + public $lines = array(); + /** + * @var ProductAttributeValue + */ + public $line; /** * Constructor * - * @param DoliDB $db Database handler + * @param DoliDb $db Database handler */ public function __construct(DoliDB $db) { - global $conf; + global $conf, $langs; $this->db = $db; $this->entity = $conf->entity; - } - /** - * Fetches the properties of a product attribute - * - * @param int $id Attribute id - * @return int <1 KO, >1 OK - */ - public function fetch($id) - { - if (!$id) { - return -1; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; } - $sql = "SELECT rowid, ref, ref_ext, label, position FROM ".MAIN_DB_PREFIX."product_attribute WHERE rowid = ".((int) $id)." AND entity IN (".getEntity('product').")"; - - $query = $this->db->query($sql); - - if (!$this->db->num_rows($query)) { - return -1; - } - - $obj = $this->db->fetch_object($query); - - $this->id = $obj->rowid; - $this->ref = $obj->ref; - $this->ref_ext = $obj->ref_ext; - $this->label = $obj->label; - $this->rang = $obj->position; - $this->position = $obj->position; - - return 1; - } - - /** - * Returns an array of all product variants - * - * @return ProductAttribute[] - */ - public function fetchAll() - { - $return = array(); - - $sql = 'SELECT rowid, ref, ref_ext, label, position FROM '.MAIN_DB_PREFIX."product_attribute WHERE entity IN (".getEntity('product').')'; - $sql .= $this->db->order('position', 'asc'); - $query = $this->db->query($sql); - if ($query) { - while ($result = $this->db->fetch_object($query)) { - $tmp = new ProductAttribute($this->db); - $tmp->id = $result->rowid; - $tmp->ref = $result->ref; - $tmp->ref_ext = $result->ref_ext; - $tmp->label = $result->label; - $tmp->rang = $result->position; - $tmp->position = $result->position; - - $return[] = $tmp; + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); } - } else { - dol_print_error($this->db); } - return $return; + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } } /** @@ -148,29 +168,165 @@ class ProductAttribute extends CommonObject */ public function create(User $user, $notrigger = 0) { - if (empty($notrigger)) { + global $langs; + $error = 0; + + // Clean parameters + $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase + $this->label = trim($this->label); + $this->position = $this->position > 0 ? $this->position : 0; + + // Position to use + if (empty($this->position)) { + $positionmax = $this->getMaxAttributesPosition(); + $this->position = $positionmax + 1; + } + + // Check parameters + if (empty($this->ref)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); + $error++; + } + if (empty($this->label)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $this->db->begin(); + + $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " ("; + $sql .= " ref, ref_ext, label, entity, position"; + $sql .= ")"; + $sql .= " VALUES ("; + $sql .= " '" . $this->db->escape($this->ref) . "'"; + $sql .= ", '" . $this->db->escape($this->ref_ext) . "'"; + $sql .= ", '" . $this->db->escape($this->label) . "'"; + $sql .= ", " . ((int) $this->entity); + $sql .= ", " . ((int) $this->position); + $sql .= ")"; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + $error++; + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + } + + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PRODUCT_ATTRIBUTE_CREATE', $user); if ($result < 0) { - return -1; + $error++; } // End call triggers } - //Ref must be uppercase - $this->ref = strtoupper($this->ref); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute (ref, ref_ext, label, entity, rang) - VALUES ('".$this->db->escape($this->ref)."', '".$this->db->escape($this->ref_ext)."', '".$this->db->escape($this->label)."', ".(int) $this->entity.", ".(int) $this->rang.")"; - - $query = $this->db->query($sql); - if ($query) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute'); - + if (!$error) { + $this->db->commit(); return $this->id; + } else { + $this->db->rollback(); + return -1 * $error; + } + } + + /** + * Fetches the properties of a product attribute + * + * @param int $id Attribute id + * @return int <1 KO, >1 OK + */ + public function fetch($id) + { + global $langs; + $error = 0; + + // Clean parameters + $id = $id > 0 ? $id : 0; + + // Check parameters + if (empty($id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; } - return -1; + $sql = "SELECT rowid, ref, ref_ext, label, position"; + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE rowid = " . ((int) $id); + $sql .= " AND entity IN (" . getEntity('product') . ")"; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $numrows = $this->db->num_rows($resql); + if ($numrows) { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->ref = $obj->ref; + $this->ref_ext = $obj->ref_ext; + $this->label = $obj->label; + $this->rang = $obj->position; // deprecated + $this->position = $obj->position; + } + $this->db->free($resql); + + return $numrows; + } + + /** + * Returns an array of all product variants + * + * @return ProductAttribute[] + */ + public function fetchAll() + { + $return = array(); + + $sql = "SELECT rowid, ref, ref_ext, label, position"; + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE entity IN (" . getEntity('product') . ")"; + $sql .= $this->db->order("position", "asc"); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + dol_print_error($this->db); + return $return; + } + + while ($obj = $this->db->fetch_object($resql)) { + $tmp = new ProductAttribute($this->db); + + $tmp->id = $obj->rowid; + $tmp->ref = $obj->ref; + $tmp->ref_ext = $obj->ref_ext; + $tmp->label = $obj->label; + $tmp->rang = $obj->position; // deprecated + $tmp->position = $obj->position; + + $return[] = $tmp; + } + + return $return; } /** @@ -182,26 +338,66 @@ class ProductAttribute extends CommonObject */ public function update(User $user, $notrigger = 0) { - if (empty($notrigger)) { + global $langs; + $error = 0; + + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; + $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase + $this->label = trim($this->label); + + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if (empty($this->ref)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); + $error++; + } + if (empty($this->label)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET"; + + $sql .= " ref = '" . $this->db->escape($this->ref) . "'"; + $sql .= ", ref_ext = '" . $this->db->escape($this->ref_ext) . "'"; + $sql .= ", label = '" . $this->db->escape($this->label) . "'"; + $sql .= ", position = " . ((int) $this->position); + + $sql .= " WHERE rowid = " . ((int) $this->id); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + $error++; + } + + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PRODUCT_ATTRIBUTE_MODIFY', $user); if ($result < 0) { - return -1; + $error++; } // End call triggers } - //Ref must be uppercase - $this->ref = trim(strtoupper($this->ref)); - $this->label = trim($this->label); - - $sql = "UPDATE ".MAIN_DB_PREFIX."product_attribute SET ref = '".$this->db->escape($this->ref)."', ref_ext = '".$this->db->escape($this->ref_ext)."', label = '".$this->db->escape($this->label)."', rang = ".(int) $this->rang." WHERE rowid = ".(int) $this->id; - - if ($this->db->query($sql)) { + if (!$error) { + $this->db->commit(); return 1; + } else { + $this->db->rollback(); + return -1 * $error; } - - return -1; } /** @@ -213,22 +409,298 @@ class ProductAttribute extends CommonObject */ public function delete(User $user, $notrigger = 0) { - if (empty($notrigger)) { + global $langs; + $error = 0; + + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; + + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $result = $this->isUsed(); + if ($result < 0) { + return -1; + } elseif ($result > 0) { + $this->errors[] = $langs->trans('ErrorAttributeIsUsedIntoProduct'); + return -1; + } + + $this->db->begin(); + + if (!$notrigger) { // Call trigger $result = $this->call_trigger('PRODUCT_ATTRIBUTE_DELETE', $user); if ($result < 0) { - return -1; + $error++; } // End call triggers } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute WHERE rowid = ".(int) $this->id; + if (!$error) { + // Delete values + $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element_line; + $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id); - if ($this->db->query($sql)) { - return 1; + dol_syslog(__METHOD__ . ' - Delete values', LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + $error++; + } } - return -1; + if (!$error) { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE rowid = " . ((int) $this->id); + + dol_syslog(__METHOD__ . ' - Delete attribute', LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + $error++; + } + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1 * $error; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Load array lines + * + * @param string $filters Filter on other fields + * + * @return int <0 if KO, >0 if OK + */ + public function fetch_lines($filters = '') + { + // phpcs:enable + global $langs; + $this->lines = array(); + $error = 0; + + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; + + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $sql = "SELECT td.rowid, td.fk_product_attribute, td.ref, td.value, td.position"; + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element_line . " AS td"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $this->table_element . " AS t ON t.rowid = td." . $this->fk_element; + $sql .= " WHERE t.rowid = " . ((int) $this->id); + $sql .= " AND t.entity IN (" . getEntity('product') . ")"; + if ($filters) { + $sql .= $filters; + } + $sql .= $this->db->order("td.position", "asc"); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -3; + } + + $num = $this->db->num_rows($resql); + if ($num) { + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + + $line = new ProductAttributeValue($this->db); + + $line->id = $obj->rowid; + $line->fk_product_attribute = $obj->fk_product_attribute; + $line->ref = $obj->ref; + $line->value = $obj->value; + $line->position = $obj->position; + + $this->lines[$i] = $line; + $i++; + } + } + $this->db->free($resql); + + return $num; + } + + /** + * Retrieve an array of proposal lines + * @param string $filters Filter on other fields + * + * @return int >0 if OK, <0 if KO + */ + public function getLinesArray($filters = '') + { + return $this->fetch_lines($filters); + } + + /** + * Add a proposal line into database (linked to product/service or not) + * The parameters are already supposed to be appropriate and with final values to the call + * of this method. Also, for the VAT rate, it must have already been defined + * by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product) + * and desc must already have the right value (it's up to the caller to manage multilanguage) + * + * @param string $ref Ref of the value + * @param string $value Value + * @param int $position Position of line + * @param int $notrigger disable line update trigger + * @return int >0 if OK, <0 if KO + */ + public function addLine($ref, $value, $position = -1, $notrigger = 0) + { + global $langs, $user; + dol_syslog(__METHOD__ . " id={$this->id}, ref=$ref, value=$value, notrigger=$notrigger"); + $error = 0; + + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; + + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $this->db->begin(); + + //Fetch current line from the database and then clone the object and set it in $oldcopy property + $this->line = new ProductAttributeValue($this->db); + + // Position to use + $positiontouse = $position; + if ($positiontouse == -1) { + $positionmax = $this->line_max(0); + $positiontouse = $positionmax + 1; + } + + $this->line->context = $this->context; + $this->line->fk_product_attribute = $this->id; + $this->line->ref = $ref; + $this->line->value = $value; + $this->line->position = $positiontouse; + + $result = $this->line->create($user, $notrigger); + + if ($result < 0) { + $this->error = $this->line->error; + $this->errors = $this->line->errors; + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return $this->line->id; + } + } + + + /** + * Update a line + * + * @param int $lineid Id of line + * @param string $ref Ref of the value + * @param string $value Value + * @param int $notrigger disable line update trigger + * @return int >=0 if OK, <0 if KO + */ + public function updateLine($lineid, $ref, $value, $notrigger = 0) + { + global $user; + + dol_syslog(__METHOD__ . " lineid=$lineid, ref=$ref, value=$value, notrigger=$notrigger"); + + // Clean parameters + $lineid = $lineid > 0 ? $lineid : 0; + + $this->db->begin(); + + //Fetch current line from the database and then clone the object and set it in $oldcopy property + $this->line = new ProductAttributeValue($this->db); + $result = $this->line->fetch($lineid); + if ($result > 0) { + $this->line->oldcopy = clone $this->line; + + $this->line->context = $this->context; + $this->line->ref = $ref; + $this->line->value = $value; + + $result = $this->line->update($user, $notrigger); + } + + if ($result < 0) { + $this->error = $this->line->error; + $this->errors = $this->line->errors; + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return $result; + } + } + + /** + * Delete a line + * + * @param User $user Object user + * @param int $lineid Id of line to delete + * @param int $notrigger disable line update trigger + * @return int >0 if OK, <0 if KO + */ + public function deleteLine(User $user, $lineid, $notrigger = 0) + { + dol_syslog(__METHOD__ . " lineid=$lineid, notrigger=$notrigger"); + + // Clean parameters + $lineid = $lineid > 0 ? $lineid : 0; + + $this->db->begin(); + + //Fetch current line from the database + $this->line = new ProductAttributeValue($this->db); + $result = $this->line->fetch($lineid); + if ($result > 0) { + $this->line->context = $this->context; + + $result = $this->line->delete($user, $notrigger); + } + + if ($result < 0) { + $this->error = $this->line->error; + $this->errors = $this->line->errors; + $this->db->rollback(); + return -1; + } else { + $this->db->commit(); + return $result; + } } /** @@ -238,12 +710,40 @@ class ProductAttribute extends CommonObject */ public function countChildValues() { - $sql = "SELECT COUNT(*) count FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE fk_product_attribute = ".(int) $this->id; + global $langs; + $error = 0; + $count = 0; - $query = $this->db->query($sql); - $result = $this->db->fetch_object($query); + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; - return $result->count; + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $sql = "SELECT COUNT(*) AS count"; + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element_line; + $sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + if ($obj = $this->db->fetch_object($resql)) { + $count = $obj->count; + } + + return $count; } /** @@ -253,140 +753,649 @@ class ProductAttribute extends CommonObject */ public function countChildProducts() { - $sql = "SELECT COUNT(*) count FROM ".MAIN_DB_PREFIX."product_attribute_combination2val pac2v - LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac2v.fk_prod_combination = pac.rowid WHERE pac2v.fk_prod_attr = ".((int) $this->id)." AND pac.entity IN (".getEntity('product').")"; + global $langs; + $error = 0; + $count = 0; - $query = $this->db->query($sql); + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; - $result = $this->db->fetch_object($query); - - return $result->count; - } - - - /** - * Reorders the order of the variants. - * This is an internal function used by moveLine function - * - * @return int <0 KO >0 OK - */ - protected function reorderLines() - { - global $user; - - $tmp_order = array(); - - $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'product_attribute WHERE rang = 0'; - $sql .= $this->db->order('rang, rowid', 'asc'); - - $query = $this->db->query($sql); - - if (!$query) { + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); return -1; } - while ($result = $this->db->fetch_object($query)) { - $tmp_order[] = $result->rowid; - } + $sql = "SELECT COUNT(*) AS count"; + $sql .= " FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val AS pac2v"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination AS pac ON pac2v.fk_prod_combination = pac.rowid"; + $sql .= " WHERE pac2v.fk_prod_attr = " . ((int) $this->id); + $sql .= " AND pac.entity IN (" . getEntity('product') . ")"; - foreach ($tmp_order as $order => $rowid) { - $tmp = new ProductAttribute($this->db); - $tmp->fetch($rowid); - $tmp->rang = $order + 1; - - if ($tmp->update($user) < 0) { - return -1; - } - } - - return 1; - } - - /** - * Internal function to handle moveUp and moveDown functions - * - * @param string $type up/down - * @return int <0 KO >0 OK - */ - private function moveLine($type) - { - global $user; - - if ($this->reorderLines() < 0) { + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); return -1; } - $this->db->begin(); + if ($obj = $this->db->fetch_object($resql)) { + $count = $obj->count; + } - if ($type == 'up') { - $newrang = $this->rang - 1; + return $count; + } + + /** + * Test if used by a product + * + * @return int <0 KO, =0 if No, =1 if Yes + */ + public function isUsed() + { + global $langs; + $error = 0; + + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; + + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $sql = "SELECT COUNT(*) AS nb FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_attr = " . ((int) $this->id); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + return -1; + } + + $used = 0; + if ($obj = $this->db->fetch_object($resql)) { + $used = $obj->nb; + } + + return $used ? 1 : 0; + } + + /** + * Save a new position (field position) for details lines. + * You can choose to set position for lines with already a position or lines without any position defined. + * + * @param boolean $renum True to renum all already ordered lines, false to renum only not already ordered lines. + * @param string $rowidorder ASC or DESC + * @return int <0 if KO, >0 if OK + */ + public function attributeOrder($renum = false, $rowidorder = 'ASC') + { + // Count number of attributes to reorder (according to choice $renum) + $nl = 0; + $sql = "SELECT count(rowid) FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE entity IN (" . getEntity('product') . ")"; + if (!$renum) { + $sql .= " AND position = 0"; } else { - $newrang = $this->rang + 1; + $sql .= " AND position <> 0"; } - $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_attribute SET rang = '.((int) $this->rang).' WHERE rang = '.((int) $newrang); + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $row = $this->db->fetch_row($resql); + $nl = $row[0]; + } else { + dol_print_error($this->db); + } + if ($nl > 0) { + // The goal of this part is to reorder all attributes. + $rows = array(); + // We first search all attributes + $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE entity IN (" . getEntity('product') . ")"; + $sql .= " ORDER BY position ASC, rowid " . $rowidorder; + + dol_syslog(__METHOD__ . " search all attributes", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $i = 0; + $num = $this->db->num_rows($resql); + while ($i < $num) { + $row = $this->db->fetch_row($resql); + $rows[] = $row[0]; // Add attributes into array rows + $i++; + } + + // Now we set a new number for each attributes + if (!empty($rows)) { + foreach ($rows as $key => $row) { + $this->updatePositionOfAttribute($row, ($key + 1)); + } + } + } else { + dol_print_error($this->db); + } + } + return 1; + } + + /** + * Update position of line (rang) + * + * @param int $rowid Id of line + * @param int $position Position + * @return int <0 if KO, >0 if OK + */ + public function updatePositionOfAttribute($rowid, $position) + { + global $hookmanager; + + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position); + $sql .= " WHERE rowid = " . ((int) $rowid); + + dol_syslog(__METHOD__, LOG_DEBUG); if (!$this->db->query($sql)) { - $this->db->rollback(); + dol_print_error($this->db); return -1; + } else { + $parameters = array('rowid' => $rowid, 'position' => $position); + $action = ''; + $reshook = $hookmanager->executeHooks('afterPositionOfAttributeUpdate', $parameters, $this, $action); + return 1; + } + } + + /** + * Get position of attribute + * + * @param int $rowid Id of line + * @return int Value of position in table of attributes + */ + public function getPositionOfAttribute($rowid) + { + $sql = "SELECT position FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE entity IN (" . getEntity('product') . ")"; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $row = $this->db->fetch_row($resql); + return $row[0]; } - $this->rang = $newrang; - - if ($this->update($user) < 0) { - $this->db->rollback(); - return -1; - } - - $this->db->commit(); - return 1; + return 0; } /** - * Shows this attribute before others + * Update a attribute to have a higher position * - * @return int <0 KO >0 OK + * @param int $rowid Id of line + * @return int <0 KO >0 OK */ - public function moveUp() + public function attributeMoveUp($rowid) { - return $this->moveLine('up'); + $this->attributeOrder(false, 'ASC'); + + // Get position of attribute + $position = $this->getPositionOfAttribute($rowid); + + // Update position of attribute + $this->updateAttributePositionUp($rowid, $position); } /** - * Shows this attribute after others + * Update a attribute to have a lower position * - * @return int <0 KO >0 OK + * @param int $rowid Id of line + * @return int <0 KO >0 OK */ - public function moveDown() + public function attributeMoveDown($rowid) { - return $this->moveLine('down'); + $this->attributeOrder(false, 'ASC'); + + // Get position of line + $position = $this->getPositionOfAttribute($rowid); + + // Get max value for position + $max = $this->getMaxAttributesPosition(); + + // Update position of attribute + $this->updateAttributePositionDown($rowid, $position, $max); } /** - * Updates the order of all variants. Used by AJAX page for drag&drop + * Update position of attribute (up) * - * @param DoliDB $db Database handler - * @param array $order Array with row id ordered in ascendent mode - * @return int <0 KO >0 OK + * @param int $rowid Id of line + * @param int $position Position + * @return void */ - public static function bulkUpdateOrder(DoliDB $db, array $order) + public function updateAttributePositionUp($rowid, $position) { - global $user; - - $tmp = new ProductAttribute($db); - - foreach ($order as $key => $attrid) { - if ($tmp->fetch($attrid) < 0) { - return -1; + if ($position > 1) { + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position); + $sql .= " WHERE entity IN (" . getEntity('product') . ")"; + $sql .= " AND position = " . ((int) ($position - 1)); + if ($this->db->query($sql)) { + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) ($position - 1)); + $sql .= " WHERE rowid = " . ((int) $rowid); + if (!$this->db->query($sql)) { + dol_print_error($this->db); + } + } else { + dol_print_error($this->db); } + } + } - $tmp->rang = $key; + /** + * Update position of attribute (down) + * + * @param int $rowid Id of line + * @param int $position Position + * @param int $max Max + * @return void + */ + public function updateAttributePositionDown($rowid, $position, $max) + { + if ($position < $max) { + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position); + $sql .= " WHERE entity IN (" . getEntity('product') . ")"; + $sql .= " AND position = " . ((int) ($position + 1)); + if ($this->db->query($sql)) { + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) ($position + 1)); + $sql .= " WHERE rowid = " . ((int) $rowid); + if (!$this->db->query($sql)) { + dol_print_error($this->db); + } + } else { + dol_print_error($this->db); + } + } + } - if ($tmp->update($user) < 0) { - return -1; + /** + * Get max value used for position of attributes + * + * @return int Max value of position in table of attributes + */ + public function getMaxAttributesPosition() + { + // Search the last position of attributes + $sql = "SELECT max(position) FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE entity IN (" . getEntity('product') . ")"; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $row = $this->db->fetch_row($resql); + return $row[0]; + } + + return 0; + } + + /** + * Update position of attributes with ajax + * + * @param array $rows Array of rows + * @return void + */ + public function attributesAjaxOrder($rows) + { + $num = count($rows); + for ($i = 0; $i < $num; $i++) { + $this->updatePositionOfAttribute($rows[$i], ($i + 1)); + } + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $conf, $langs, $hookmanager; + + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } + + $result = ''; + + $label = img_picto('', $this->picto) . ' ' . $langs->trans("ProductAttribute") . ''; + if (isset($this->status)) { + $label .= ' ' . $this->getLibStatut(5); + } + $label .= '
'; + $label .= '' . $langs->trans('Ref') . ': ' . $this->ref; + if (!empty($this->label)) { + $label .= '
' . $langs->trans('Label') . ': ' . $this->label; + } + + $url = dol_buildpath('/variants/card.php', 1) . '?id=' . $this->id; + + if ($option != 'nolink') { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($url && $add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; } } - return 1; + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowProductAttribute"); + $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"'; + } + $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"'; + $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"'; + } else { + $linkclose = ($morecss ? ' class="' . $morecss . '"' : ''); + } + + if ($option == 'nolink' || empty($url)) { + $linkstart = ''; + if ($option == 'nolink' || empty($url)) { + $linkend = ''; + } else { + $linkend = ''; + } + + $result .= $linkstart; + + if (empty($this->showphoto_on_popup)) { + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + } else { + if ($withpicto) { + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + list($class, $module) = explode('@', $this->picto); + $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref); + $filearray = dol_dir_list($upload_dir, "files"); + $filename = $filearray[0]['name']; + if (!empty($filename)) { + $pospoint = strpos($filearray[0]['name'], '.'); + + $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint); + if (empty($conf->global->{strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS'})) { + $result .= '
No photo
'; + } else { + $result .= '
No photo
'; + } + + $result .= '
'; + } else { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + } + } + + if ($withpicto != 2) { + $result .= $this->ref; + } + + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + global $action, $hookmanager; + $hookmanager->initHooks(array('variantsdao')); + $parameters = array('id' => $this->id, 'getnomurl' => $result); + $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } + + return $result; } + + /** + * Return the label of the status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLabelStatus($mode = 0) + { + return $this->LibStatut(0, $mode); + } + + /** + * Return label of status of product attribute + * + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut(0, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return label of a status + * + * @param int $status Id status + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label + */ + public function LibStatut($status, $mode = 1) + { + // phpcs:enable + return ''; + } + + // -------------------- + // TODO: All functions here must be redesigned and moved as they are not business functions but output functions + // -------------------- + + /* This is to show add lines */ + + /** + * Show add free and predefined products/services form + * + * @param int $dateSelector 1=Show also date range input fields + * @param Societe $seller Object thirdparty who sell + * @param Societe $buyer Object thirdparty who buy + * @param string $defaulttpldir Directory where to find the template + * @return void + */ + public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/variants/tpl') + { + global $conf, $user, $langs, $object, $hookmanager; + global $form; + + // Output template part (modules that overwrite templates must declare this into descriptor) + // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'. + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { + if (!empty($module)) { + $tpl = dol_buildpath($reldir . '/productattributevalueline_create.tpl.php'); + } else { + $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_create.tpl.php'; + } + + if (empty($conf->file->strict_mode)) { + $res = @include $tpl; + } else { + $res = include $tpl; // for debug + } + if ($res) { + break; + } + } + } + + /* This is to show array of line of details */ + + /** + * Return HTML table for object lines + * TODO Move this into an output class file (htmlline.class.php) + * If lines are into a template, title must also be into a template + * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. + * + * @param string $action Action code + * @param string $seller Object of seller third party + * @param string $buyer Object of buyer third party + * @param int $selected Object line selected + * @param int $dateSelector 1=Show also date range input fields + * @param string $defaulttpldir Directory where to find the template + * @return void + */ + public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/variants/tpl') + { + global $conf, $hookmanager, $langs, $user, $form, $object; + // TODO We should not use global var for this + global $disableedit, $disablemove, $disableremove; + + $num = count($this->lines); + + $parameters = array('num' => $num, 'selected' => $selected, 'table_element_line' => $this->table_element_line); + $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) { + // Output template part (modules that overwrite templates must declare this into descriptor) + // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook. + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { + if (!empty($module)) { + $tpl = dol_buildpath($reldir . '/productattributevalueline_title.tpl.php'); + } else { + $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_title.tpl.php'; + } + if (empty($conf->file->strict_mode)) { + $res = @include $tpl; + } else { + $res = include $tpl; // for debug + } + if ($res) { + break; + } + } + } + + $i = 0; + + print "\n"; + foreach ($this->lines as $line) { + if (is_object($hookmanager)) { // Old code is commented on preceding line. + $parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'selected' => $selected, 'table_element_line' => $line->table_element); + $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + } + if (empty($reshook)) { + $this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, null, $defaulttpldir); + } + + $i++; + } + print "\n"; + } + + /** + * Return HTML content of a detail line + * TODO Move this into an output class file (htmlline.class.php) + * + * @param string $action GET/POST action + * @param CommonObjectLine $line Selected object line to output + * @param string $var Is it a an odd line (true) + * @param int $num Number of line (0) + * @param int $i I + * @param int $dateSelector 1=Show also date range input fields + * @param string $seller Object of seller third party + * @param string $buyer Object of buyer third party + * @param int $selected Object line selected + * @param Extrafields $extrafields Object of extrafields + * @param string $defaulttpldir Directory where to find the template (deprecated) + * @return void + */ + public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/variants/tpl') + { + global $conf, $langs, $user, $object, $hookmanager; + global $form; + global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this ! + + $object_rights = $user->rights->produit->lire || $user->rights->service->lire; + + // Line in view mode + if ($action != 'editline' || $selected != $line->id) { + // Output template part (modules that overwrite templates must declare this into descriptor) + // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine. + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { + if (!empty($module)) { + $tpl = dol_buildpath($reldir . '/productattributevalueline_view.tpl.php'); + } else { + $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_view.tpl.php'; + } + + if (empty($conf->file->strict_mode)) { + $res = @include $tpl; + } else { + $res = include $tpl; // for debug + } + if ($res) { + break; + } + } + } + + // Line in update mode + if ($action == 'editline' && $selected == $line->id) { + // Output template part (modules that overwrite templates must declare this into descriptor) + // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine. + $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); + foreach ($dirtpls as $module => $reldir) { + if (!empty($module)) { + $tpl = dol_buildpath($reldir . '/productattributevalueline_edit.tpl.php'); + } else { + $tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_edit.tpl.php'; + } + + if (empty($conf->file->strict_mode)) { + $res = @include $tpl; + } else { + $res = include $tpl; // for debug + } + if ($res) { + break; + } + } + } + } + + /* This is to show array of line of details of source object */ } diff --git a/htdocs/variants/class/ProductAttributeValue.class.php b/htdocs/variants/class/ProductAttributeValue.class.php index 5ee341526bb..9d98f9a7f2b 100644 --- a/htdocs/variants/class/ProductAttributeValue.class.php +++ b/htdocs/variants/class/ProductAttributeValue.class.php @@ -1,6 +1,7 @@ + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,42 +17,79 @@ * along with this program. If not, see . */ -require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; /** * Class ProductAttributeValue * Used to represent a product attribute value */ -class ProductAttributeValue extends CommonObject +class ProductAttributeValue extends CommonObjectLine { /** - * Database handler - * @var DoliDB + * @var string ID of module. */ - public $db; + public $module = 'variants'; /** - * Attribute value id - * @var int + * @var string ID to identify managed object. */ + public $element = 'productattributevalue'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'product_attribute_value'; + + /** + * @var int Does this object support multicompany module ? + * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table + */ + public $ismultientitymanaged = 1; + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'picto' is code of a picto to show before value in forms + * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM) + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200' + * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1. + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"), + 'fk_product_attribute' => array('type'=>'integer:ProductAttribute:variants/class/ProductAttribute.class.php', 'label'=>'ProductAttribute', 'enabled'=>1, 'visible'=>0, 'position'=>10, 'notnull'=>1, 'index'=>1,), + 'ref' => array('type'=>'varchar(255)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''), + 'value' => array('type'=>'varchar(255)', 'label'=>'Value', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'help'=>"", 'showoncombobox'=>'1',), + 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,), + ); public $id; - - /** - * Product attribute id - * @var int - */ public $fk_product_attribute; - - /** - * Attribute value ref - * @var string - */ public $ref; - - /** - * Attribute value value - * @var string - */ public $value; + public $position; /** * Constructor @@ -60,40 +98,163 @@ class ProductAttributeValue extends CommonObject */ public function __construct(DoliDB $db) { - global $conf; + global $conf, $langs; $this->db = $db; $this->entity = $conf->entity; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } + + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); + } + } + + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Creates a value for a product attribute + * + * @param User $user Object user + * @param int $notrigger Do not execute trigger + * @return int <0 KO >0 OK + */ + public function create(User $user, $notrigger = 0) + { + global $langs; + $error = 0; + + // Clean parameters + $this->fk_product_attribute = $this->fk_product_attribute > 0 ? $this->fk_product_attribute : 0; + $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase + $this->value = trim($this->value); + + // Check parameters + if (empty($this->fk_product_attribute)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductAttribute")); + $error++; + } + if (empty($this->ref)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); + $error++; + } + if (empty($this->value)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Value")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $this->db->begin(); + + $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " ("; + $sql .= " fk_product_attribute, ref, value, entity, position"; + $sql .= ")"; + $sql .= " VALUES ("; + $sql .= " " . ((int) $this->fk_product_attribute); + $sql .= ", '" . $this->db->escape($this->ref) . "'"; + $sql .= ", '" . $this->db->escape($this->value) . "'"; + $sql .= ", " . ((int) $this->entity); + $sql .= ", " . ((int) $this->position); + $sql .= ")"; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + $error++; + } + + if (!$error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element); + } + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_CREATE', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + + if ($error) { + $this->db->rollback(); + return -1 * $error; + } else { + $this->db->commit(); + return $this->id; + } } /** * Gets a product attribute value * - * @param int $valueid Product attribute value id + * @param int $id Product attribute value id * @return int <0 KO, >0 OK */ - public function fetch($valueid) + public function fetch($id) { - $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE rowid = ".(int) $valueid." AND entity IN (".getEntity('product').")"; + global $langs; + $error = 0; - $query = $this->db->query($sql); + // Clean parameters + $id = $id > 0 ? $id : 0; - if (!$query) { + // Check parameters + if (empty($id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); return -1; } - if (!$this->db->num_rows($query)) { + $sql = "SELECT rowid, fk_product_attribute, ref, value"; + $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql .= " WHERE rowid = " . ((int) $id); + $sql .= " AND entity IN (" . getEntity('product') . ")"; + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); return -1; } - $obj = $this->db->fetch_object($query); + $numrows = $this->db->num_rows($resql); + if ($numrows) { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->fk_product_attribute = $obj->fk_product_attribute; - $this->ref = $obj->ref; - $this->value = $obj->value; + $this->id = $obj->rowid; + $this->fk_product_attribute = $obj->fk_product_attribute; + $this->ref = $obj->ref; + $this->value = $obj->value; + } + $this->db->free($resql); - return 1; + return $numrows; } /** @@ -107,24 +268,24 @@ class ProductAttributeValue extends CommonObject { $return = array(); - $sql = 'SELECT '; + $sql = "SELECT "; if ($only_used) { - $sql .= 'DISTINCT '; + $sql .= "DISTINCT "; } - $sql .= 'v.fk_product_attribute, v.rowid, v.ref, v.value FROM '.MAIN_DB_PREFIX.'product_attribute_value v '; + $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM " . MAIN_DB_PREFIX . "product_attribute_value v "; if ($only_used) { - $sql .= 'LEFT JOIN '.MAIN_DB_PREFIX.'product_attribute_combination2val c2v ON c2v.fk_prod_attr_val = v.rowid '; - $sql .= 'LEFT JOIN '.MAIN_DB_PREFIX.'product_attribute_combination c ON c.rowid = c2v.fk_prod_combination '; - $sql .= 'LEFT JOIN '.MAIN_DB_PREFIX.'product p ON p.rowid = c.fk_product_child '; + $sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination2val c2v ON c2v.fk_prod_attr_val = v.rowid "; + $sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination c ON c.rowid = c2v.fk_prod_combination "; + $sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product p ON p.rowid = c.fk_product_child "; } - $sql .= 'WHERE v.fk_product_attribute = '.(int) $prodattr_id; + $sql .= "WHERE v.fk_product_attribute = " . ((int) $prodattr_id); if ($only_used) { - $sql .= ' AND c2v.rowid IS NOT NULL AND p.tosell = 1'; + $sql .= " AND c2v.rowid IS NOT NULL AND p.tosell = 1"; } $query = $this->db->query($sql); @@ -142,45 +303,6 @@ class ProductAttributeValue extends CommonObject return $return; } - /** - * Creates a value for a product attribute - * - * @param User $user Object user - * @param int $notrigger Do not execute trigger - * @return int <0 KO >0 OK - */ - public function create(User $user, $notrigger = 0) - { - if (!$this->fk_product_attribute) { - return -1; - } - - // Ref must be uppercase - $this->ref = strtoupper($this->ref); - $this->value = $this->db->escape($this->value); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute_value (fk_product_attribute, ref, value, entity) - VALUES (".(int) $this->fk_product_attribute.", '".$this->db->escape($this->ref)."', '".$this->db->escape($this->value)."', ".(int) $this->entity.")"; - - $query = $this->db->query($sql); - - if ($query) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute_value'); - if (empty($notrigger)) { - // Call trigger - $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_CREATE', $user); - if ($result < 0) { - return -1; - } - // End call triggers - } - - return 1; - } - - return -1; - } - /** * Updates a product attribute value * @@ -190,28 +312,66 @@ class ProductAttributeValue extends CommonObject */ public function update(User $user, $notrigger = 0) { - if (empty($notrigger)) { + global $langs; + $error = 0; + + // Clean parameters + $this->fk_product_attribute = $this->fk_product_attribute > 0 ? $this->fk_product_attribute : 0; + $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase + $this->value = trim($this->value); + + // Check parameters + if (empty($this->fk_product_attribute)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductAttribute")); + $error++; + } + if (empty($this->ref)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")); + $error++; + } + if (empty($this->value)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Value")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET"; + + $sql .= " fk_product_attribute = " . ((int) $this->fk_product_attribute); + $sql .= ", ref = '" . $this->db->escape($this->ref) . "'"; + $sql .= ", value = '" . $this->db->escape($this->value) . "'"; + $sql .= ", position = " . ((int) $this->position); + + $sql .= " WHERE rowid = " . ((int) $this->id); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + $error++; + } + + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_MODIFY', $user); if ($result < 0) { - return -1; + $error++; } // End call triggers } - //Ref must be uppercase - $this->ref = trim(strtoupper($this->ref)); - $this->value = trim($this->value); - - $sql = "UPDATE ".MAIN_DB_PREFIX."product_attribute_value - SET fk_product_attribute = '".(int) $this->fk_product_attribute."', ref = '".$this->db->escape($this->ref)."', - value = '".$this->db->escape($this->value)."' WHERE rowid = ".(int) $this->id; - - if ($this->db->query($sql)) { + if (!$error) { + $this->db->commit(); return 1; + } else { + $this->db->rollback(); + return -1 * $error; } - - return -1; } /** @@ -223,56 +383,98 @@ class ProductAttributeValue extends CommonObject */ public function delete(User $user, $notrigger = 0) { + global $langs; + $error = 0; - if (empty($notrigger)) { - // Call trigger - $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_DELETE', $user); - if ($result < 0) { - return -1; - } - // End call triggers + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; + + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; } - $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE rowid = ".(int) $this->id; - if ($this->db->query($sql)) { - return 1; - } - - return -1; - } - - /** - * Deletes all product attribute values by a product attribute id - * - * @param int $fk_attribute Product attribute id - * @param User $user Object user - * @return int <0 KO, >0 OK - */ - public function deleteByFkAttribute($fk_attribute, User $user) - { - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE fk_product_attribute = ".(int) $fk_attribute; - - $query = $this->db->query($sql); - - if (!$query) { + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); return -1; } - if (!$this->db->num_rows($query)) { - return 1; + $result = $this->isUsed(); + if ($result < 0) { + return -1; + } elseif ($result > 0) { + $this->errors[] = $langs->trans('ErrorAttributeValueIsUsedIntoProduct'); + return -1; } - while ($obj = $this->db->fetch_object($query)) { - $tmp = new ProductAttributeValue($this->db); - if ($tmp->fetch($obj->rowid) > 0) { - $result = $tmp->delete($user); - if ($result < 0) { - return -1; - } - } else { - return -1; + $this->db->begin(); + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_DELETE', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } + + if (!$error) { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element . " WHERE rowid = " . ((int) $this->id); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + $error++; } } - return 1; + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1 * $error; + } + } + + /** + * Test if used by a product + * + * @return int <0 KO, =0 if No, =1 if Yes + */ + public function isUsed() + { + global $langs; + $error = 0; + + // Clean parameters + $this->id = $this->id > 0 ? $this->id : 0; + + // Check parameters + if (empty($this->id)) { + $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID")); + $error++; + } + if ($error) { + dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR); + return -1; + } + + $sql = "SELECT COUNT(*) AS nb FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_attr_val = " . ((int) $this->id); + + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = "Error " . $this->db->lasterror(); + return -1; + } + + $used = 0; + if ($obj = $this->db->fetch_object($resql)) { + $used = $obj->nb; + } + + return $used ? 1 : 0; } } diff --git a/htdocs/variants/class/ProductCombination.class.php b/htdocs/variants/class/ProductCombination.class.php index bb6372fd5eb..a418d3c9e32 100644 --- a/htdocs/variants/class/ProductCombination.class.php +++ b/htdocs/variants/class/ProductCombination.class.php @@ -2,6 +2,7 @@ /* Copyright (C) 2016 Marcos García * Copyright (C) 2018 Juanjo Menent + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -628,12 +629,12 @@ class ProductCombination $variants = array(); //Attributes - $sql = "SELECT DISTINCT fk_prod_attr, a.rang"; + $sql = "SELECT DISTINCT fk_prod_attr, a.position"; $sql .= " FROM ".MAIN_DB_PREFIX."product_attribute_combination2val c2v LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination c ON c2v.fk_prod_combination = c.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product p ON p.rowid = c.fk_product_child"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute a ON a.rowid = fk_prod_attr"; $sql .= " WHERE c.fk_product_parent = ".((int) $productid)." AND p.tosell = 1"; - $sql .= $this->db->order('a.rang', 'asc'); + $sql .= $this->db->order('a.position', 'asc'); $query = $this->db->query($sql); diff --git a/htdocs/variants/class/ProductCombination2ValuePair.class.php b/htdocs/variants/class/ProductCombination2ValuePair.class.php index 0d23910b703..27406cdfc75 100644 --- a/htdocs/variants/class/ProductCombination2ValuePair.class.php +++ b/htdocs/variants/class/ProductCombination2ValuePair.class.php @@ -1,6 +1,7 @@ + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -69,8 +70,8 @@ class ProductCombination2ValuePair */ public function __toString() { - require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php'; - require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php'; + require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttributeValue.class.php'; + require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttribute.class.php'; $prodattr = new ProductAttribute($this->db); $prodattrval = new ProductAttributeValue($this->db); @@ -78,7 +79,7 @@ class ProductCombination2ValuePair $prodattr->fetch($this->fk_prod_attr); $prodattrval->fetch($this->fk_prod_attr_val); - return $prodattr->label.': '.$prodattrval->value; + return $prodattr->label . ': ' . $prodattrval->value; } /** @@ -87,14 +88,14 @@ class ProductCombination2ValuePair */ public function create() { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute_combination2val + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_attribute_combination2val (fk_prod_combination, fk_prod_attr, fk_prod_attr_val) - VALUES(".(int) $this->fk_prod_combination.", ".(int) $this->fk_prod_attr.", ".(int) $this->fk_prod_attr_val.")"; + VALUES(" . (int) $this->fk_prod_combination . ", " . (int) $this->fk_prod_attr . ", " . (int) $this->fk_prod_attr_val . ")"; $query = $this->db->query($sql); if ($query) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute_combination2val'); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . 'product_attribute_combination2val'); return 1; } @@ -115,10 +116,10 @@ class ProductCombination2ValuePair c2v.fk_prod_attr_val, c2v.fk_prod_attr, c2v.fk_prod_combination - FROM ".MAIN_DB_PREFIX."product_attribute c LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination2val c2v ON c.rowid = c2v.fk_prod_attr - WHERE c2v.fk_prod_combination = ".(int) $fk_combination; + FROM " . MAIN_DB_PREFIX . "product_attribute c LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination2val c2v ON c.rowid = c2v.fk_prod_attr + WHERE c2v.fk_prod_combination = " . (int) $fk_combination; - $sql .= $this->db->order('c.rang', 'asc'); + $sql .= $this->db->order('c.position', 'asc'); $query = $this->db->query($sql); @@ -149,7 +150,7 @@ class ProductCombination2ValuePair */ public function deleteByFkCombination($fk_combination) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute_combination2val WHERE fk_prod_combination = ".(int) $fk_combination; + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_combination = " . (int) $fk_combination; if ($this->db->query($sql)) { return 1; diff --git a/htdocs/variants/combinations.php b/htdocs/variants/combinations.php index 64fa6b08b93..2284a496c0f 100644 --- a/htdocs/variants/combinations.php +++ b/htdocs/variants/combinations.php @@ -2,6 +2,7 @@ /* Copyright (C) 2016 Marcos García * Copyright (C) 2017 Laurent Destailleur * Copyright (C) 2018-2019 Frédéric France + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -50,6 +51,7 @@ $confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); $cancel = GETPOST('cancel', 'alpha'); $delete_product = GETPOST('delete_product', 'alpha'); +$subaction = GETPOST('subaction', 'aZ09'); // Security check $fieldvalue = (!empty($id) ? $id : $ref); @@ -106,8 +108,19 @@ if ($action == 'add') { } if ($action == 'create' && GETPOST('selectvariant', 'alpha')) { // We click on select combination $action = 'add'; - if (GETPOST('attribute') != '-1' && GETPOST('value') != '-1') { - $selectedvariant[GETPOST('attribute').':'.GETPOST('value')] = GETPOST('attribute').':'.GETPOST('value'); + $attribute_id = GETPOST('attribute', 'int'); + $attribute_value_id = GETPOST('value', 'int'); + if ($attribute_id> 0 && $attribute_value_id > 0) { + $feature = $attribute_id . '-' . $attribute_value_id; + $selectedvariant[$feature] = $feature; + $_SESSION['addvariant_'.$object->id] = $selectedvariant; + } +} +if ($action == 'create' && $subaction == 'delete') { // We click on select combination + $action = 'add'; + $feature = GETPOST('feature', 'intcomma'); + if (isset($selectedvariant[$feature])) { + unset($selectedvariant[$feature]); $_SESSION['addvariant_'.$object->id] = $selectedvariant; } } @@ -118,7 +131,7 @@ $prodcomb2val = new ProductCombination2ValuePair($db); $productCombination2ValuePairs1 = array(); -if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha')) { // We click on Create all defined combinations +if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha') && empty($subaction)) { // We click on Create all defined combinations //$features = GETPOST('features', 'array'); $features = $_SESSION['addvariant_'.$object->id]; @@ -146,13 +159,8 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST( //First, sanitize foreach ($features as $feature) { - $explode = explode(':', $feature); - - if ($prodattr->fetch($explode[0]) < 0) { - continue; - } - - if ($prodattr_val->fetch($explode[1]) < 0) { + $explode = explode('-', $feature); + if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) { continue; } @@ -460,19 +468,16 @@ if (!empty($id) || !empty($ref)) { //First, sanitize $listofvariantselected = '
'; if (!empty($features)) { + $toprint = array(); foreach ($features as $feature) { - $explode = explode(':', $feature); - - if ($prodattr->fetch($explode[0]) < 0) { + $explode = explode('-', $feature); + if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) { continue; } - - if ($prodattr_val->fetch($explode[1]) < 0) { - continue; - } - - $listofvariantselected .= ''.$prodattr->label.':'.$prodattr_val->value.' '; + $toprint[] = '
  • ' . $prodattr->label.' : '.$prodattr_val->value . + ' ' . img_delete() . '
  • '; } + $listofvariantselected .= '
      ' . implode(' ', $toprint) . '
    '; } $listofvariantselected .= '
    '; //print dol_get_fiche_end(); @@ -572,9 +577,8 @@ if (!empty($id) || !empty($ref)) { print load_fiche_titre($title); - print '
    '."\n"; + print ''."\n"; print ''; - print ''."\n"; print ''."\n"; if ($valueid > 0) { print ''."\n"; @@ -820,10 +824,9 @@ if (!empty($id) || !empty($ref)) { // List of variants - print ''; + print ''; print ''; print ''; - print ''; print ''; // List of mass actions available diff --git a/htdocs/variants/create.php b/htdocs/variants/create.php deleted file mode 100644 index f87ad3ef504..00000000000 --- a/htdocs/variants/create.php +++ /dev/null @@ -1,115 +0,0 @@ - - * Copyright (C) 2018 Frédéric France - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php'; - -$ref = GETPOST('ref', 'alpha'); -$label = GETPOST('label', 'alpha'); -$backtopage = GETPOST('backtopage', 'alpha'); -$action = GETPOST('action', 'alpha'); - -$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; - -// Security check -if (empty($conf->variants->enabled)) { - accessforbidden('Module not enabled'); -} -if ($user->socid > 0) { // Protection if external user - accessforbidden(); -} -//$result = restrictedArea($user, 'variant'); -if (!$permissiontoread) accessforbidden(); - - -/* - * Actions - */ - -if ($action == 'add') { - if (empty($ref) || empty($label)) { - setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors'); - } else { - $prodattr = new ProductAttribute($db); - $prodattr->label = $label; - $prodattr->ref = $ref; - - $resid = $prodattr->create($user); - if ($resid > 0) { - setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); - if ($backtopage) { - header('Location: '.$backtopage); - } else { - header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$resid.'&backtopage='.urlencode($backtopage)); - } - exit; - } else { - setEventMessages($langs->trans('ErrorRecordAlreadyExists'), $prodattr->errors, 'errors'); - } - } -} - -$langs->load('products'); - - -/* - * View - */ - -$help_url = 'EN:Module_Products#Variants'; - -$title = $langs->trans('NewProductAttribute'); - -llxHeader('', $title, $help_url); - - -print load_fiche_titre($title); - -print dol_get_fiche_head(); - -print ''; -print ''; -print ''; -print ''; - -?> - - - - - - - - - - - -
    trans("VariantRefExample"); ?> -
    trans("VariantLabelExample"); ?> -
    - -
    '; - -print ''; - -// End of page -llxFooter(); -$db->close(); diff --git a/htdocs/variants/create_val.php b/htdocs/variants/create_val.php deleted file mode 100644 index 1ca647960e2..00000000000 --- a/htdocs/variants/create_val.php +++ /dev/null @@ -1,161 +0,0 @@ - - * Copyright (C) 2018 Frédéric France - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -require '../main.inc.php'; -require 'class/ProductAttribute.class.php'; -require 'class/ProductAttributeValue.class.php'; - -$id = GETPOST('id', 'int'); -$ref = GETPOST('ref', 'alpha'); -$value = GETPOST('value', 'alpha'); - -$action = GETPOST('action', 'aZ09'); -$cancel = GETPOST('cancel', 'alpha'); -$backtopage = GETPOST('backtopage', 'alpha'); - -$object = new ProductAttribute($db); -$objectval = new ProductAttributeValue($db); - -if ($object->fetch($id) < 1) { - dol_print_error($db, $langs->trans('ErrorRecordNotFound')); - exit(); -} - -$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; - -// Security check -if (empty($conf->variants->enabled)) { - accessforbidden('Module not enabled'); -} -if ($user->socid > 0) { // Protection if external user - accessforbidden(); -} -//$result = restrictedArea($user, 'variant'); -if (!$permissiontoread) accessforbidden(); - - -/* - * Actions - */ - -if ($cancel) { - $action = ''; - header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id); - exit(); -} - -// None - - - -/* - * View - */ - -if ($action == 'add') { - if (empty($ref) || empty($value)) { - setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors'); - } else { - $objectval->fk_product_attribute = $object->id; - $objectval->ref = $ref; - $objectval->value = $value; - - if ($objectval->create($user) > 0) { - setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); - header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id); - exit(); - } else { - setEventMessages($langs->trans('ErrorCreatingProductAttributeValue'), $objectval->errors, 'errors'); - } - } -} - -$langs->load('products'); - -$help_url = 'EN:Module_Products#Variants'; - -$title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label)); - -llxHeader('', $title, $help_url); - -$h = 0; -$head[$h][0] = DOL_URL_ROOT.'/variants/card.php?id='.$object->id; -$head[$h][1] = $langs->trans("ProductAttributeName"); -$head[$h][2] = 'variant'; -$h++; - -print dol_get_fiche_head($head, 'variant', $langs->trans('ProductAttributeName'), -1, 'generic'); - -print '
    '; -print '
    '; -?> - - - - - - - - -
    trans('Ref') ?>ref) ?> -
    trans('Label') ?>label) ?>
    - -'; - -print dol_get_fiche_end(); - -print '
    '; - - -print '
    '; -print ''; -print ''; -print ''; -print ''; - -print load_fiche_titre($langs->trans('NewProductAttributeValue')); - -print dol_get_fiche_head(); - -?> - - - - - - - - - -
    -'; -print ''; -print '   '; -print ''; -print '
    '; - -print ''; - -// End of page -llxFooter(); -$db->close(); diff --git a/htdocs/variants/lib/variants.lib.php b/htdocs/variants/lib/variants.lib.php new file mode 100644 index 00000000000..e04d6fc15fe --- /dev/null +++ b/htdocs/variants/lib/variants.lib.php @@ -0,0 +1,53 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file /variants/lib/variants.lib.php + * \ingroup variants + * \brief Library files with common functions for Variants + */ + + +/** + * Prepare array with list of tabs + * + * @param Product $object Object related to tabs + * @return array Array of tabs to show + */ +function productAttributePrepareHead($object) +{ + global $langs, $conf; + $langs->load("products"); + + $h = 0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/variants/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("ProductAttribute"); + $head[$h][2] = 'card'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'product_attribute'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'product_attribute', 'remove'); + + return $head; +} diff --git a/htdocs/variants/list.php b/htdocs/variants/list.php index eedb24524e0..6881b17b781 100644 --- a/htdocs/variants/list.php +++ b/htdocs/variants/list.php @@ -1,5 +1,6 @@ + * Copyright (C) 2022 Open-Dsi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -15,47 +16,195 @@ * along with this program. If not, see . */ +/** + * \file htdocs/variants/list.php + * \ingroup variants + * \brief List page for product attribute + */ + require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php'; -$action = GETPOST('action', 'aZ09'); +// Load translation files required by the page +$langs->loadLangs(array("products", "other")); + +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'productattributelist'; // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') + +$id = GETPOST('id', 'int'); + +// Load variable for pagination +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + // If $page is not defined, or '' or -1 or if we click on clear filters + $page = 0; +} +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects $object = new ProductAttribute($db); -$rowid = GETPOST('rowid', 'int'); // Id of line for up / down when no javascript available +//$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->variants->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('productattributelist')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +//$extrafields->fetch_name_optionals_label($object->table_element); + +//$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) { + $sortfield = "t.position"; // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} + +// Initialize array of search criterias +$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int')); + $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int')); + } +} +$search['nb_of_values'] = GETPOST('search_nb_of_values', 'alpha'); +$search['nb_products'] = GETPOST('search_nb_products', 'alpha'); + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach ($object->fields as $key => $val) { + if (!empty($val['searchall'])) { + $fieldstosearchall['t.'.$key] = $val['label']; + } +} + +// Definition of array of fields for columns +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) { + $visible = (int) dol_eval($val['visible'], 1); + $arrayfields['t.'.$key] = array( + 'label'=>$val['label'], + 'checked'=>(($visible < 0) ? 0 : 1), + 'enabled'=>($visible != 3 && dol_eval($val['enabled'], 1)), + 'position'=>$val['position'], + 'help'=> isset($val['help']) ? $val['help'] : '' + ); + } +} +$arrayfields['nb_of_values'] = array( + 'label' => $langs->trans('NbOfDifferentValues'), + 'checked' => 1, + 'enabled' => 1, + 'position' => 40, + 'help' => '' +); +$arrayfields['nb_products'] = array( + 'label' => $langs->trans('NbProducts'), + 'checked' => 1, + 'enabled' => 1, + 'position' => 50, + 'help' => '' +); +// Extra fields +//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); $permissiontoread = $user->rights->produit->lire || $user->rights->service->lire; -$permissiontoadd = $user->rights->produit->creer || $user->rights->service->creer; +$permissiontoadd = $user->rights->produit->lire || $user->rights->service->lire; +$permissiontodelete = $user->rights->produit->lire || $user->rights->service->lire; // Security check if (empty($conf->variants->enabled)) { accessforbidden('Module not enabled'); } +$socid = 0; if ($user->socid > 0) { // Protection if external user + //$socid = $user->socid; accessforbidden(); } - - -//$result = restrictedArea($user, 'variant'); if (!$permissiontoread) accessforbidden(); - /* * Actions */ -if ($action == 'up' && $permissiontoadd) { - $object->fetch($rowid); - $object->moveUp(); +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} - header('Location: '.$_SERVER['PHP_SELF']); - exit(); -} elseif ($action == 'down' && $permissiontoadd) { - $object->fetch($rowid); - $object->moveDown(); +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} - header('Location: '.$_SERVER['PHP_SELF']); - exit(); +if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + foreach ($object->fields as $key => $val) { + $search[$key] = ''; + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = ''; + $search[$key.'_dtend'] = ''; + } + } + $search['nb_of_values'] = ''; + $search['nb_products'] = ''; + $toselect = array(); + $search_array_options = array(); + } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + if ($action == 'up' && $permissiontoadd) { + $object->attributeMoveUp($rowid); + + header('Location: '.$_SERVER['PHP_SELF']); + exit(); + } elseif ($action == 'down' && $permissiontoadd) { + $object->attributeMoveDown($rowid); + + header('Location: '.$_SERVER['PHP_SELF']); + exit(); + } + + // Mass actions + $objectclass = 'ProductAttribute'; + $objectlabel = 'ProductAttribute'; + $uploaddir = $conf->variants->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -64,22 +213,540 @@ if ($action == 'up' && $permissiontoadd) { * View */ -$langs->load('products'); +$form = new Form($db); -$title = $langs->trans($langs->trans('ProductAttributes')); +$now = dol_now(); -$variants = $object->fetchAll(); +$help_url = ''; +$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("ProductAttributes")); +$morejs = array(); +$morecss = array(); -llxHeader('', $title); -$newcardbutton = ''; -if ($user->rights->produit->creer) { - $newcardbutton .= dolGetButtonTitle($langs->trans('Create'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/variants/create.php'); +// Build and execute select +// -------------------------------------------------------------------- +$sql = "SELECT "; +$sql .= " COUNT(DISTINCT pav.rowid) AS nb_of_values, COUNT(DISTINCT pac2v.fk_prod_combination) AS nb_products,"; +$sql .= $object->getFieldList("t"); +// Add fields from extrafields +//if (!empty($extrafields->attributes[$object->table_element]['label'])) { +// foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { +// $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key." as options_".$key.", " : ""); +// } +//} +// Add fields from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= preg_replace('/^,/', '', $hookmanager->resPrint); +$sql = preg_replace('/,\s*$/', '', $sql); +$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; +//if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { +// $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +//} +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination2val AS pac2v ON pac2v.fk_prod_attr = t.rowid"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_value AS pav ON pav.fk_product_attribute = t.rowid"; +// Add table from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') { + $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key); + if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) { + if (preg_match('/_dtstart$/', $key)) { + $sql .= " AND t.".$columnName." >= '".$db->idate($search[$key])."'"; + } + if (preg_match('/_dtend$/', $key)) { + $sql .= " AND t." . $columnName . " <= '" . $db->idate($search[$key]) . "'"; + } + } + } elseif (array_key_exists($key, $object->fields)) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) { + if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($object->fields[$key]['arrayofkeyval']) || !array_key_exists('0', $object->fields[$key]['arrayofkeyval'])))) { + $search[$key] = ''; + } + $mode_search = 2; + } + if ($search[$key] != '') { + $sql .= natural_search("t.".$key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); +// Add where from extra fields +//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; + +$hasgroupby = true; +$sql .= " GROUP BY "; +foreach ($object->fields as $key => $val) { + $sql .= "t." . $key . ", "; +} +// Add fields from extrafields +//if (!empty($extrafields->attributes[$object->table_element]['label'])) { +// foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { +// $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); +// } +//} +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace("/,\s*$/", "", $sql); + +$sql .= " HAVING 1=1"; +if ($search['nb_of_values'] != '') { + $sql .= natural_search("nb_of_values", $search['nb_of_values'], 1); +} +if ($search['nb_products'] != '') { + $sql .= natural_search("nb_products", $search['nb_products'], 1); +} +// Add HAVING from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql .= empty($hookmanager->resPrint) ? "" : " ".$hookmanager->resPrint; + +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + /* This old and fast method to get and count full list returns all record so use a high amount of memory. + $resql = $db->query($sql); + $nbtotalofrecords = $db->num_rows($resql); + */ + /* The slow method does not consume memory on mysql (not tested on pgsql) */ + /*$resql = $db->query($sql, 0, 'auto', 1); + while ($db->fetch_object($resql)) { + $nbtotalofrecords++; + }*/ + /* The fast and low memory method to get and count full list converts the sql into a sql count */ + $sqlforcount = preg_replace("/^SELECT[a-z0-9\._\s\(\),]+FROM/i", "SELECT COUNT(*) as nbtotalofrecords FROM", $sql); + $resql = $db->query($sqlforcount); + if ($resql) { + if ($hasgroupby) { + $nbtotalofrecords = $db->num_rows($resql); + } else { + $objforcount = $db->fetch_object($resql); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + } + if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0 + $page = 0; + $offset = 0; + } + $db->free($resql); + } } -print load_fiche_titre($title, $newcardbutton, 'product'); +// Complete request and execute it with limit +$sql .= $db->order($sortfield, $sortorder); +if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); +} + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + + +// Direct jump if only one record found +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: " . dol_buildpath('/variants/card.php', 2) . '?id=' . $id); + exit; +} + + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', ''); + +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + if ($skey != '') { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } + } elseif ($search[$key] != '') { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +// Add $param from extra fields +//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; +// Add $param from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook +$param .= $hookmanager->resPrint; + +// List of mass actions available +$arrayofmassactions = array( + //'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"), + //'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"), + //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"), + //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"), +); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); + +print '
    '."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/variants/card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); + +// Add code for pre mass action (confirmation or email presend form) +$topicmail = "SendProductAttributeRef"; +$modelmail = "productattribute"; +$objecttmp = new ProductAttribute($db); +$trackid = 'pa'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; +} + +$moreforfilter = ''; +/*$moreforfilter.='
    '; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
    ';*/ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} + +if (!empty($moreforfilter)) { + print '
    '; + print $moreforfilter; + print '
    '; +} + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print ''."\n"; + + +// Fields title search +// -------------------------------------------------------------------- +print ''; +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + } +} +// Extra fields +//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; +$key = 'nb_of_values'; +if (!empty($arrayfields[$key]['checked'])) { + print ''; +} +$key = 'nb_products'; +if (!empty($arrayfields[$key]['checked'])) { + print ''; +} +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print ''; +print ''; +print ''; +print ''."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; + } +} +// Extra fields +//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +$key = 'nb_of_values'; +if (!empty($arrayfields[$key]['checked'])) { + print getTitleFieldOfList($arrayfields[$key]['label'], 0, $_SERVER['PHP_SELF'], $key, '', $param, 'class="center"', $sortfield, $sortorder, 'center ')."\n"; +} +$key = 'nb_products'; +if (!empty($arrayfields[$key]['checked'])) { + print getTitleFieldOfList($arrayfields[$key]['label'], 0, $_SERVER['PHP_SELF'], $key, '', $param, 'class="center"', $sortfield, $sortorder, 'center ')."\n"; +} +// Hook fields +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print getTitleFieldOfList('', 0, '', '', '', '', '', '', '', 'linecoledit ')."\n"; +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +print getTitleFieldOfList('', 0, '', '', '', '', '', '', '', 'linecolmove ')."\n"; +print ''."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine = 0; +//if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { +// foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { +// if (preg_match('/\$object/', $val)) { +// $needToFetchEachLine++; // There is at least one compute field that use $object +// } +// } +//} + + +// Loop on record +// -------------------------------------------------------------------- +$i = 0; +$totalarray = array(); +$totalarray['nbfield'] = 0; +while ($i < ($limit ? min($num, $limit) : $num)) { + $obj = $db->fetch_object($resql); + if (empty($obj)) { + break; // Should not happen + } + + $object->setVarsFromFetchObj($obj); + + // Show here line of result + print ''; + foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '') . 'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '') . 'center'; + } + + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '') . 'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '') . 'nowrap'; + } + + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status')) && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '') . 'right'; + } + //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + + if (!empty($arrayfields['t.' . $key]['checked'])) { + print ''; + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif ($key == 'rowid') { + print $object->showOutputField($val, $key, $object->id, ''); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure']) && $val['isameasure'] == 1) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.' . $key; + } + if (!isset($totalarray['val'])) { + $totalarray['val'] = array(); + } + if (!isset($totalarray['val']['t.' . $key])) { + $totalarray['val']['t.' . $key] = 0; + } + $totalarray['val']['t.' . $key] += $object->$key; + } + } + } + // Extra fields + //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + $key = 'nb_of_values'; + if (!empty($arrayfields[$key]['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + $key = 'nb_products'; + if (!empty($arrayfields[$key]['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Fields from hook + $parameters = array('arrayfields' => $arrayfields, 'object' => $object, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Action column + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + + print '' . "\n"; + + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +// If no record found +if ($num == 0) { + $colspan = 3; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print ''; +} + +$db->free($resql); + +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
    '; + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) { + print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', 'maxwidth125', 1); + } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + print '
    '; + print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
    '; + print '
    '; + print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
    '; + } elseif ($key == 'lang') { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin = new FormAdmin($db); + print $formadmin->select_language($search[$key], 'search_lang', 0, null, 1, 0, 0, 'minwidth150 maxwidth200', 2); + } else { + print ''; + } + print '
    '; + print ''; + print ''; + print ''; + print ''; +$searchpicto = $form->showFilterButtons(); +print $searchpicto; +print '
    '; + print $obj->$key; + print ''; + print $obj->$key; + print ''; + if ($permissiontoadd) { + print '' . img_edit() . ''; + } + print ''; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print ''; + if ($i > 0) { + print '' . img_up('default', 0, 'imgupforline') . ''; + } + if ($i < $num - 1) { + print '' . img_down('default', 0, 'imgdownforline') . ''; + } + print '
    '.$langs->trans("NoRecordFound").'
    '."\n"; +print '
    '."\n"; + +print '
    '."\n"; $forcereloadpage = empty($conf->global->MAIN_FORCE_RELOAD_PAGE) ? 0 : 1; +$tagidfortablednd = (empty($tagidfortablednd) ? 'tableattributes' : $tagidfortablednd); ?> - - - - - - - - - $attribute) { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; -} -print '
    trans('Ref') ?>trans('Label') ?>trans('NbOfDifferentValues') ?>trans('NbProducts') ?>
    '.dol_htmlentities($attribute->ref).''.dol_htmlentities($attribute->label).''.$attribute->countChildValues().''.$attribute->countChildProducts().''; - print ''.img_edit().''; - print ''.img_delete().''; - print ''; - if ($key > 0) { - print ''.img_up('default', 0, 'imgupforline').''; - } - if ($key < count($variants) - 1) { - print ''.img_down('default', 0, 'imgdownforline').''; - } - print '
    '; +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } + + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); + + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; + + print $formfile->showdocuments('massfilesarea_productattribute', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); +} // End of page llxFooter(); diff --git a/htdocs/variants/tpl/README b/htdocs/variants/tpl/README new file mode 100644 index 00000000000..432895e939f --- /dev/null +++ b/htdocs/variants/tpl/README @@ -0,0 +1,3 @@ +README (english) + +This directory is used for storing the common default templates of the system core. (outside any modules) \ No newline at end of file diff --git a/htdocs/variants/tpl/productattributevalueline_create.tpl.php b/htdocs/variants/tpl/productattributevalueline_create.tpl.php new file mode 100644 index 00000000000..cc16302a68d --- /dev/null +++ b/htdocs/variants/tpl/productattributevalueline_create.tpl.php @@ -0,0 +1,91 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $conf + * $langs + * $dateSelector + * $forceall (0 by default, 1 for supplier invoices/orders) + * $senderissupplier (0 by default, 1 or 2 for supplier invoices/orders) + * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax) + */ + +// Protection to avoid direct call of template +if (empty($object) || !is_object($object)) { + print "Error: this template page cannot be called directly as an URL"; + exit; +} + +global $forcetoshowtitlelines; + +// Define colspan for the button 'Add' +$colspan = 3; // Columns: col edit + col delete + move button + +// Lines for extrafield +$objectline = null; + +print "\n"; +$nolinesbefore = (count($this->lines) == 0 || $forcetoshowtitlelines); +if ($nolinesbefore) { + ?> + + global->MAIN_VIEW_LINE_NUMBER)) { ?> + + + +
    trans('AddNewLine'); ?> + + trans('Value'); ?> +   + + + + global->MAIN_VIEW_LINE_NUMBER)) { + $coldisplay++; + echo ''; + } + $coldisplay++; + ?> + + trans('Ref') . ': '; } ?> + " autofocus> + executeHooks('formCreateValueOptions', $parameters, $object, $action); + if (!empty($hookmanager->resPrint)) { + print $hookmanager->resPrint; + } + } + ?> + + + + "> + + + + + + + + diff --git a/htdocs/variants/tpl/productattributevalueline_edit.tpl.php b/htdocs/variants/tpl/productattributevalueline_edit.tpl.php new file mode 100644 index 00000000000..3b842962258 --- /dev/null +++ b/htdocs/variants/tpl/productattributevalueline_edit.tpl.php @@ -0,0 +1,77 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $conf + * $langs + * $seller, $buyer + * $dateSelector + * $forceall (0 by default, 1 for supplier invoices/orders) + * $senderissupplier (0 by default, 1 for supplier invoices/orders) + * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax) + * $canchangeproduct (0 by default, 1 to allow to change the product if it is a predefined product) + */ + +// Protection to avoid direct call of template +if (empty($object) || !is_object($object)) { + print "Error, template page can't be called as URL"; + exit; +} + +// Define colspan for the button 'Add' +$colspan = 3; // Column: col edit + col delete + move button + +print "\n"; + +$coldisplay = 0; +?> + +global->MAIN_VIEW_LINE_NUMBER)) { ?> + + + +
    + + + + ref); ?>"> + $line); + $reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $object, $action); + if (!empty($hookmanager->resPrint)) { + print $hookmanager->resPrint; + } + } + ?> + + + + value); ?>"> + + + + + ">
    + "> + + + + diff --git a/htdocs/variants/tpl/productattributevalueline_title.tpl.php b/htdocs/variants/tpl/productattributevalueline_title.tpl.php new file mode 100644 index 00000000000..ac32a229d5b --- /dev/null +++ b/htdocs/variants/tpl/productattributevalueline_title.tpl.php @@ -0,0 +1,70 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $conf + * $langs + * $element (used to test $user->rights->$element->creer) + * $permtoedit (used to replace test $user->rights->$element->creer) + * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax) + * $outputalsopricetotalwithtax + * $usemargins (0 to disable all margins columns, 1 to show according to margin setup) + * + * $type, $text, $description, $line + */ + +// Protection to avoid direct call of template +if (empty($object) || !is_object($object)) { + print "Error, template page can't be called as URL"; + exit; +} + +print "\n"; + +// Title line +print "\n"; + +print ''; + +// Adds a line numbering column +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ' '; +} + +// Ref +print ''.$langs->trans('Ref').''; + +// Value +print ''.$langs->trans('Value').''; + +print ''; // No width to allow autodim + +print ''; + +print ''; + +if ($action == 'selectlines') { + print ''; + print ''; + print ''; + print ''; +} + +print "\n"; +print "\n"; + +print "\n"; diff --git a/htdocs/variants/tpl/productattributevalueline_view.tpl.php b/htdocs/variants/tpl/productattributevalueline_view.tpl.php new file mode 100644 index 00000000000..6acf155f89a --- /dev/null +++ b/htdocs/variants/tpl/productattributevalueline_view.tpl.php @@ -0,0 +1,105 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $conf + * $langs + * $dateSelector + * $forceall (0 by default, 1 for supplier invoices/orders) + * $element (used to test $user->rights->$element->creer) + * $permtoedit (used to replace test $user->rights->$element->creer) + * $senderissupplier (0 by default, 1 for supplier invoices/orders) + * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax) + * $outputalsopricetotalwithtax + * $usemargins (0 to disable all margins columns, 1 to show according to margin setup) + * $object_rights->creer initialized from = $object->getRights() + * $disableedit, $disablemove, $disableremove + * + * $text, $description, $line + */ + +// Protection to avoid direct call of template +if (empty($object) || !is_object($object)) { + print "Error, template page can't be called as URL"; + exit; +} + +// add html5 elements +$domData = ' data-element="'.$line->element.'"'; +$domData .= ' data-id="'.$line->id.'"'; + +$coldisplay = 0; +?> + + > +global->MAIN_VIEW_LINE_NUMBER)) { ?> + + +
    + ref ?> + + + value ?> +write) && $action != 'selectlines') { + print ''; + $coldisplay++; + if (empty($disableedit)) { ?> + id.'#line_'.$line->id; ?>"> + '; + } + print ''; + + print ''; + $coldisplay++; + if (empty($disableremove)) { // For situation invoice, deletion is not possible if there is a parent company. + print 'id.'">'; + print img_delete(); + print ''; + } + print ''; + + if ($num > 1 && $conf->browser->layout != 'phone' && empty($disablemove)) { + print ''; + $coldisplay++; + if ($i > 0) { ?> + id; ?>"> + + + + id; ?>"> + + + '; + } else { + print 'browser->layout != 'phone' && empty($disablemove)) ? ' class="linecolmove tdlineupdown center"' : ' class="linecolmove center"').'>'; + $coldisplay++; + } +} else { + print ''; + $coldisplay = $coldisplay + 3; +} + +if ($action == 'selectlines') { ?> + +\n"; + +print "\n";