diff --git a/README.md b/README.md index 5559613eaa2..c476f14a8cc 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Other licenses apply for some included dependencies. See [COPYRIGHT](https://git If you have low technical skills and you're looking to install Dolibarr ERP/CRM in just a few clicks, you can use one of the packaged versions: -- [DoliWamp for Windows](https://wiki.dolibarr.org/index.php/Dolibarr_for_Windows_DoliWamp) +- [DoliWamp for Windows](https://wiki.dolibarr.org/index.php/Dolibarr_for_Windows_(DoliWamp)) - [DoliDeb for Debian](https://wiki.dolibarr.org/index.php/Dolibarr_for_Ubuntu_or_Debian) - DoliRpm for Redhat, Fedora, OpenSuse, Mandriva or Mageia diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index 6d7d92ce22b..583b12368dc 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -81,22 +81,22 @@ $list_account[] = '---Others---'; $list_account[] = 'ACCOUNTING_VAT_BUY_ACCOUNT'; $list_account[] = 'ACCOUNTING_VAT_SOLD_ACCOUNT'; $list_account[] = 'ACCOUNTING_VAT_PAY_ACCOUNT'; -if ($conf->banque->enabled) { +if (!empty($conf->banque->enabled)) { $list_account[] = 'ACCOUNTING_ACCOUNT_TRANSFER_CASH'; } -if ($conf->don->enabled) { +if (!empty($conf->don->enabled)) { $list_account[] = 'DONATION_ACCOUNTINGACCOUNT'; } -if ($conf->adherent->enabled) { +if (!empty($conf->adherent->enabled)) { $list_account[] = 'ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT'; } -if ($conf->loan->enabled) { +if (!empty($conf->loan->enabled)) { $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_CAPITAL'; $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INTEREST'; $list_account[] = 'LOAN_ACCOUNTING_ACCOUNT_INSURANCE'; } $list_account[] = 'ACCOUNTING_ACCOUNT_SUSPENSE'; -if ($conf->societe->enabled) { +if (!empty($conf->societe->enabled)) { $list_account[] = '---Deposits---'; $list_account[] = 'ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT'; } @@ -246,7 +246,7 @@ foreach ($list_account as $key) { } } -if ($conf->societe->enabled) { +if (!empty($conf->societe->enabled)) { print ''; print '' . img_picto('', 'bill', 'class="pictofixedwidth"') . $langs->trans("UseAuxiliaryAccountOnCustomerDeposit") . ''; if (!empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT)) { diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 28c35016054..8cccef2d342 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -741,11 +741,11 @@ class AccountingAccount extends CommonObject global $hookmanager; // Instantiate hooks for external modules - $hookmanager->initHooks(array('accoutancyBindingCalculation')); + $hookmanager->initHooks(array('accountancyBindingCalculation')); - // Execute hook accoutancyBindingCalculation + // Execute hook accountancyBindingCalculation $parameters = array('buyer' => $buyer, 'seller' => $seller, 'product' => $product, 'facture' => $facture, 'factureDet' => $factureDet ,'accountingAccount'=>$accountingAccount, $type); - $reshook = $hookmanager->executeHooks('accoutancyBindingCalculation', $parameters); // Note that $action and $object may have been modified by some hooks + $reshook = $hookmanager->executeHooks('accountancyBindingCalculation', $parameters); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { $const_name = ''; diff --git a/htdocs/accountancy/index.php b/htdocs/accountancy/index.php index 18277eb6751..99ae0bd845b 100644 --- a/htdocs/accountancy/index.php +++ b/htdocs/accountancy/index.php @@ -86,7 +86,7 @@ if (!empty($conf->global->INVOICE_USE_SITUATION) && $conf->global->INVOICE_USE_S print ''.$langs->trans("SorryThisModuleIsNotCompatibleWithTheExperimentalFeatureOfSituationInvoices")."\n"; print "
"; -} elseif ($conf->accounting->enabled) { +} elseif (!empty($conf->accounting->enabled)) { $step = 0; $resultboxes = FormOther::getBoxesArea($user, "27"); // Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb) diff --git a/htdocs/adherents/admin/member.php b/htdocs/adherents/admin/member.php index ed2453ef793..bae229bc77b 100644 --- a/htdocs/adherents/admin/member.php +++ b/htdocs/adherents/admin/member.php @@ -108,7 +108,7 @@ if ($action == 'set_default') { $res3 = dolibarr_set_const($db, 'ADHERENT_CREATE_EXTERNAL_USER_LOGIN', GETPOST('ADHERENT_CREATE_EXTERNAL_USER_LOGIN', 'alpha'), 'chaine', 0, '', $conf->entity); $res4 = dolibarr_set_const($db, 'ADHERENT_BANK_USE', GETPOST('ADHERENT_BANK_USE', 'alpha'), 'chaine', 0, '', $conf->entity); // Use vat for invoice creation - if ($conf->facture->enabled) { + if (!empty($conf->facture->enabled)) { $res4 = dolibarr_set_const($db, 'ADHERENT_VAT_FOR_SUBSCRIPTIONS', GETPOST('ADHERENT_VAT_FOR_SUBSCRIPTIONS', 'alpha'), 'chaine', 0, '', $conf->entity); $res5 = dolibarr_set_const($db, 'ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS', GETPOST('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS', 'alpha'), 'chaine', 0, '', $conf->entity); if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { @@ -256,7 +256,7 @@ print ''; print "\n"; // Use vat for invoice creation -if ($conf->facture->enabled) { +if (!empty($conf->facture->enabled)) { print ''.$langs->trans("VATToUseForSubscriptions").''; if (!empty($conf->banque->enabled)) { print ''; diff --git a/htdocs/adherents/subscription/list.php b/htdocs/adherents/subscription/list.php index d96adbc3b82..6056e1320f0 100644 --- a/htdocs/adherents/subscription/list.php +++ b/htdocs/adherents/subscription/list.php @@ -628,10 +628,10 @@ while ($i < min($num, $limit)) { 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($obj->rowid, $arrayofselected)) { + if (in_array($obj->crowid, $arrayofselected)) { $selected = 1; } - print ''; + print ''; } print ''; if (!$i) { diff --git a/htdocs/admin/bank.php b/htdocs/admin/bank.php index e1e468b0cec..ef365881feb 100644 --- a/htdocs/admin/bank.php +++ b/htdocs/admin/bank.php @@ -53,8 +53,6 @@ $type = 'bankaccount'; // Order display of bank account if ($action == 'setbankorder') { if (dolibarr_set_const($db, "BANK_SHOW_ORDER_OPTION", GETPOST('value', 'alpha'), 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; } else { dol_print_error($db); } @@ -63,15 +61,11 @@ if ($action == 'setbankorder') { // Auto report last num releve on conciliate if ($action == 'setreportlastnumreleve') { if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 1, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; } else { dol_print_error($db); } } elseif ($action == 'unsetreportlastnumreleve') { if (dolibarr_set_const($db, "BANK_REPORT_LAST_NUM_RELEVE", 0, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; } else { dol_print_error($db); } @@ -80,15 +74,11 @@ if ($action == 'setreportlastnumreleve') { // Colorize movements if ($action == 'setbankcolorizemovement') { if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 1, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; } else { dol_print_error($db); } } elseif ($action == 'unsetbankcolorizemovement') { if (dolibarr_set_const($db, "BANK_COLORIZE_MOVEMENT", 0, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; } else { dol_print_error($db); } @@ -427,13 +417,13 @@ print ""; // Active if ($conf->global->BANK_COLORIZE_MOVEMENT) { print ''."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; print ''; } else { print ''."\n"; - print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; + print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; print ""; } @@ -483,13 +473,13 @@ print ''; // Active if ($conf->global->BANK_REPORT_LAST_NUM_RELEVE) { print ''."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; print ''; } else { print ''."\n"; - print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; + print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; print ""; } diff --git a/htdocs/admin/bom.php b/htdocs/admin/bom.php index e3adb206d7e..dc56d3ae79f 100644 --- a/htdocs/admin/bom.php +++ b/htdocs/admin/bom.php @@ -93,7 +93,7 @@ if ($action == 'updateMask') { header("Location: ".DOL_URL_ROOT."/document.php?modulepart=bom&file=SPECIMEN.pdf"); return; } else { - setEventMessages($module->error, null, 'errors'); + setEventMessages($module->error, $module->errors, 'errors'); dol_syslog($module->error, LOG_ERR); } } else { @@ -176,7 +176,7 @@ $head = bomAdminPrepareHead(); print dol_get_fiche_head($head, 'settings', $langs->trans("BOMs"), -1, 'bom'); /* - * BOMs Numbering model + * Numbering module */ print load_fiche_titre($langs->trans("BOMsNumberingModules"), '', ''); @@ -202,10 +202,11 @@ foreach ($dirmodels as $reldir) { while (($file = readdir($handle)) !== false) { if (substr($file, 0, 8) == 'mod_bom_' && substr($file, dol_strlen($file) - 3, 3) == 'php') { $file = substr($file, 0, dol_strlen($file) - 4); + $classname = $file; require_once $dir.$file.'.php'; - $module = new $file($db); + $module = new $classname($db); // Show modules according to features level if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { @@ -220,7 +221,7 @@ foreach ($dirmodels as $reldir) { print $module->info(); print ''; - // Show example of numbering model + // Show example of numbering module print ''; $tmp = $module->getExample(); if (preg_match('/^Error/', $tmp)) { @@ -277,13 +278,13 @@ foreach ($dirmodels as $reldir) { } print ""; print ""; -print "
\n"; /* * Document templates generators */ +print "
\n"; print load_fiche_titre($langs->trans("BOMsModelModule"), '', ''); // Load array def with activated templates @@ -307,8 +308,8 @@ if ($resql) { print '
'; -print "\n"; -print "\n"; +print '
'; +print ''; print ''; print ''; print '\n"; @@ -364,13 +365,13 @@ foreach ($dirmodels as $reldir) { // Active if (in_array($name, $def)) { print ''; } else { print '"; } @@ -379,7 +380,7 @@ foreach ($dirmodels as $reldir) { if ($conf->global->BOM_ADDON_PDF == $name) { print img_picto($langs->trans("Default"), 'on'); } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + print 'scandir).'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; } print ''; @@ -421,12 +422,12 @@ foreach ($dirmodels as $reldir) { print '
'.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Status")."'."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; print ''."\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print 'scandir).'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; print "
'; print '
'; -print "
"; /* * Other options */ +print "
"; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); print '
'; diff --git a/htdocs/admin/emailcollector_card.php b/htdocs/admin/emailcollector_card.php index d01b160ca31..50e3faa7d51 100644 --- a/htdocs/admin/emailcollector_card.php +++ b/htdocs/admin/emailcollector_card.php @@ -1,5 +1,6 @@ + * Copyright (C) 2022 Charlene Benke * * 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 @@ -592,15 +593,15 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea 'recordjoinpiece'=>'AttachJoinedDocumentsToObject', 'recordevent'=>'RecordEvent'); $arrayoftypesnocondition = $arrayoftypes; - if ($conf->projet->enabled) { + if (!empty($conf->projet->enabled)) { $arrayoftypes['project'] = 'CreateLeadAndThirdParty'; } $arrayoftypesnocondition['project'] = 'CreateLeadAndThirdParty'; - if ($conf->ticket->enabled) { + if (!empty($conf->ticket->enabled)) { $arrayoftypes['ticket'] = 'CreateTicketAndThirdParty'; } $arrayoftypesnocondition['ticket'] = 'CreateTicketAndThirdParty'; - if ($conf->recruitment->enabled) { + if (!empty($conf->recruitment->enabled)) { $arrayoftypes['candidature'] = 'CreateCandidature'; } $arrayoftypesnocondition['candidature'] = 'CreateCandidature'; diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index fcf3116a971..aedd91a34eb 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -76,7 +76,7 @@ if (preg_match('/^(set|del)_([A-Z_]+)$/', $action, $regs)) { } if ($action == 'removebackgroundlogin' && !empty($conf->global->MAIN_LOGIN_BACKGROUND)) { - dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV + 1, 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", getDolGlobalInt('MAIN_IHM_PARAMS_REV') + 1, 'chaine', 0, '', $conf->entity); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $logofile = $conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND; @@ -100,6 +100,7 @@ if ($action == 'update') { if ($mode == 'template') { dolibarr_set_const($db, "MAIN_THEME", GETPOST("main_theme", 'aZ09'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", getDolGlobalInt('MAIN_IHM_PARAMS_REV') + 1, 'chaine', 0, '', $conf->entity); if (GETPOSTISSET('THEME_TOPMENU_DISABLE_IMAGE')) { $val=GETPOST('THEME_TOPMENU_DISABLE_IMAGE'); @@ -227,7 +228,7 @@ if ($action == 'update') { if ($mode == 'other') { dolibarr_set_const($db, "MAIN_LANG_DEFAULT", GETPOST("MAIN_LANG_DEFAULT", 'aZ09'), 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV + 1, 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", getDolGlobalInt('MAIN_IHM_PARAMS_REV') + 1, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", GETPOST("main_size_liste_limit", 'int'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", GETPOST("main_size_shortliste_limit", 'int'), 'chaine', 0, '', $conf->entity); diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index dbf4ca53686..0db1b26dc7d 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -528,8 +528,8 @@ if ($mode == 'common' || $mode == 'commonkanban') { $moreforfilter .= ''; //$moreforfilter .= '
'.$moreinfo.' '.$moreinfo2.'
'; diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index e8f59727c07..a5e83155f03 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -394,7 +394,7 @@ print "\n"; print "\n"; // Option to force stock to be enough before adding a line into document -if ($conf->invoice->enabled) { +if (!empty($conf->invoice->enabled)) { print ''; print ''.$langs->trans("StockMustBeEnoughForInvoice").''; print ''; @@ -408,7 +408,7 @@ if ($conf->invoice->enabled) { print "\n"; } -if ($conf->order->enabled) { +if (!empty($conf->order->enabled)) { print ''; print ''.$langs->trans("StockMustBeEnoughForOrder").''; print ''; @@ -422,7 +422,7 @@ if ($conf->order->enabled) { print "\n"; } -if ($conf->expedition->enabled) { +if (!empty($conf->expedition->enabled)) { print ''; print ''.$langs->trans("StockMustBeEnoughForShipment").''; print ''; diff --git a/htdocs/admin/stocktransfer.php b/htdocs/admin/stocktransfer.php new file mode 100644 index 00000000000..e0ce72eeb25 --- /dev/null +++ b/htdocs/admin/stocktransfer.php @@ -0,0 +1,484 @@ + + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) 2021 SuperAdmin + * + * 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 stocktransfer/admin/setup.php + * \ingroup stocktransfer + * \brief StockTransfer setup page. + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; +if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); + +global $langs, $user; + +// Libraries +require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/class/stocktransfer.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/lib/stocktransfer.lib.php'; + +// Translations +$langs->loadLangs(array("admin", "stocks")); + +// Access control +if (!$user->admin) accessforbidden(); + +// Parameters +$action = GETPOST('action', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); + +$value = GETPOST('value', 'alpha'); + +$arrayofparameters = array( + 'STOCKTRANSFER_MYPARAM1'=>array('css'=>'minwidth200', 'enabled'=>1), + 'STOCKTRANSFER_MYPARAM2'=>array('css'=>'minwidth500', 'enabled'=>1) +); + +$error = 0; +$setupnotempty = 0; + + +/* + * Actions + */ + +if ((float) DOL_VERSION >= 6) { + include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; +} + +if ($action == 'updateMask') { + $maskconststocktransfer = GETPOST('maskconststocktransfer', 'alpha'); + $maskstocktransfer = GETPOST('maskStockTransfer', 'alpha'); + + if ($maskconststocktransfer) $res = dolibarr_set_const($db, $maskconststocktransfer, $maskstocktransfer, 'chaine', 0, '', $conf->entity); + + if (!$res > 0) $error++; + + if (!$error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } +} elseif ($action == 'specimen') { + $modele = GETPOST('module', 'alpha'); + $tmpobjectkey = 'StockTransfer'; + + $tmpobject = new $tmpobjectkey($db); + $tmpobject->initAsSpecimen(); + + // Search template files + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $file = dol_buildpath($reldir."core/modules/stocktransfer/doc/pdf_".$modele.".modules.php", 0); + if (file_exists($file)) { + $filefound = 1; + $classname = "pdf_".$modele; + break; + } + } + + if ($filefound) { + require_once $file; + + $module = new $classname($db); + + if ($module->write_file($tmpobject, $langs) > 0) { + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=".strtolower($tmpobjectkey)."&file=SPECIMEN.pdf"); + return; + } else { + setEventMessages($module->error, null, 'errors'); + dol_syslog($module->error, LOG_ERR); + } + } else { + setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); + dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); + } +} elseif ($action == 'set') { // Activate a model + $ret = addDocumentModel($value, 'stocktransfer', $label, $scandir); +} elseif ($action == 'del') { + $tmpobjectkey = 'StockTransfer'; + + $ret = delDocumentModel($value, 'stocktransfer'); + if ($ret > 0) { + $constforval = strtoupper($tmpobjectkey).'_ADDON_PDF'; + if ($conf->global->$constforval == "$value") dolibarr_del_const($db, $constforval, $conf->entity); + } +} elseif ($action == 'setdoc') { // Set default model + $tmpobjectkey = 'StockTransfer'; + $constforval = strtoupper($tmpobjectkey).'_ADDON_PDF'; + if (dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity)) { + // The constant that was read before the new set + // We therefore requires a variable to have a coherent view + $conf->global->$constforval = $value; + } + + // On active le modele + $ret = delDocumentModel($value, 'stocktransfer'); + if ($ret > 0) { + $ret = addDocumentModel($value, 'stocktransfer', $label, $scandir); + } +} elseif ($action == 'setmod') { + // TODO Check if numbering module chosen can be activated + // by calling method canBeActivated + $tmpobjectkey = 'StockTransfer'; + $constforval = 'STOCKTRANSFER_'.strtoupper($tmpobjectkey)."_ADDON"; + dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); +} + + + +/* + * View + */ + +$form = new Form($db); + +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + +$page_name = "StockTransferSetup"; +llxHeader('', $langs->trans($page_name)); + +// Subheader +$linkback = ''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans($page_name), $linkback, 'stock'); + +// Configuration header +$head = stocktransferAdminPrepareHead(); +dol_fiche_head($head, 'settings', '', -1, "stocktransfer@stocktransfer"); + +// Setup page goes here +echo ''.$langs->trans("StockTransferSetupPage").''; + + +/*if ($action == 'edit') +{ + print '
'; + print ''; + print ''; + + print ''; + print ''; + + foreach ($arrayofparameters as $key => $val) + { + print ''; + } + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); + print $form->textwithpicto($langs->trans($key), $tooltiphelp); + print '
'; + + print '
'; + print ''; + print '
'; + + print '
'; + print '
'; +} else { + if (!empty($arrayofparameters)) + { + print ''; + print ''; + + foreach ($arrayofparameters as $key => $val) + { + $setupnotempty++; + + print ''; + } + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + $tooltiphelp = (($langs->trans($key.'Tooltip') != $key.'Tooltip') ? $langs->trans($key.'Tooltip') : ''); + print $form->textwithpicto($langs->trans($key), $tooltiphelp); + print ''.$conf->global->$key.'
'; + + print '
'; + print ''.$langs->trans("Modify").''; + print '
'; + } + else + { + print '
'.$langs->trans("NothingToSetup"); + } +}*/ + + +$moduledir = 'stocktransfer'; +$myTmpObjects = array(); +$myTmpObjects[$moduledir]=array('includerefgeneration'=>1, 'includedocgeneration'=>1); + +foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { + if ($myTmpObjectKey == 'MyObject') continue; + if ($myTmpObjectArray['includerefgeneration']) { + /* + * Orders Numbering model + */ + $setupnotempty++; + + print load_fiche_titre($langs->trans("NumberingModules", $myTmpObjectKey), '', ''); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''."\n"; + + clearstatcache(); + + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/".$moduledir); + + if (is_dir($dir)) { + $handle = opendir($dir); + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (strpos($file, 'mod_'.strtolower($myTmpObjectKey).'_') === 0 && substr($file, dol_strlen($file) - 3, 3) == 'php') { + $file = substr($file, 0, dol_strlen($file) - 4); + + require_once $dir.'/'.$file.'.php'; + + $module = new $file($db); + + // Show modules according to features level + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; + + if ($module->isEnabled()) { + dol_include_once('/'.$moduledir.'/class/'.strtolower($myTmpObjectKey).'.class.php'); + + print ''; + + // Show example of numbering model + print ''."\n"; + + print ''; + + $mytmpinstance = new $myTmpObjectKey($db); + $mytmpinstance->initAsSpecimen(); + + // Info + $htmltooltip = ''; + $htmltooltip .= ''.$langs->trans("Version").': '.$module->getVersion().'
'; + + $nextval = $module->getNextValue($mytmpinstance); + if ("$nextval" != $langs->trans("NotAvailable")) { // Keep " on nextval + $htmltooltip .= ''.$langs->trans("NextValue").': '; + if ($nextval) { + if (preg_match('/^Error/', $nextval) || $nextval == 'NotConfigured') + $nextval = $langs->trans($nextval); + $htmltooltip .= $nextval.'
'; + } else { + $htmltooltip .= $langs->trans($module->error).'
'; + } + } + + print ''; + + print "\n"; + } + } + } + closedir($handle); + } + } + } + print "
'.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Example").''.$langs->trans("Status").''.$langs->trans("ShortInfo").'
'.$module->name."\n"; + print $module->info(); + print ''; + $tmp = $module->getExample(); + if (preg_match('/^Error/', $tmp)) print '
'.$langs->trans($tmp).'
'; + elseif ($tmp == 'NotConfigured') print $langs->trans($tmp); + else print $tmp; + print '
'; + $constforvar = 'STOCKTRANSFER_'.strtoupper($myTmpObjectKey).'_ADDON'; + if ($conf->global->$constforvar == $file) { + print img_picto($langs->trans("Activated"), 'switch_on'); + } else { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print '

\n"; + } + + if ($myTmpObjectArray['includedocgeneration']) { + /* + * Document templates generators + */ + $setupnotempty++; + $type = strtolower($myTmpObjectKey); + + print load_fiche_titre($langs->trans("DocumentModules", $myTmpObjectKey), '', ''); + + // Load array def with activated templates + $def = array(); + $sql = "SELECT nom"; + $sql .= " FROM ".MAIN_DB_PREFIX."document_model"; + $sql .= " WHERE type = '".$db->escape($type)."'"; + $sql .= " AND entity = ".$conf->entity; + $resql = $db->query($sql); + if ($resql) { + $i = 0; + $num_rows = $db->num_rows($resql); + while ($i < $num_rows) { + $array = $db->fetch_array($resql); + array_push($def, $array[0]); + $i++; + } + } else { + dol_print_error($db); + } + + print "\n"; + print "\n"; + print ''; + print ''; + print '\n"; + print '\n"; + print ''; + print ''; + print "\n"; + + clearstatcache(); + + foreach ($dirmodels as $reldir) { + foreach (array('', '/doc') as $valdir) { + $realpath = $reldir."core/modules/".$moduledir.$valdir; + $dir = dol_buildpath($realpath); + + if (is_dir($dir)) { + $handle = opendir($dir); + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + $filelist[] = $file; + } + closedir($handle); + arsort($filelist); + + foreach ($filelist as $file) { + if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { + if (file_exists($dir.'/'.$file)) { + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); + + require_once $dir.'/'.$file; + $module = new $classname($db); + + $modulequalified = 1; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; + + if ($modulequalified) { + print ''; + + // Active + if (in_array($name, $def)) { + print ''; + } else { + print '"; + } + + // Default + print ''; + + // Info + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip .= '
'.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); + if ($module->type == 'pdf') { + $htmltooltip .= '
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + } + $htmltooltip .= '
'.$langs->trans("Path").': '.preg_replace('/^\//', '', $realpath).'/'.$file; + + $htmltooltip .= '

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
'.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + + print ''; + + // Preview + print ''; + + print "\n"; + } + } + } + } + } + } + } + } + + print '
'.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Status")."'.$langs->trans("Default")."'.$langs->trans("ShortInfo").''.$langs->trans("Preview").'
'; + print (empty($module->name) ? $name : $module->name); + print "\n"; + if (method_exists($module, 'info')) print $module->info($langs); + else print $module->description; + print ''."\n"; + print ''; + print img_picto($langs->trans("Enabled"), 'switch_on'); + print ''; + print ''."\n"; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print "'; + $constforvar = strtoupper($myTmpObjectKey).'_ADDON_PDF'; + if ($conf->global->$constforvar == $name) { + print img_picto($langs->trans("Default"), 'on'); + } else { + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + } + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print ''; + if ($module->type == 'pdf') { + print ''.img_object($langs->trans("Preview"), 'generic').''; + } else { + print img_object($langs->trans("PreviewNotAvailable"), 'generic'); + } + print '
'; + } +} + +if (empty($setupnotempty)) { + print '
'.$langs->trans("NothingToSetup"); +} + +// Page end +dol_fiche_end(); + +llxFooter(); +$db->close(); diff --git a/htdocs/admin/supplier_proposal.php b/htdocs/admin/supplier_proposal.php index 9bd684afb22..80f2c6a62f4 100644 --- a/htdocs/admin/supplier_proposal.php +++ b/htdocs/admin/supplier_proposal.php @@ -498,7 +498,7 @@ print '\n"; print ''; -if ($conf->banque->enabled) { +if (!empty($conf->banque->enabled)) { print ''; print $langs->trans("BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_PROPOSAL").' '; if (!empty($conf->use_javascript_ajax)) { diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 578e1afa497..ef4ca462008 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -1,6 +1,7 @@ - * Copyright (C) 2017-2020 Laurent Destailleur +/* Copyright (C) 2017 ATM Consulting + * Copyright (C) 2017-2020 Laurent Destailleur + * Copyright (C) 2022 charlene benke * * 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 @@ -139,76 +140,53 @@ class BlockedLog $this->trackedevents = array(); - if ($conf->facture->enabled) { + if (!empty($conf->facture->enabled)) { $this->trackedevents['BILL_VALIDATE'] = 'logBILL_VALIDATE'; - } - if ($conf->facture->enabled) { $this->trackedevents['BILL_DELETE'] = 'logBILL_DELETE'; - } - if ($conf->facture->enabled) { $this->trackedevents['BILL_SENTBYMAIL'] = 'logBILL_SENTBYMAIL'; - } - if ($conf->facture->enabled) { $this->trackedevents['DOC_DOWNLOAD'] = 'BlockedLogBillDownload'; - } - if ($conf->facture->enabled) { $this->trackedevents['DOC_PREVIEW'] = 'BlockedLogBillPreview'; - } - if ($conf->facture->enabled) { $this->trackedevents['PAYMENT_CUSTOMER_CREATE'] = 'logPAYMENT_CUSTOMER_CREATE'; - } - if ($conf->facture->enabled) { $this->trackedevents['PAYMENT_CUSTOMER_DELETE'] = 'logPAYMENT_CUSTOMER_DELETE'; } /* Supplier - if ($conf->fournisseur->enabled) $this->trackedevents['BILL_SUPPLIER_VALIDATE']='BlockedLogSupplierBillValidate'; - if ($conf->fournisseur->enabled) $this->trackedevents['BILL_SUPPLIER_DELETE']='BlockedLogSupplierBillDelete'; - if ($conf->fournisseur->enabled) $this->trackedevents['BILL_SUPPLIER_SENTBYMAIL']='BlockedLogSupplierBillSentByEmail'; // Trigger key does not exists, we want just into array to list it as done - if ($conf->fournisseur->enabled) $this->trackedevents['SUPPLIER_DOC_DOWNLOAD']='BlockedLogSupplierBillDownload'; // Trigger key does not exists, we want just into array to list it as done - if ($conf->fournisseur->enabled) $this->trackedevents['SUPPLIER_DOC_PREVIEW']='BlockedLogSupplierBillPreview'; // Trigger key does not exists, we want just into array to list it as done + if (!empty($conf->fournisseur->enabled)) { + $this->trackedevents['BILL_SUPPLIER_VALIDATE']='BlockedLogSupplierBillValidate'; + $this->trackedevents['BILL_SUPPLIER_DELETE']='BlockedLogSupplierBillDelete'; + $this->trackedevents['BILL_SUPPLIER_SENTBYMAIL']='BlockedLogSupplierBillSentByEmail'; // Trigger key does not exists, we want just into array to list it as done + $this->trackedevents['SUPPLIER_DOC_DOWNLOAD']='BlockedLogSupplierBillDownload'; // Trigger key does not exists, we want just into array to list it as done + $this->trackedevents['SUPPLIER_DOC_PREVIEW']='BlockedLogSupplierBillPreview'; // Trigger key does not exists, we want just into array to list it as done - if ($conf->fournisseur->enabled) $this->trackedevents['PAYMENT_SUPPLIER_CREATE']='BlockedLogSupplierBillPaymentCreate'; - if ($conf->fournisseur->enabled) $this->trackedevents['PAYMENT_SUPPLIER_DELETE']='BlockedLogsupplierBillPaymentCreate'; + $this->trackedevents['PAYMENT_SUPPLIER_CREATE']='BlockedLogSupplierBillPaymentCreate'; + $this->trackedevents['PAYMENT_SUPPLIER_DELETE']='BlockedLogsupplierBillPaymentCreate'; + } */ - if ($conf->don->enabled) { + if (!empty($conf->don->enabled)) { $this->trackedevents['DON_VALIDATE'] = 'logDON_VALIDATE'; - } - if ($conf->don->enabled) { $this->trackedevents['DON_DELETE'] = 'logDON_DELETE'; - } - //if ($conf->don->enabled) $this->trackedevents['DON_SENTBYMAIL']='logDON_SENTBYMAIL'; - - if ($conf->don->enabled) { + //$this->trackedevents['DON_SENTBYMAIL']='logDON_SENTBYMAIL'; $this->trackedevents['DONATION_PAYMENT_CREATE'] = 'logDONATION_PAYMENT_CREATE'; - } - if ($conf->don->enabled) { $this->trackedevents['DONATION_PAYMENT_DELETE'] = 'logDONATION_PAYMENT_DELETE'; } /* - if ($conf->salary->enabled) $this->trackedevents['PAYMENT_SALARY_CREATE']='BlockedLogSalaryPaymentCreate'; - if ($conf->salary->enabled) $this->trackedevents['PAYMENT_SALARY_MODIFY']='BlockedLogSalaryPaymentCreate'; - if ($conf->salary->enabled) $this->trackedevents['PAYMENT_SALARY_DELETE']='BlockedLogSalaryPaymentCreate'; + if (!empty($conf->salary->enabled)) { + $this->trackedevents['PAYMENT_SALARY_CREATE']='BlockedLogSalaryPaymentCreate'; + $this->trackedevents['PAYMENT_SALARY_MODIFY']='BlockedLogSalaryPaymentCreate'; + $this->trackedevents['PAYMENT_SALARY_DELETE']='BlockedLogSalaryPaymentCreate'; + } */ - if ($conf->adherent->enabled) { + if (!empty($conf->adherent->enabled)) { $this->trackedevents['MEMBER_SUBSCRIPTION_CREATE'] = 'logMEMBER_SUBSCRIPTION_CREATE'; - } - if ($conf->adherent->enabled) { $this->trackedevents['MEMBER_SUBSCRIPTION_MODIFY'] = 'logMEMBER_SUBSCRIPTION_MODIFY'; - } - if ($conf->adherent->enabled) { $this->trackedevents['MEMBER_SUBSCRIPTION_DELETE'] = 'logMEMBER_SUBSCRIPTION_DELETE'; } - if ($conf->banque->enabled) { + if (!empty($conf->banque->enabled)) { $this->trackedevents['PAYMENT_VARIOUS_CREATE'] = 'logPAYMENT_VARIOUS_CREATE'; - } - if ($conf->banque->enabled) { $this->trackedevents['PAYMENT_VARIOUS_MODIFY'] = 'logPAYMENT_VARIOUS_MODIFY'; - } - if ($conf->banque->enabled) { $this->trackedevents['PAYMENT_VARIOUS_DELETE'] = 'logPAYMENT_VARIOUS_DELETE'; } // $conf->global->BANK_ENABLE_POS_CASHCONTROL must be set to 1 by all external POS modules diff --git a/htdocs/bom/bom_net_needs.php b/htdocs/bom/bom_net_needs.php index d08cce70382..baf4b096324 100644 --- a/htdocs/bom/bom_net_needs.php +++ b/htdocs/bom/bom_net_needs.php @@ -188,7 +188,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $viewlink = dolGetButtonTitle($langs->trans('GroupByProduct'), '', 'fa fa-bars imgforviewmode', $_SERVER['PHP_SELF'].'?id='.$object->id.'&token='.newToken(), '', 1, array('morecss' => 'reposition '.($action !== 'treeview' ? 'btnTitleSelected':''))); $viewlink .= dolGetButtonTitle($langs->trans('TreeStructure'), '', 'fa fa-stream imgforviewmode', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=treeview&token='.newToken(), '', 1, array('morecss' => 'reposition marginleftonly '.($action == 'treeview' ? 'btnTitleSelected':''))); - print load_fiche_titre($langs->trans("BillOfMaterials"), $viewlink, 'cubes'); + print load_fiche_titre($langs->trans("BOMNetNeeds"), $viewlink, ''); /* * Lines diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index fb7fd68e13a..640db9bc372 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -820,13 +820,6 @@ class BOM extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('bomdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } @@ -1301,6 +1294,7 @@ class BOMLine extends CommonObjectLine */ public $childBom = array(); + /** * Constructor * @@ -1514,13 +1508,6 @@ class BOMLine extends CommonObjectLine } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('bomlinedao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 6c43e818ecc..05b1822f45f 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -37,6 +37,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/knowledgemanagement/class/knowledgerecord.class.php'; /** @@ -825,7 +826,7 @@ class Categorie extends CommonObject /** * Return list of fetched instance of elements having this category * - * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member', ...) + * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member', 'knowledge_management' ...) * @param int $onlyids Return only ids of objects (consume less memory) * @param int $limit Limit * @param int $offset Offset diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index a406bb56463..31b9f04586e 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -389,6 +389,9 @@ class ActionComm extends CommonObject const EVENT_FINISHED = 100; + public $fields = array(); + + /** * Constructor * @@ -1626,12 +1629,6 @@ class ActionComm extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($tooltip, 1, 0, '', 1).'"'; $linkclose .= ' class="'.$classname.' classfortooltip"'; - /* - $hookmanager->initHooks(array('actiondao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose); - */ } else { $linkclose .= ' class="'.$classname.'"'; } diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 34dd94664e7..f0a7e1febf8 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -642,7 +642,6 @@ $s = $newtitle; // Calendars from hooks $parameters = array(); -$object = null; $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); if (empty($reshook)) { $s .= $hookmanager->resPrint; @@ -687,7 +686,6 @@ $viewmode .= ''; // Add more views from hooks $parameters = array(); -$object = null; $reshook = $hookmanager->executeHooks('addCalendarView', $parameters, $object, $action); if (empty($reshook)) { $viewmode .= $hookmanager->resPrint; diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index 9069b63179f..95639a25997 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -135,7 +135,7 @@ if (GETPOST('exportcsv', 'int')) { $sql = "SELECT mc.rowid, mc.lastname, mc.firstname, mc.email, mc.other, mc.statut as status, mc.date_envoi, mc.tms,"; $sql .= " mc.source_id, mc.source_type, mc.error_text"; $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; - $sql .= " WHERE mc.fk_mailing=".((int) $object->id); + $sql .= " WHERE mc.fk_mailing = ".((int) $object->id); $sql .= $db->order($sortfield, $sortorder); $resql = $db->query($sql); @@ -365,17 +365,19 @@ if ($object->fetch($id) >= 0) { $obj = new $classname($db); + // Check if qualified + $qualified = (is_null($obj->enabled) ? 1 : dol_eval($obj->enabled, 1)); + // Check dependencies - $qualified = (isset($obj->enabled) ? $obj->enabled : 1); foreach ($obj->require_module as $key) { - if (!$conf->$key->enabled || (!$user->admin && $obj->require_admin)) { + if (empty($conf->$key->enabled) || (empty($user->admin) && $obj->require_admin)) { $qualified = 0; //print "Les prerequis d'activation du module mailing ne sont pas respectes. Il ne sera pas actif"; break; } } - // Si le module mailing est qualifie + // If module is qualified if ($qualified) { $var = !$var; @@ -402,7 +404,7 @@ if ($object->fetch($id) >= 0) { } print '
'; - if ($nbofrecipient >= 0) { + if ($nbofrecipient === '' || $nbofrecipient >= 0) { print $nbofrecipient; } else { print $langs->trans("Error").' '.img_error($obj->error); diff --git a/htdocs/comm/mailing/class/mailing.class.php b/htdocs/comm/mailing/class/mailing.class.php index c944d9ab216..4ea794bfbd4 100644 --- a/htdocs/comm/mailing/class/mailing.class.php +++ b/htdocs/comm/mailing/class/mailing.class.php @@ -728,13 +728,6 @@ class Mailing extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('myobjectdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index 0a182e6dcbe..576285594b4 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -335,11 +335,11 @@ foreach ($data as $val) { print ''; print ' 0 ? '&userid='.$userid : '').'">'.$year.''; print ''.$val['nb'].''; - print ''.round($val['nb_diff']).'%'; + print ''.(isset($val['nb_diff']) ? round($val['nb_diff']): "0").'%'; print ''.price(price2num($val['total'], 'MT'), 1).''; - print ''.round($val['total_diff']).'%'; + print ''.(isset($val['total_diff']) ? round($val['total_diff']) : "0").'%'; print ''.price(price2num($val['avg'], 'MT'), 1).''; - print ''.round($val['avg_diff']).'%'; + print ''.(isset($val['avg_diff']) ? round($val['avg_diff']) : "0").'%'; print ''; $oldyear = $year; } diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index 603627ee91e..3e33ddedf57 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -394,11 +394,11 @@ foreach ($data as $val) { print ''; print ' 0 ? '&userid='.$userid : '').'">'.$year.''; print ''.$val['nb'].''; - print ''.round($val['nb_diff']).'%'; + print ''.(isset($val['nb_diff']) ? round($val['nb_diff']): "0").'%'; print ''.price(price2num($val['total'], 'MT'), 1).''; - print ''.round($val['total_diff']).'%'; + print ''.(isset($val['total_diff']) ? round($val['total_diff']) : "0").'%'; print ''.price(price2num($val['avg'], 'MT'), 1).''; - print ''.round($val['avg_diff']).'%'; + print ''.(isset($val['avg_diff']) ? round($val['avg_diff']) : "0").'%'; print ''; $oldyear = $year; } diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 77aded9c594..8bad5dbebd0 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -694,13 +694,6 @@ class PaymentVarious extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('myobjectdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 90bc79483bf..8e6fb27d5f0 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -616,9 +616,18 @@ foreach ($accounts as $key => $type) { // Transactions to reconcile if (!empty($arrayfields['toreconcile']['checked'])) { - print ''; - $conciliate = $objecttmp->canBeConciliated(); + + $labeltoshow = ''; + if ($conciliate == -2) { + $labeltoshow = $langs->trans("CashAccount"); + } elseif ($conciliate == -3) { + $labeltoshow = $langs->trans("Closed"); + } elseif (empty($objecttmp->rappro)) { + $labeltoshow = $langs->trans("ConciliationDisabled"); + } + + print ''; if ($conciliate == -2) { print ''.$langs->trans("CashAccount").''; } elseif ($conciliate == -3) { diff --git a/htdocs/compta/cashcontrol/class/cashcontrol.class.php b/htdocs/compta/cashcontrol/class/cashcontrol.class.php index 63dae3a3a1c..d7744f777fe 100644 --- a/htdocs/compta/cashcontrol/class/cashcontrol.class.php +++ b/htdocs/compta/cashcontrol/class/cashcontrol.class.php @@ -439,13 +439,6 @@ class CashControl extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('myobjectdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 8cde488a2e0..22a9a2bffc8 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -1243,13 +1243,6 @@ class BonPrelevement extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('myobjectdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index 0bef7ff555a..1df7ae4db62 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -179,6 +179,7 @@ $allparams = array_merge($commonparams, $headerparams, $tableparams); $headerparams = array_merge($commonparams, $headerparams); $tableparams = array_merge($commonparams, $tableparams); +$paramslink=""; foreach ($allparams as $key => $value) { $paramslink .= '&'.$key.'='.$value; } @@ -202,6 +203,9 @@ if ($modecompta == "BOOKKEEPINGCOLLECTED") { $modecompta = "RECETTES-DEPENSES"; } +$exportlink=""; +$namelink=""; + // Show report header if ($modecompta == "CREANCES-DETTES") { $name = $langs->trans("Turnover").', '.$langs->trans("ByThirdParties"); diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index e7ec8c61db7..b99002fe609 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -144,6 +144,8 @@ llxHeader(); $form = new Form($db); +$exportlink=""; +$namelink=""; // Affiche en-tete du rapport if ($modecompta == "CREANCES-DETTES") { $name = $langs->trans("Turnover"); @@ -254,6 +256,11 @@ $sql .= " ORDER BY dm"; $minyearmonth = $maxyearmonth = 0; +$cum = array(); +$cum_ht = array(); +$total_ht = array(); +$total = array(); + $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -395,6 +402,12 @@ for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) { $case = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage), "%Y-%m"); $caseprev = dol_print_date(dol_mktime(1, 1, 1, $mois_modulo, 1, $annee_decalage - 1), "%Y-%m"); + $total_ht[$annee]=0; + $total[$annee]=0; + $cum_ht[$case]=0; + $cum[$case]=0; + + if ($annee >= $year_start) { // We ignore $annee < $year_start, we loop on it to be able to make delta, nothing is output. if ($modecompta == 'CREANCES-DETTES') { // Value turnover of month w/o VAT diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 922da9c30a8..9fa3602ee4b 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -1475,13 +1475,6 @@ class Contact extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('contactdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } $linkstart = ''; if ($object->thirdparty->client) { $thirdTypeArray['customer'] = $langs->trans("customer"); - if ($conf->propal->enabled && $user->rights->propal->lire) { + if (!empty($conf->propal->enabled) && $user->rights->propal->lire) { $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); } - if ($conf->commande->enabled && $user->rights->commande->lire) { + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); } - if ($conf->facture->enabled && $user->rights->facture->lire) { + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); } - if ($conf->contrat->enabled && $user->rights->contrat->lire) { + if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); } } diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 7ad5ceedb85..d17f5399679 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -264,10 +264,6 @@ if (empty($reshook)) { } $id = $object->create($user); - if ($id < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } - if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); @@ -379,6 +375,9 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } + if ($error) { + $action = 'create'; + } } else { $result = $object->create($user); if ($result > 0) { diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 9c9b457a533..b63690fcc32 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -7378,18 +7378,18 @@ abstract class CommonObject $checked = ' checked '; } $value = ''; - } elseif ($type == 'mail') { + } elseif ($type == 'mail' || $type == 'email') { $value = dol_print_email($value, 0, 0, 0, 64, 1, 1); } elseif ($type == 'url') { $value = dol_print_url($value, '_blank', 32, 1); } elseif ($type == 'phone') { - $value = dol_print_phone($value, '', 0, 0, '', ' ', 1); + $value = dol_print_phone($value, '', 0, 0, '', ' ', 'phone'); } elseif ($type == 'price') { if (!is_null($value) && $value !== '') { $value = price($value, 0, $langs, 0, 0, -1, $conf->currency); } } elseif ($type == 'select') { - $value = $param['options'][$value]; + $value = isset($param['options'][$value])?$param['options'][$value]:''; } elseif ($type == 'sellist') { $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); @@ -8054,7 +8054,7 @@ abstract class CommonObject // a first td column was already output (and may be another on before if MAIN_VIEW_LINE_NUMBER set), so this td is the next one $out .= ''; } elseif ($display_type == 'line') { - $out .= '
'; + $out .= '
'; } switch ($mode) { diff --git a/htdocs/core/class/commonobjectline.class.php b/htdocs/core/class/commonobjectline.class.php index c45e3f1698c..c1ba05cc279 100644 --- a/htdocs/core/class/commonobjectline.class.php +++ b/htdocs/core/class/commonobjectline.class.php @@ -77,6 +77,9 @@ abstract class CommonObjectLine extends CommonObject public $multilangs; public $product_type; // type in line + public $fk_product; // product id in line (when line is linked to a product) + + public $product; // To store full product object after a fetch_product() on a line public $product_ref; // ref in product table public $product_label; // label in product table public $product_desc; // desc in product table diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 274b408411f..e04b61291a4 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -1677,15 +1677,18 @@ class ExtraFields } } } else { - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $toprint = array(); $obj = $this->db->fetch_object($resql); - $c = new Categorie($this->db); - $c->fetch($obj->rowid); - $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text - foreach ($ways as $way) { - $toprint[] = '
  • color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.img_object('', 'category').' '.$way.'
  • '; + if ($obj->rowid) { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $c = new Categorie($this->db); + $result = $c->fetch($obj->rowid); + if ($result > 0) { + $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formatted text + foreach ($ways as $way) { + $toprint[] = '
  • color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . img_object('', 'category') . ' ' . $way . '
  • '; + } + } } $value = '
      '.implode(' ', $toprint).'
    '; } diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 95ebe740f24..dd9eabc59f6 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -867,17 +867,17 @@ class Form /** * Return combo list of activated countries, into language of user * - * @param string $selected Id or Code or Label of preselected country - * @param string $htmlname Name of html select object - * @param string $htmloption More html options on select object - * @param integer $maxlength Max length for labels (0=no limit) - * @param string $morecss More css class - * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key - * @param int $showempty Show empty choice - * @param int $disablefavorites 1=Disable favorites, - * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...) - * @param array $exclude_country_code Array of country code (iso2) to exclude - * @param int $hideflags Hide flags + * @param string $selected Id or Code or Label of preselected country + * @param string $htmlname Name of html select object + * @param string $htmloption More html options on select object + * @param integer $maxlength Max length for labels (0=no limit) + * @param string $morecss More css class + * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key + * @param int|string $showempty Show empty choice + * @param int $disablefavorites 1=Disable favorites, + * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...) + * @param array $exclude_country_code Array of country code (iso2) to exclude + * @param int $hideflags Hide flags * @return string HTML string with select */ public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array(), $hideflags = 0) @@ -926,7 +926,11 @@ class Form } if ($showempty) { - $out .= ''."\n"; + if (is_numeric($showempty)) { + $out .= ''."\n"; + } else { + $out .= ''."\n"; + } } if ($addspecialentries) { // Add dedicated entries for groups of countries @@ -8627,27 +8631,27 @@ class Form $possiblelinks = array( 'propal'=>array( - 'enabled'=>$conf->propal->enabled, + 'enabled'=>(!empty($conf->propal->enabled) ? $conf->propal->enabled : 0), 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('propal').')'), 'order'=>array( - 'enabled'=>$conf->commande->enabled, + 'enabled'=>(!empty($conf->commande->enabled) ? $conf->commande->enabled : 0), 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('commande').')'), 'invoice'=>array( - 'enabled'=>$conf->facture->enabled, + 'enabled'=>(!empty($conf->facture->enabled) ? $conf->facture->enabled : 0), 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'), 'invoice_template'=>array( - 'enabled'=>$conf->facture->enabled, + 'enabled'=>(!empty($conf->facture->enabled) ? $conf->facture->enabled : 0), 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'), 'contrat'=>array( - 'enabled'=>$conf->contrat->enabled, + 'enabled'=>(!empty($conf->contrat->enabled) ? $conf->contrat->enabled : 0), 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, SUM(td.total_ht) as total_ht diff --git a/htdocs/core/class/html.formticket.class.php b/htdocs/core/class/html.formticket.class.php index 5600f51f5e2..31a48f38cf4 100644 --- a/htdocs/core/class/html.formticket.class.php +++ b/htdocs/core/class/html.formticket.class.php @@ -346,7 +346,7 @@ class FormTicket } } - if ($conf->knowledgemanagement->enabled) { + if (!empty($conf->knowledgemanagement->enabled)) { // KM Articles print ''; print ' diff --git a/htdocs/core/lib/doc.lib.php b/htdocs/core/lib/doc.lib.php index 97eaa7d0b9e..d1a7cea5d9a 100644 --- a/htdocs/core/lib/doc.lib.php +++ b/htdocs/core/lib/doc.lib.php @@ -128,11 +128,9 @@ function doc_getlinedesc($line, $outputlangs, $hideref = 0, $hidedesc = 0, $issu } else { $ref_prodserv = $prodser->ref; // Show local ref only } - - $ref_prodserv .= " - "; } - $libelleproduitservice = $prefix_prodserv.$ref_prodserv.$libelleproduitservice; + $libelleproduitservice = $prefix_prodserv.$ref_prodserv.($libelleproduitservice ? " - " : "").$libelleproduitservice; } } diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index f768833cd39..f9f7398a4b7 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -273,7 +273,7 @@ function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $s "position" => (int) $obj->position, "acl" => $obj->acl, "share" => $obj->share, - "description" => $obj->description + "description" => isset($obj->description)?$obj->description:'' ); } $i++; diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 978d385fcda..fc743889b28 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -183,6 +183,21 @@ function isASecretKey($keyname) return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname); } + +/** + * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA' + * + * @param int|string $n Numeric value + * @return string Column in Excel format + */ +function num2Alpha($n) +{ + for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) + $r = chr($n % 26 + 0x41) . $r; + return $r; +} + + /** * Return information about user browser * @@ -3012,8 +3027,16 @@ function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetwor } } else { if (!empty($dictsocialnetworks[$type]['url'])) { + $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']); + if ($tmpvirginurl) { + $value = preg_replace('/'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value); + } $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']); - $htmllink .= ' 
    '.dol_escape_htmltag($value).''; + if (preg_match('/^https?:\/\//i', $link)) { + $htmllink .= ' '.dol_escape_htmltag($value).''; + } else { + $htmllink .= ' '.dol_escape_htmltag($value).''; + } } else { $htmllink .= dol_escape_htmltag($value); } @@ -10339,9 +10362,11 @@ function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = // Js Confirm button if ($userRight && !empty($params['confirm'])) { if (!is_array($params['confirm'])) { - $params['confirm'] = array( - 'url' => $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes' - ); + $params['confirm'] = array(); + } + + if (empty($params['confirm']['url'])) { + $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes'; } // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action diff --git a/htdocs/core/lib/usergroups.lib.php b/htdocs/core/lib/usergroups.lib.php index 3883ae11fb4..dac412f92a6 100644 --- a/htdocs/core/lib/usergroups.lib.php +++ b/htdocs/core/lib/usergroups.lib.php @@ -485,7 +485,7 @@ function showSkins($fuser, $edit = 0, $foruserprofile = false) print ''; if ($edit) { //print ajax_constantonoff('THEME_TOPMENU_DISABLE_IMAGE', array(), null, 0, 0, 1); - print $form->selectarray('THEME_TOPMENU_DISABLE_IMAGE', $listoftopmenumodes, $conf->global->THEME_TOPMENU_DISABLE_IMAGE); + print $form->selectarray('THEME_TOPMENU_DISABLE_IMAGE', $listoftopmenumodes, isset($conf->global->THEME_TOPMENU_DISABLE_IMAGE)?$conf->global->THEME_TOPMENU_DISABLE_IMAGE:0); } else { $listoftopmenumodes[$conf->global->THEME_TOPMENU_DISABLE_IMAGE]; //print yn($conf->global->THEME_TOPMENU_DISABLE_IMAGE); diff --git a/htdocs/core/menus/standard/auguria.lib.php b/htdocs/core/menus/standard/auguria.lib.php index 556ee3e609a..ea6d21fe457 100644 --- a/htdocs/core/menus/standard/auguria.lib.php +++ b/htdocs/core/menus/standard/auguria.lib.php @@ -339,7 +339,7 @@ function print_left_auguria_menu($db, $menu_array_before, $menu_array_after, &$t $newmenu = $menuArbo->menuLeftCharger($newmenu, $mainmenu, $leftmenu, ($user->socid ? 1 : 0), 'auguria', $tabMenu); // We update newmenu for special dynamic menus - if ($conf->banque->enabled && $user->rights->banque->lire && $mainmenu == 'bank') { // Entry for each bank account + if (!empty($conf->banque->enabled) && $user->rights->banque->lire && $mainmenu == 'bank') { // Entry for each bank account include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // Required for to get Account::TYPE_CASH for example $sql = "SELECT rowid, label, courant, rappro, courant"; diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index b3788d776a0..3fb069cca24 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -2049,6 +2049,12 @@ function get_left_menu_products($mainmenu, &$newmenu, $usemenuhider = 1, $leftme } } + if ($conf->stocktransfer->enabled) { + $newmenu->add('/product/stock/stocktransfer/stocktransfer_list.php', $langs->trans("ModuleStockTransferName"), 0, $user->rights->stocktransfer->stocktransfer->read, '', $mainmenu, 'stocktransfer', 0, '', '', '', img_picto('', 'stock', 'class="pictofixedwidth"')); + $newmenu->add('/product/stock/stocktransfer/stocktransfer_card.php?action=create', $langs->trans('StockTransferNew'), 1, $user->rights->stocktransfer->stocktransfer->write); + $newmenu->add('/product/stock/stocktransfer/stocktransfer_list.php', $langs->trans('List'), 1, $user->rights->stocktransfer->stocktransfer->read); + } + // Inventory if (!empty($conf->stock->enabled)) { $langs->load("stocks"); diff --git a/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php b/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php index 761aae99142..82f45497d41 100644 --- a/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php +++ b/htdocs/core/modules/bom/doc/doc_generic_bom_odt.modules.php @@ -169,7 +169,7 @@ class doc_generic_bom_odt extends ModelePDFBom $texte .= '
    '; // Show list of found files foreach ($listoffiles as $file) { - $texte .= '- '.$file['name'].' '.img_picto('', 'listlight').'
    '; + $texte .= '- '.$file['name'].' '.img_picto('', 'listlight').'
    '; } $texte .= '
    '; } @@ -406,10 +406,22 @@ class doc_generic_bom_odt extends ModelePDFBom $foundtagforlines = 0; dol_syslog($e->getMessage(), LOG_INFO); } + if ($foundtagforlines) { $linenumber = 0; foreach ($object->lines as $line) { $linenumber++; + + if ($line->fk_product > 0) { + $line->fetch_product(); + + $line->product_ref = $line->product->ref; + $line->product_desc = $line->product->description; + $line->product_label = $line->product->label; + $line->product_type = $line->product->type; + $line->product_barcode = $line->product->barcode; + } + $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber); complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); // Call the ODTSubstitutionLine hook diff --git a/htdocs/core/modules/import/import_csv.modules.php b/htdocs/core/modules/import/import_csv.modules.php index 16568288aa4..8c3e5bfeab9 100644 --- a/htdocs/core/modules/import/import_csv.modules.php +++ b/htdocs/core/modules/import/import_csv.modules.php @@ -750,13 +750,6 @@ class ImportCsv extends ModeleImports $i++; } - // We db escape social network field because he isn't in field creation - if (in_array("socialnetworks", $listfields)) { - $socialkey = array_search("socialnetworks", $listfields); - $tmpsql = $listvalues[$socialkey]; - $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'"; - } - // We add hidden fields (but only if there is at least one field to add into table) // We process here all the fields that were declared into the array $this->import_fieldshidden_array of the descriptor file. // Previously we processed the ->import_fields_array. @@ -819,11 +812,18 @@ class ImportCsv extends ModeleImports $updatedone = false; $insertdone = false; + $is_table_category_link = false; + $fname = 'rowid'; + if (strpos($tablename, '_categorie_') !== false) { + $is_table_category_link = true; + $fname='*'; + } + if (!empty($updatekeys)) { // We do SELECT to get the rowid, if we already have the rowid, it's to be used below for related tables (extrafields) if (empty($lastinsertid)) { // No insert done yet for a parent table - $sqlSelect = "SELECT rowid FROM ".$tablename; + $sqlSelect = "SELECT ".$fname." FROM ".$tablename; $data = array_combine($listfields, $listvalues); $where = array(); @@ -831,8 +831,18 @@ class ImportCsv extends ModeleImports foreach ($updatekeys as $key) { $col = $objimport->array_import_updatekeys[0][$key]; $key = preg_replace('/^.*\./i', '', $key); - $where[] = $key.' = '.$data[$key]; - $filters[] = $col.' = '.$data[$key]; + if ($conf->socialnetworks->enabled && strpos($key, "socialnetworks") !== false) { + $tmp = explode("_", $key); + $key = $tmp[0]; + $socialnetwork = $tmp[1]; + $jsondata = $data[$key]; + $json = json_decode($jsondata); + $where[] = $key." LIKE '%\"".$socialnetwork."\":\"".$this->db->escape($json->$socialnetwork)."\"%'"; + $filters[] = $col." LIKE '%\"".$socialnetwork."\":\"".$this->db->escape($json->$socialnetwork)."\"%'"; + } else { + $where[] = $key.' = '.$data[$key]; + $filters[] = $col.' = '.$data[$key]; + } } $sqlSelect .= " WHERE ".implode(' AND ', $where); @@ -842,6 +852,7 @@ class ImportCsv extends ModeleImports if ($num_rows == 1) { $res = $this->db->fetch_object($resql); $lastinsertid = $res->rowid; + if ($is_table_category_link) $lastinsertid = 'linktable'; // used to apply update on tables like llx_categorie_product and avoid being blocked for all file content if at least one entry already exists $last_insert_id_array[$tablename] = $lastinsertid; } elseif ($num_rows > 1) { $this->errors[$error]['lib'] = $langs->trans('MultipleRecordFoundWithTheseFilters', implode(', ', $filters)); @@ -888,6 +899,13 @@ class ImportCsv extends ModeleImports } if (!empty($lastinsertid)) { + // We db escape social network field because he isn't in field creation + if (in_array("socialnetworks", $listfields)) { + $socialkey = array_search("socialnetworks", $listfields); + $tmpsql = $listvalues[$socialkey]; + $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'"; + } + // Build SQL UPDATE request $sqlstart = "UPDATE ".$tablename; @@ -903,6 +921,10 @@ class ImportCsv extends ModeleImports } $sqlend = " WHERE ".$keyfield." = ".((int) $lastinsertid); + if ($is_table_category_link) { + $sqlend = " WHERE " . implode(' AND ', $where); + } + $sql = $sqlstart.$sqlend; // Run update request @@ -921,6 +943,13 @@ class ImportCsv extends ModeleImports // Update not done, we do insert if (!$error && !$updatedone) { + // We db escape social network field because he isn't in field creation + if (in_array("socialnetworks", $listfields)) { + $socialkey = array_search("socialnetworks", $listfields); + $tmpsql = $listvalues[$socialkey]; + $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'"; + } + // Build SQL INSERT request $sqlstart = "INSERT INTO ".$tablename."(".implode(", ", $listfields).", import_key"; $sqlend = ") VALUES(".implode(', ', $listvalues).", '".$this->db->escape($importid)."'"; diff --git a/htdocs/core/modules/import/import_xlsx.modules.php b/htdocs/core/modules/import/import_xlsx.modules.php index d16a9a764eb..4740f7d3390 100644 --- a/htdocs/core/modules/import/import_xlsx.modules.php +++ b/htdocs/core/modules/import/import_xlsx.modules.php @@ -1,6 +1,6 @@ - * Copyright (C) 2009-2012 Regis Houssin +/* Copyright (C) 2006-2012 Laurent Destailleur + * Copyright (C) 2009-2012 Regis Houssin * Copyright (C) 2012 Christophe Battarel * Copyright (C) 2012-2016 Juanjo Menent * @@ -446,7 +446,7 @@ class ImportXlsx extends ModeleImports // Is it a required field ? if (preg_match('/\*/', $objimport->array_import_fields[0][$val]) && ((string) $newval == '')) { - $this->errors[$error]['lib'] = $langs->trans('ErrorMissingMandatoryValue', $key); + $this->errors[$error]['lib'] = $langs->trans('ErrorMissingMandatoryValue', num2Alpha($key - 1)); $this->errors[$error]['type'] = 'NOTNULL'; $errorforthistable++; $error++; @@ -795,13 +795,6 @@ class ImportXlsx extends ModeleImports $i++; } - // We db escape social network field because he isn't in field creation - if (in_array("socialnetworks", $listfields)) { - $socialkey = array_search("socialnetworks", $listfields); - $tmpsql = $listvalues[$socialkey]; - $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'"; - } - // We add hidden fields (but only if there is at least one field to add into table) // We process here all the fields that were declared into the array $this->import_fieldshidden_array of the descriptor file. // Previously we processed the ->import_fields_array. @@ -863,11 +856,19 @@ class ImportXlsx extends ModeleImports if (!empty($listfields)) { $updatedone = false; $insertdone = false; + + $is_table_category_link = false; + $fname = 'rowid'; + if (strpos($tablename, '_categorie_') !== false) { + $is_table_category_link = true; + $fname='*'; + } + if (!empty($updatekeys)) { // We do SELECT to get the rowid, if we already have the rowid, it's to be used below for related tables (extrafields) if (empty($lastinsertid)) { // No insert done yet for a parent table - $sqlSelect = "SELECT rowid FROM " . $tablename; + $sqlSelect = "SELECT ".$fname." FROM " . $tablename; $data = array_combine($listfields, $listvalues); $where = array(); @@ -875,8 +876,18 @@ class ImportXlsx extends ModeleImports foreach ($updatekeys as $key) { $col = $objimport->array_import_updatekeys[0][$key]; $key = preg_replace('/^.*\./i', '', $key); - $where[] = $key . ' = ' . $data[$key]; - $filters[] = $col . ' = ' . $data[$key]; + if ($conf->socialnetworks->enabled && strpos($key, "socialnetworks") !== false) { + $tmp = explode("_", $key); + $key = $tmp[0]; + $socialnetwork = $tmp[1]; + $jsondata = $data[$key]; + $json = json_decode($jsondata); + $where[] = $key." LIKE '%\"".$socialnetwork."\":\"".$this->db->escape($json->$socialnetwork)."\"%'"; + $filters[] = $col." LIKE '%\"".$socialnetwork."\":\"".$this->db->escape($json->$socialnetwork)."\"%'"; + } else { + $where[] = $key.' = '.$data[$key]; + $filters[] = $col.' = '.$data[$key]; + } } $sqlSelect .= " WHERE " . implode(' AND ', $where); @@ -886,6 +897,7 @@ class ImportXlsx extends ModeleImports if ($num_rows == 1) { $res = $this->db->fetch_object($resql); $lastinsertid = $res->rowid; + if ($is_table_category_link) $lastinsertid = 'linktable'; // used to apply update on tables like llx_categorie_product and avoid being blocked for all file content if at least one entry already exists $last_insert_id_array[$tablename] = $lastinsertid; } elseif ($num_rows > 1) { $this->errors[$error]['lib'] = $langs->trans('MultipleRecordFoundWithTheseFilters', implode(', ', $filters)); @@ -911,7 +923,7 @@ class ImportXlsx extends ModeleImports if (empty($keyfield)) { $keyfield = 'rowid'; } - $sqlSelect .= "WHERE ".$keyfield." = ".((int) $lastinsertid); + $sqlSelect .= " WHERE ".$keyfield." = ".((int) $lastinsertid); $resql = $this->db->query($sqlSelect); if ($resql) { @@ -932,6 +944,13 @@ class ImportXlsx extends ModeleImports } if (!empty($lastinsertid)) { + // We db escape social network field because he isn't in field creation + if (in_array("socialnetworks", $listfields)) { + $socialkey = array_search("socialnetworks", $listfields); + $tmpsql = $listvalues[$socialkey]; + $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'"; + } + // Build SQL UPDATE request $sqlstart = "UPDATE " . $tablename; @@ -947,6 +966,10 @@ class ImportXlsx extends ModeleImports } $sqlend = " WHERE " . $keyfield . " = ".((int) $lastinsertid); + if ($is_table_category_link) { + $sqlend = " WHERE " . implode(' AND ', $where); + } + $sql = $sqlstart . $sqlend; // Run update request @@ -965,6 +988,13 @@ class ImportXlsx extends ModeleImports // Update not done, we do insert if (!$error && !$updatedone) { + // We db escape social network field because he isn't in field creation + if (in_array("socialnetworks", $listfields)) { + $socialkey = array_search("socialnetworks", $listfields); + $tmpsql = $listvalues[$socialkey]; + $listvalues[$socialkey] = "'".$this->db->escape($tmpsql)."'"; + } + // Build SQL INSERT request $sqlstart = "INSERT INTO " . $tablename . "(" . implode(", ", $listfields) . ", import_key"; $sqlend = ") VALUES(" . implode(', ', $listvalues) . ", '" . $this->db->escape($importid) . "'"; diff --git a/htdocs/core/modules/mailings/advthirdparties.modules.php b/htdocs/core/modules/mailings/advthirdparties.modules.php index 538e5389727..688db8b8e7f 100644 --- a/htdocs/core/modules/mailings/advthirdparties.modules.php +++ b/htdocs/core/modules/mailings/advthirdparties.modules.php @@ -42,6 +42,8 @@ class mailing_advthirdparties extends MailingTargets */ public $db; + public $enabled = '$conf->societe->enabled'; + /** * Constructor @@ -198,8 +200,8 @@ class mailing_advthirdparties extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Not use here - * @return int Nb of recipients + * @param string $sql Not use here + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { @@ -210,8 +212,7 @@ class mailing_advthirdparties extends MailingTargets $sql .= " WHERE s.email != ''"; $sql .= " AND s.entity IN (".getEntity('societe').")"; - // La requete doit retourner un champ "nb" pour etre comprise - // par parent::getNbOfRecipients + // La requete doit retourner un champ "nb" pour etre comprise par parent::getNbOfRecipients return parent::getNbOfRecipients($sql); } diff --git a/htdocs/core/modules/mailings/contacts1.modules.php b/htdocs/core/modules/mailings/contacts1.modules.php index 69b48fd6e32..e3e349d2a17 100644 --- a/htdocs/core/modules/mailings/contacts1.modules.php +++ b/htdocs/core/modules/mailings/contacts1.modules.php @@ -38,6 +38,8 @@ class mailing_contacts1 extends MailingTargets public $require_module = array("societe"); // Module mailing actif si modules require_module actifs public $require_admin = 0; // Module mailing actif pour user admin ou non + public $enabled = '$conf->societe->enabled'; + /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ @@ -92,8 +94,8 @@ class mailing_contacts1 extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Requete sql de comptage - * @return int + * @param string $sql Requete sql de comptage + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { diff --git a/htdocs/core/modules/mailings/example.modules.php b/htdocs/core/modules/mailings/example.modules.php index bd553e1fd5d..739ab773196 100644 --- a/htdocs/core/modules/mailings/example.modules.php +++ b/htdocs/core/modules/mailings/example.modules.php @@ -111,8 +111,8 @@ class mailing_example extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Requete sql de comptage - * @return int|string Number of recipient or '?' + * @param string $sql Requete sql de comptage + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { diff --git a/htdocs/core/modules/mailings/fraise.modules.php b/htdocs/core/modules/mailings/fraise.modules.php index aa7c218417b..992539cc303 100644 --- a/htdocs/core/modules/mailings/fraise.modules.php +++ b/htdocs/core/modules/mailings/fraise.modules.php @@ -41,6 +41,8 @@ class mailing_fraise extends MailingTargets public $require_module = array('adherent'); + public $enabled = '$conf->adherent->enabled'; + /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ @@ -91,8 +93,8 @@ class mailing_fraise extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Requete sql de comptage - * @return int Nb of recipients + * @param string $sql Requete sql de comptage + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { @@ -100,8 +102,7 @@ class mailing_fraise extends MailingTargets $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a"; $sql .= " WHERE (a.email IS NOT NULL AND a.email != '') AND a.entity IN (".getEntity('member').")"; - // La requete doit retourner un champ "nb" pour etre comprise - // par parent::getNbOfRecipients + // La requete doit retourner un champ "nb" pour etre comprise par parent::getNbOfRecipients return parent::getNbOfRecipients($sql); } diff --git a/htdocs/core/modules/mailings/modules_mailings.php b/htdocs/core/modules/mailings/modules_mailings.php index 9df8d44daf1..2064613d1e9 100644 --- a/htdocs/core/modules/mailings/modules_mailings.php +++ b/htdocs/core/modules/mailings/modules_mailings.php @@ -36,6 +36,11 @@ class MailingTargets // This can't be abstract as it is used for some method */ public $db; + /** + * @var string Condition to be enabled + */ + public $enabled; + /** * @var string Error code (or message) */ @@ -94,8 +99,8 @@ class MailingTargets // This can't be abstract as it is used for some method /** * Retourne nombre de destinataires * - * @param string $sql Sql request to count - * @return int Nb of recipient, or <0 if error + * @param string $sql Sql request to count + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql) { diff --git a/htdocs/core/modules/mailings/partnership.modules.php b/htdocs/core/modules/mailings/partnership.modules.php index b41a5e04c85..7813d93f54d 100644 --- a/htdocs/core/modules/mailings/partnership.modules.php +++ b/htdocs/core/modules/mailings/partnership.modules.php @@ -41,6 +41,8 @@ class mailing_partnership extends MailingTargets */ public $db; + public $enabled = '$conf->partnership->enabled'; + /** * Constructor @@ -164,8 +166,8 @@ class mailing_partnership extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Requete sql de comptage - * @return int Nb of recipients + * @param string $sql Requete sql de comptage + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { @@ -185,8 +187,7 @@ class mailing_partnership extends MailingTargets //print $sql; - // La requete doit retourner un champ "nb" pour etre comprise - // par parent::getNbOfRecipients + // La requete doit retourner un champ "nb" pour etre comprise par parent::getNbOfRecipients return parent::getNbOfRecipients($sql); } diff --git a/htdocs/core/modules/mailings/pomme.modules.php b/htdocs/core/modules/mailings/pomme.modules.php index 56d62449bcf..7fdcdeb0c60 100644 --- a/htdocs/core/modules/mailings/pomme.modules.php +++ b/htdocs/core/modules/mailings/pomme.modules.php @@ -89,8 +89,8 @@ class mailing_pomme extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql SQL request to use to count - * @return int Number of recipients + * @param string $sql SQL request to use to count + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { @@ -101,8 +101,7 @@ class mailing_pomme extends MailingTargets $sql .= " WHERE u.email != ''"; // u.email IS NOT NULL est implicite dans ce test $sql .= " AND u.entity IN (0,".$conf->entity.")"; - // La requete doit retourner un champ "nb" pour etre comprise - // par parent::getNbOfRecipients + // La requete doit retourner un champ "nb" pour etre comprise par parent::getNbOfRecipients return parent::getNbOfRecipients($sql); } diff --git a/htdocs/core/modules/mailings/thirdparties.modules.php b/htdocs/core/modules/mailings/thirdparties.modules.php index a18103b40f9..073d45439eb 100644 --- a/htdocs/core/modules/mailings/thirdparties.modules.php +++ b/htdocs/core/modules/mailings/thirdparties.modules.php @@ -31,6 +31,8 @@ class mailing_thirdparties extends MailingTargets public $require_module = array("societe"); // This module allows to select by categories must be also enabled if category module is not activated + public $enabled = '$conf->societe->enabled'; + /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ @@ -209,8 +211,8 @@ class mailing_thirdparties extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Requete sql de comptage - * @return int Nb of recipients + * @param string $sql Requete sql de comptage + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { @@ -221,8 +223,7 @@ class mailing_thirdparties extends MailingTargets $sql .= " WHERE s.email <> ''"; $sql .= " AND s.entity IN (".getEntity('societe').")"; - // La requete doit retourner un champ "nb" pour etre comprise - // par parent::getNbOfRecipients + // La requete doit retourner un champ "nb" pour etre comprise par parent::getNbOfRecipients return parent::getNbOfRecipients($sql); } diff --git a/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php b/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php index 09f4cf76ae6..b5dec9cbbe0 100644 --- a/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php +++ b/htdocs/core/modules/mailings/thirdparties_services_expired.modules.php @@ -29,6 +29,8 @@ class mailing_thirdparties_services_expired extends MailingTargets public $require_module = array('contrat'); + public $enabled = '$conf->societe->enabled'; + /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png */ @@ -182,8 +184,8 @@ class mailing_thirdparties_services_expired extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql SQL request to use to count - * @return int Number of recipients + * @param string $sql SQL request to use to count + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { diff --git a/htdocs/core/modules/mailings/xinputfile.modules.php b/htdocs/core/modules/mailings/xinputfile.modules.php index 3ece88d4c1d..77044ddb29e 100644 --- a/htdocs/core/modules/mailings/xinputfile.modules.php +++ b/htdocs/core/modules/mailings/xinputfile.modules.php @@ -77,8 +77,8 @@ class mailing_xinputfile extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Sql request to count - * @return string '' means NA + * @param string $sql Sql request to count + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { diff --git a/htdocs/core/modules/mailings/xinputuser.modules.php b/htdocs/core/modules/mailings/xinputuser.modules.php index b2874b43ca0..117a5722c3c 100644 --- a/htdocs/core/modules/mailings/xinputuser.modules.php +++ b/htdocs/core/modules/mailings/xinputuser.modules.php @@ -77,8 +77,8 @@ class mailing_xinputuser extends MailingTargets * For example if this selector is used to extract 500 different * emails from a text file, this function must return 500. * - * @param string $sql Sql request to count - * @return string '' means NA + * @param string $sql Sql request to count + * @return int|string Nb of recipient, or <0 if error, or '' if NA */ public function getNbOfRecipients($sql = '') { diff --git a/htdocs/core/modules/modCategorie.class.php b/htdocs/core/modules/modCategorie.class.php index 6ee294eff58..9e138c6ccef 100644 --- a/htdocs/core/modules/modCategorie.class.php +++ b/htdocs/core/modules/modCategorie.class.php @@ -481,6 +481,7 @@ class modCategorie extends DolibarrModules 'cp.fk_product'=>array('rule'=>'fetchidfromref', 'classfile'=>'/product/class/product.class.php', 'class'=>'Product', 'method'=>'fetch', 'element'=>'Product') ); $this->import_examplevalues_array[$r] = array('cp.fk_categorie'=>"rowid or label", 'cp.fk_product'=>"rowid or ref"); + $this->import_updatekeys_array[$r] = array('cp.fk_categorie' => 'Category', 'cp.fk_product' => 'ProductRef'); } // 1 Suppliers diff --git a/htdocs/core/modules/modSociete.class.php b/htdocs/core/modules/modSociete.class.php index a6d9b95d19c..322988e7a7b 100644 --- a/htdocs/core/modules/modSociete.class.php +++ b/htdocs/core/modules/modSociete.class.php @@ -693,6 +693,15 @@ class modSociete extends DolibarrModules 's.code_compta' => 'CustomerAccountancyCode', 's.code_compta_fournisseur' => 'SupplierAccountancyCode' ); + if (!empty($conf->socialnetworks->enabled)) { + $sql = "SELECT code, label FROM ".MAIN_DB_PREFIX."c_socialnetworks WHERE active = 1"; + $resql = $this->db->query($sql); + while ($obj = $this->db->fetch_object($resql)) { + $fieldname = 's.socialnetworks_'.$obj->code; + $fieldlabel = ucfirst($obj->label); + $this->import_updatekeys_array[$r][$fieldname] = $fieldlabel; + } + } // Add profids as criteria to search duplicates $langs->load("companies"); $i=1; diff --git a/htdocs/core/modules/modStockTransfer.class.php b/htdocs/core/modules/modStockTransfer.class.php new file mode 100644 index 00000000000..376cf9409f2 --- /dev/null +++ b/htdocs/core/modules/modStockTransfer.class.php @@ -0,0 +1,507 @@ + + * Copyright (C) 2018-2019 Nicolas ZABOURI + * Copyright (C) 2019-2020 Frédéric France + * Copyright (C) 2021 SuperAdmin + * Copyright (C) 2021 Gauthier VERDOL + * + * 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 . + */ + +/** + * \defgroup stocktransfer Module StockTransfer + * \brief StockTransfer module descriptor. + * + * \file htdocs/stocktransfer/core/modules/modStockTransfer.class.php + * \ingroup stocktransfer + * \brief Description and activation file for module StockTransfer + */ +include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; + +/** + * Description and activation class for module StockTransfer + */ +class modStockTransfer extends DolibarrModules +{ + /** + * Constructor. Define names, constants, directories, boxes, permissions + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $langs, $conf; + $this->db = $db; + + $langs->load('stocks'); + // Id for module (must be unique). + // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id). + $this->numero = 701; // TODO Go on page https://wiki.dolibarr.org/index.php/List_of_modules_id to reserve an id number for your module + // Key text used to identify module (for permissions, menus, etc...) + $this->rights_class = 'stocktransfer'; + // Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...' + // It is used to group modules by family in module setup page + $this->family = "other"; + // Module position in the family on 2 digits ('01', '10', '20', ...) + $this->module_position = '90'; + // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this) + //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily"))); + // Module label (no space allowed), used if translation string 'ModuleStockTransferName' not found (StockTransfer is name of module). + $this->name = preg_replace('/^mod/i', '', get_class($this)); + // Module description, used if translation string 'ModuleStockTransferDesc' not found (StockTransfer is name of module). + $this->description = $langs->trans("ModuleStockTransferDesc"); + // Used only if file README.md and README-LL.md not found. + $this->descriptionlong = "StockTransfer description (Long)"; + $this->editor_name = 'Editor name'; + $this->editor_url = 'https://www.example.com'; + // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z' + $this->version = 'development'; + // Url to the file with your last numberversion of this module + //$this->url_last_version = 'http://www.example.com/versionmodule.txt'; + + // Key used in llx_const table to save module status enabled/disabled (where STOCKTRANSFER is value of property name of module in uppercase) + $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + // Name of image file used for this module. + // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' + // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' + $this->picto = 'stock'; + // Define some features supported by module (triggers, login, substitutions, menus, css, etc...) + $this->module_parts = array( + // Set this to 1 if module has its own trigger directory (core/triggers) + 'triggers' => 0, + // Set this to 1 if module has its own login method file (core/login) + 'login' => 0, + // Set this to 1 if module has its own substitution function file (core/substitutions) + 'substitutions' => 0, + // Set this to 1 if module has its own menus handler directory (core/menus) + 'menus' => 0, + // Set this to 1 if module overwrite template dir (core/tpl) + 'tpl' => 0, + // Set this to 1 if module has its own barcode directory (core/modules/barcode) + 'barcode' => 0, + // Set this to 1 if module has its own models directory (core/modules/xxx) + 'models' => 1, + // Set this to 1 if module has its own theme directory (theme) + 'theme' => 0, + // Set this to relative path of css file if module has its own css file + 'css' => array( + // '/stocktransfer/css/stocktransfer.css.php', + ), + // Set this to relative path of js file if module must load a js on all pages + 'js' => array( + // '/stocktransfer/js/stocktransfer.js.php', + ), + // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context to 'all' + 'hooks' => array( + // 'data' => array( + // 'hookcontext1', + // 'hookcontext2', + // ), + // 'entity' => '0', + ), + // Set this to 1 if features of module are opened to external users + 'moduleforexternal' => 0, + 'contactelement'=>1 + ); + // Data directories to create when module is enabled. + // Example: this->dirs = array("/stocktransfer/temp","/stocktransfer/subdir"); + $this->dirs = array("/stocktransfer/temp"); + // Config pages. Put here list of php page, stored into stocktransfer/admin directory, to use to setup module. + $this->config_page_url = array("stocktransfer.php"); + // Dependencies + // A condition to hide module + $this->hidden = false; + // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...) + $this->depends = array('modStock', 'modProduct'); + $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) + $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) + $this->langfiles = array("stocktransfer@stocktransfer"); + $this->phpmin = array(5, 5); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(11, -3); // Minimum version of Dolibarr required by module + $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + //$this->automatic_activation = array('FR'=>'StockTransferWasAutomaticallyActivatedBecauseOfYourCountryChoice'); + //$this->always_enabled = true; // If true, can't be disabled + + // Constants + // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) + // Example: $this->const=array(1 => array('STOCKTRANSFER_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1), + // 2 => array('STOCKTRANSFER_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1) + // ); + $this->const = array(); + + // Some keys to add into the overwriting translation tables + /*$this->overwrite_translation = array( + 'en_US:ParentCompany'=>'Parent company or reseller', + 'fr_FR:ParentCompany'=>'Maison mère ou revendeur' + )*/ + + if (!isset($conf->stocktransfer) || !isset($conf->stocktransfer->enabled)) { + $conf->stocktransfer = new stdClass(); + $conf->stocktransfer->enabled = 0; + } + + // Array to add new pages in new tabs + $this->tabs = array(); + // Example: + // $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@stocktransfer:$user->rights->stocktransfer->read:/stocktransfer/mynewtab1.php?id=__ID__'); // To add a new tab identified by code tabname1 + // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@stocktransfer:$user->rights->othermodule->read:/stocktransfer/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key. + // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname + // + // Where objecttype can be + // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) + // 'contact' to add a tab in contact view + // 'contract' to add a tab in contract view + // 'group' to add a tab in group view + // 'intervention' to add a tab in intervention view + // 'invoice' to add a tab in customer invoice view + // 'invoice_supplier' to add a tab in supplier invoice view + // 'member' to add a tab in fundation member view + // 'opensurveypoll' to add a tab in opensurvey poll view + // 'order' to add a tab in customer order view + // 'order_supplier' to add a tab in supplier order view + // 'payment' to add a tab in payment view + // 'payment_supplier' to add a tab in supplier payment view + // 'product' to add a tab in product view + // 'propal' to add a tab in propal view + // 'project' to add a tab in project view + // 'stock' to add a tab in stock view + // 'thirdparty' to add a tab in third party view + // 'user' to add a tab in user view + + // Dictionaries + $this->dictionaries = array(); + /* Example: + $this->dictionaries=array( + 'langs'=>'stocktransfer@stocktransfer', + // List of tables we want to see into dictonnary editor + 'tabname'=>array(MAIN_DB_PREFIX."table1", MAIN_DB_PREFIX."table2", MAIN_DB_PREFIX."table3"), + // Label of tables + 'tablib'=>array("Table1", "Table2", "Table3"), + // Request to select fields + 'tabsql'=>array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table1 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table2 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table3 as f'), + // Sort order + 'tabsqlsort'=>array("label ASC", "label ASC", "label ASC"), + // List of fields (result of select to show dictionary) + 'tabfield'=>array("code,label", "code,label", "code,label"), + // List of fields (list of fields to edit a record) + 'tabfieldvalue'=>array("code,label", "code,label", "code,label"), + // List of fields (list of fields for insert) + 'tabfieldinsert'=>array("code,label", "code,label", "code,label"), + // Name of columns with primary key (try to always name it 'rowid') + 'tabrowid'=>array("rowid", "rowid", "rowid"), + // Condition to show each dictionary + 'tabcond'=>array($conf->stocktransfer->enabled, $conf->stocktransfer->enabled, $conf->stocktransfer->enabled) + ); + */ + + // Boxes/Widgets + // Add here list of php file(s) stored in stocktransfer/core/boxes that contains a class to show a widget. + $this->boxes = array( + // 0 => array( + // 'file' => 'stocktransferwidget1.php@stocktransfer', + // 'note' => 'Widget provided by StockTransfer', + // 'enabledbydefaulton' => 'Home', + // ), + // ... + ); + + // Cronjobs (List of cron jobs entries to add when module is enabled) + // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week + $this->cronjobs = array( + // 0 => array( + // 'label' => 'MyJob label', + // 'jobtype' => 'method', + // 'class' => '/stocktransfer/class/stocktransfer.class.php', + // 'objectname' => 'StockTransfer', + // 'method' => 'doScheduledJob', + // 'parameters' => '', + // 'comment' => 'Comment', + // 'frequency' => 2, + // 'unitfrequency' => 3600, + // 'status' => 0, + // 'test' => '$conf->stocktransfer->enabled', + // 'priority' => 50, + // ), + ); + // Example: $this->cronjobs=array( + // 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->stocktransfer->enabled', 'priority'=>50), + // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->stocktransfer->enabled', 'priority'=>50) + // ); + + // Permissions provided by this module + $this->rights = array(); + $r = 10; + // Add here entries to declare new permissions + /* BEGIN MODULEBUILDER PERMISSIONS */ + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = $langs->trans('StockTransferRightRead'); // Permission label + $this->rights[$r][4] = 'stocktransfer'; // In php code, permission will be checked by test if ($user->rights->stocktransfer->level1->level2) + $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->stocktransfer->level1->level2) + $r++; + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = $langs->trans('StockTransferRightCreateUpdate'); // Permission label + $this->rights[$r][4] = 'stocktransfer'; // In php code, permission will be checked by test if ($user->rights->stocktransfer->level1->level2) + $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->stocktransfer->level1->level2) + $r++; + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = $langs->trans('StockTransferRightDelete'); // Permission label + $this->rights[$r][4] = 'stocktransfer'; // In php code, permission will be checked by test if ($user->rights->stocktransfer->level1->level2) + $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->stocktransfer->level1->level2) + $r++; + /* END MODULEBUILDER PERMISSIONS */ + + // Main menu entries to add + $langs->load('stocktransfer@stocktransfer'); + $this->menu = array(); + $r = 0; + // Add here entries to declare new menus + /* BEGIN MODULEBUILDER TOPMENU */ + /*$this->menu[$r++] = array( + 'fk_menu'=>'', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'top', // This is a Top menu entry + 'titre'=>'ModuleStockTransferName', + 'mainmenu'=>'stocktransfer', + 'leftmenu'=>'', + 'url'=>'/stocktransfer/stocktransferindex.php', + 'langs'=>'stocktransfer@stocktransfer', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000 + $r, + 'enabled'=>'$conf->stocktransfer->enabled', // Define condition to show or hide menu entry. Use '$conf->stocktransfer->enabled' if entry must be visible if module is enabled. + 'perms'=>'1', // Use 'perms'=>'$user->rights->stocktransfer->stocktransfer->read' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + );*/ + /* END MODULEBUILDER TOPMENU */ + /* BEGIN MODULEBUILDER LEFTMENU STOCKTRANSFER + $this->menu[$r++]=array( + 'fk_menu'=>'fk_mainmenu=stocktransfer', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'left', // This is a Top menu entry + 'titre'=>'StockTransfer', + 'mainmenu'=>'stocktransfer', + 'leftmenu'=>'stocktransfer', + 'url'=>'/stocktransfer/stocktransferindex.php', + 'langs'=>'stocktransfer@stocktransfer', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000+$r, + 'enabled'=>'$conf->stocktransfer->enabled', // Define condition to show or hide menu entry. Use '$conf->stocktransfer->enabled' if entry must be visible if module is enabled. + 'perms'=>'$user->rights->stocktransfer->stocktransfer->read', // Use 'perms'=>'$user->rights->stocktransfer->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + ); + $this->menu[$r++]=array( + 'fk_menu'=>'fk_mainmenu=stocktransfer,fk_leftmenu=stocktransfer', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'left', // This is a Left menu entry + 'titre'=>'List StockTransfer', + 'mainmenu'=>'stocktransfer', + 'leftmenu'=>'stocktransfer_stocktransfer_list', + 'url'=>'/stocktransfer/stocktransfer_list.php', + 'langs'=>'stocktransfer@stocktransfer', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000+$r, + 'enabled'=>'$conf->stocktransfer->enabled', // Define condition to show or hide menu entry. Use '$conf->stocktransfer->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'perms'=>'$user->rights->stocktransfer->stocktransfer->read', // Use 'perms'=>'$user->rights->stocktransfer->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + ); + $this->menu[$r++]=array( + 'fk_menu'=>'fk_mainmenu=stocktransfer,fk_leftmenu=stocktransfer', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type'=>'left', // This is a Left menu entry + 'titre'=>'New StockTransfer', + 'mainmenu'=>'stocktransfer', + 'leftmenu'=>'stocktransfer_stocktransfer_new', + 'url'=>'/stocktransfer/stocktransfer_card.php?action=create', + 'langs'=>'stocktransfer@stocktransfer', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position'=>1000+$r, + 'enabled'=>'$conf->stocktransfer->enabled', // Define condition to show or hide menu entry. Use '$conf->stocktransfer->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'perms'=>'$user->rights->stocktransfer->stocktransfer->write', // Use 'perms'=>'$user->rights->stocktransfer->level1->level2' if you want your menu with a permission rules + 'target'=>'', + 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + ); + */ + + /*$this->menu[$r++]=array( + // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'fk_menu'=>'fk_mainmenu=products,fk_leftmenu=stock', + // This is a Left menu entry + 'type'=>'left', + 'titre'=>$langs->trans('StockTransferNew'), + 'mainmenu'=>'products', + 'leftmenu'=>'stocktransfer_stocktransfer', + 'url'=>'/stocktransfer/stocktransfer_card.php?action=create', + // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs'=>'stocktransfer@stocktransfer', + 'position'=>1100+$r, + // Define condition to show or hide menu entry. Use '$conf->stocktransfer->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'enabled'=>'$conf->stocktransfer->enabled', + // Use 'perms'=>'$user->rights->stocktransfer->level1->level2' if you want your menu with a permission rules + 'perms'=>'1', + 'target'=>'', + // 0=Menu for internal users, 1=external users, 2=both + 'user'=>2 + ); + $this->menu[$r++]=array( + // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'fk_menu'=>'fk_mainmenu=products,fk_leftmenu=stock', + // This is a Left menu entry + 'type'=>'left', + 'titre'=>$langs->trans('StockTransferList'), + 'mainmenu'=>'products', + 'leftmenu'=>'stocktransfer_stocktransferlist', + 'url'=>'/stocktransfer/stocktransfer_list.php', + // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'langs'=>'stocktransfer@stocktransfer', + 'position'=>1100+$r, + // Define condition to show or hide menu entry. Use '$conf->stocktransfer->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'enabled'=>'$conf->stocktransfer->enabled', + // Use 'perms'=>'$user->rights->stocktransfer->level1->level2' if you want your menu with a permission rules + 'perms'=>'1', + 'target'=>'', + // 0=Menu for internal users, 1=external users, 2=both + 'user'=>2, + );*/ + + /* END MODULEBUILDER LEFTMENU STOCKTRANSFER */ + + // Exports profiles provided by this module + $r = 1; + /* BEGIN MODULEBUILDER EXPORT STOCKTRANSFER */ + /* + $langs->load("stocktransfer@stocktransfer"); + $this->export_code[$r]=$this->rights_class.'_'.$r; + $this->export_label[$r]='StockTransferLines'; // Translation key (used only if key ExportDataset_xxx_z not found) + $this->export_icon[$r]='stocktransfer@stocktransfer'; + // Define $this->export_fields_array, $this->export_TypeFields_array and $this->export_entities_array + $keyforclass = 'StockTransfer'; $keyforclassfile='/stocktransfer/class/stocktransfer.class.php'; $keyforelement='stocktransfer@stocktransfer'; + include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php'; + //$this->export_fields_array[$r]['t.fieldtoadd']='FieldToAdd'; $this->export_TypeFields_array[$r]['t.fieldtoadd']='Text'; + //unset($this->export_fields_array[$r]['t.fieldtoremove']); + //$keyforclass = 'StockTransferLine'; $keyforclassfile='/stocktransfer/class/stocktransfer.class.php'; $keyforelement='stocktransferline@stocktransfer'; $keyforalias='tl'; + //include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php'; + $keyforselect='stocktransfer'; $keyforaliasextra='extra'; $keyforelement='stocktransfer@stocktransfer'; + include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; + //$keyforselect='stocktransferline'; $keyforaliasextra='extraline'; $keyforelement='stocktransferline@stocktransfer'; + //include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; + //$this->export_dependencies_array[$r] = array('stocktransferline'=>array('tl.rowid','tl.ref')); // To force to activate one or several fields if we select some fields that need same (like to select a unique key if we ask a field of a child to avoid the DISTINCT to discard them, or for computed field than need several other fields) + //$this->export_special_array[$r] = array('t.field'=>'...'); + //$this->export_examplevalues_array[$r] = array('t.field'=>'Example'); + //$this->export_help_array[$r] = array('t.field'=>'FieldDescHelp'); + $this->export_sql_start[$r]='SELECT DISTINCT '; + $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'stocktransfer as t'; + //$this->export_sql_end[$r] =' LEFT JOIN '.MAIN_DB_PREFIX.'stocktransfer_line as tl ON tl.fk_stocktransfer = t.rowid'; + $this->export_sql_end[$r] .=' WHERE 1 = 1'; + $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('stocktransfer').')'; + $r++; */ + /* END MODULEBUILDER EXPORT STOCKTRANSFER */ + + // Imports profiles provided by this module + $r = 1; + /* BEGIN MODULEBUILDER IMPORT STOCKTRANSFER */ + /* + $langs->load("stocktransfer@stocktransfer"); + $this->export_code[$r]=$this->rights_class.'_'.$r; + $this->export_label[$r]='StockTransferLines'; // Translation key (used only if key ExportDataset_xxx_z not found) + $this->export_icon[$r]='stocktransfer@stocktransfer'; + $keyforclass = 'StockTransfer'; $keyforclassfile='/stocktransfer/class/stocktransfer.class.php'; $keyforelement='stocktransfer@stocktransfer'; + include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php'; + $keyforselect='stocktransfer'; $keyforaliasextra='extra'; $keyforelement='stocktransfer@stocktransfer'; + include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; + //$this->export_dependencies_array[$r]=array('mysubobject'=>'ts.rowid', 't.myfield'=>array('t.myfield2','t.myfield3')); // To force to activate one or several fields if we select some fields that need same (like to select a unique key if we ask a field of a child to avoid the DISTINCT to discard them, or for computed field than need several other fields) + $this->export_sql_start[$r]='SELECT DISTINCT '; + $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'stocktransfer as t'; + $this->export_sql_end[$r] .=' WHERE 1 = 1'; + $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('stocktransfer').')'; + $r++; */ + /* END MODULEBUILDER IMPORT STOCKTRANSFER */ + } + + /** + * Function called when module is enabled. + * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. + * It also creates data directories + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function init($options = '') + { + global $conf, $langs; + + $result = $this->_load_tables('/install/mysql/tables/', 'stocktransfer'); + if ($result < 0) return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default') + + // Create extrafields during init + //include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + //$extrafields = new ExtraFields($this->db); + //$result1=$extrafields->addExtraField('stocktransfer_myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', 0, 0, '', '', 'stocktransfer@stocktransfer', '$conf->stocktransfer->enabled'); + //$result2=$extrafields->addExtraField('stocktransfer_myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', 0, 0, '', '', 'stocktransfer@stocktransfer', '$conf->stocktransfer->enabled'); + //$result3=$extrafields->addExtraField('stocktransfer_myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'stocktransfer@stocktransfer', '$conf->stocktransfer->enabled'); + //$result4=$extrafields->addExtraField('stocktransfer_myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', 0, 0, '', '', 'stocktransfer@stocktransfer', '$conf->stocktransfer->enabled'); + //$result5=$extrafields->addExtraField('stocktransfer_myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', 0, 0, '', '', 'stocktransfer@stocktransfer', '$conf->stocktransfer->enabled'); + + // Permissions + $this->remove($options); + + $sql = array(); + + // Rôles + $resql = $this->db->query('SELECT rowid FROM '.MAIN_DB_PREFIX.'c_type_contact WHERE code = "STDEST" AND element = "StockTransfer" AND source = "internal"'); + $res = $this->db->fetch_object($resql); + $nextid=$this->getNextId(); + if (empty($res)) $this->db->query('INSERT INTO '.MAIN_DB_PREFIX.'c_type_contact(rowid, element, source, code, libelle, active, module, position) VALUES('.((int) $nextid).', "StockTransfer", "internal", "STRESP", "Responsable du transfert de stocks", 1, NULL, 0)'); + + $resql = $this->db->query('SELECT rowid FROM '.MAIN_DB_PREFIX.'c_type_contact WHERE code = "STFROM" AND element = "StockTransfer" AND source = "external"'); + $res = $this->db->fetch_object($resql); + $nextid=$this->getNextId(); + if (empty($res)) $this->db->query('INSERT INTO '.MAIN_DB_PREFIX.'c_type_contact(rowid, element, source, code, libelle, active, module, position) VALUES('.((int) $nextid).', "StockTransfer", "external", "STFROM", "Contact expéditeur transfert de stocks", 1, NULL, 0)'); + + $resql = $this->db->query('SELECT rowid FROM '.MAIN_DB_PREFIX.'c_type_contact WHERE code = "STDEST" AND element = "StockTransfer" AND source = "external"'); + $res = $this->db->fetch_object($resql); + $nextid=$this->getNextId(); + if (empty($res)) $this->db->query('INSERT INTO '.MAIN_DB_PREFIX.'c_type_contact(rowid, element, source, code, libelle, active, module, position) VALUES('.((int) $nextid).', "StockTransfer", "external", "STDEST", "Contact destinataire transfert de stocks", 1, NULL, 0)'); + + return $this->_init($sql, $options); + } + + /** + * Returns next available id to insert new roles in llx_c_type_contact + * @return int > 0 if OK, < 0 if KO + */ + public function getNextId() + { + // Get free id for insert + $newid = 0; + $sql = "SELECT max(rowid) newid from ".MAIN_DB_PREFIX."c_type_contact"; + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + $newid = ($obj->newid + 1); + } else { + dol_print_error($this->db); + return -1; + } + return $newid; + } + + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function remove($options = '') + { + $sql = array(); + return $this->_remove($sql, $options); + } +} diff --git a/htdocs/core/modules/stocktransfer/doc/pdf_eagle.modules.php b/htdocs/core/modules/stocktransfer/doc/pdf_eagle.modules.php new file mode 100644 index 00000000000..74b0ea032b9 --- /dev/null +++ b/htdocs/core/modules/stocktransfer/doc/pdf_eagle.modules.php @@ -0,0 +1,1174 @@ + + * Copyright (C) 2005-2012 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014-2015 Marcos García + * Copyright (C) 2018 Frédéric France + * Copyright (C) 2021 Gauthier VERDOL + * + * 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 . + * or see https://www.gnu.org/ + */ + +/** + * \file htdocs/core/modules/expedition/doc/pdf_rouget.modules.php + * \ingroup expedition + * \brief Class file used to generate the dispatch slips for the Rouget model + */ + +require_once DOL_DOCUMENT_ROOT . '/core/modules/stocktransfer/modules_stocktransfer.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; + + +/** + * Class to build sending documents with model Eagle + */ +class pdf_eagle extends ModelePdfStockTransfer +{ + /** + * @var DoliDb Database handler + */ + public $db; + + /** + * @var string model name + */ + public $name; + + /** + * @var string model description (short text) + */ + public $description; + + /** + * @var string document type + */ + public $type; + + /** + * @var array Minimum version of PHP required by module. + * e.g.: PHP ≥ 5.5 = array(5, 5) + */ + public $phpmin = array(5, 5); + + /** + * Dolibarr version of the loaded document + * @var string + */ + public $version = 'dolibarr'; + + /** + * @var int page_largeur + */ + public $page_largeur; + + /** + * @var int page_hauteur + */ + public $page_hauteur; + + /** + * @var array format + */ + public $format; + + /** + * @var int marge_gauche + */ + public $marge_gauche; + + /** + * @var int marge_droite + */ + public $marge_droite; + + /** + * @var int marge_haute + */ + public $marge_haute; + + /** + * @var int marge_basse + */ + public $marge_basse; + + /** + * Issuer + * @var Societe object that emits + */ + public $emetteur; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db = 0) + { + global $conf, $langs, $mysoc; + + $this->db = $db; + $this->name = $langs->trans("StockTransferSheet"); + $this->description = $langs->trans("DocumentModelStandardPDF"); + + $this->type = 'pdf'; + $formatarray = pdf_getFormat(); + $this->page_largeur = $formatarray['width']; + $this->page_hauteur = $formatarray['height']; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; + + $this->option_logo = 1; // Display logo + + // Get source company + $this->emetteur = $mysoc; + if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined + + // Define position of columns + $this->posxdesc = $this->marge_gauche + 1; + $this->posxlot = $this->page_largeur - $this->marge_droite - 135; + $this->posxweightvol = $this->page_largeur - $this->marge_droite - 115; + $this->posxqty = $this->page_largeur - $this->marge_droite - 95; + $this->posxwarehousesource = $this->page_largeur - $this->marge_droite - 70; + $this->posxwarehousedestination = $this->page_largeur - $this->marge_droite - 35; + $this->posxpuht = $this->page_largeur - $this->marge_droite; + + /*if (!empty($conf->global->STOCKTRANSFER_PDF_DISPLAY_AMOUNT_HT)) { // Show also the prices + $this->posxqty = $this->page_largeur - $this->marge_droite - 118; + $this->posxwarehousesource = $this->page_largeur - $this->marge_droite - 96; + $this->posxwarehousedestination = $this->page_largeur - $this->marge_droite - 68; + $this->posxpuht = $this->page_largeur - $this->marge_droite - 40; + $this->posxtotalht = $this->page_largeur - $this->marge_droite - 20; + }*/ + + if (!empty($conf->global->STOCKTRANSFER_PDF_HIDE_WEIGHT_AND_VOLUME)) $this->posxweightvol = $this->posxqty; + + $this->posxpicture = $this->posxweightvol - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images + //var_dump($this->posxpicture, $this->posxweightvol);exit; + + // To work with US executive format + if ($this->page_largeur < 210) { + $this->posxqty -= 20; + $this->posxpicture -= 20; + $this->posxwarehousesource -= 20; + $this->posxwarehousedestination -= 20; + } + + /*if (!empty($conf->global->STOCKTRANSFER_PDF_HIDE_ORDERED)) { + $this->posxqty += ($this->posxwarehousedestination - $this->posxwarehousesource); + $this->posxpicture += ($this->posxwarehousedestination - $this->posxwarehousesource); + $this->posxwarehousesource = $this->posxwarehousedestination; + }*/ + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Function to build pdf onto disk + * + * @param Object $object Object StockTransfer to generate (or id if old method) + * @param Translate $outputlangs Lang output object + * @param string $srctemplatepath Full path of source filename for generator using a template file + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return int 1=OK, 0=KO + */ + public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + // phpcs:enable + global $db, $user, $conf, $langs, $hookmanager; + + $object->fetch_thirdparty(); + + $this->atLeastOneBatch = $this->atLeastOneBatch($object); + + if (!is_object($outputlangs)) $outputlangs = $langs; + // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; + + // Load traductions files required by page + $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch", "stocks", "stocktransfer@stocktransfer")); + + $nblines = count($object->lines); + + // Loop on each lines to detect if there is at least one image to show + $realpatharray = array(); + if (!empty($conf->global->MAIN_GENERATE_STOCKTRANSFER_WITH_PICTURE)) { + $objphoto = new Product($this->db); + + for ($i = 0; $i < $nblines; $i++) { + if (empty($object->lines[$i]->fk_product)) continue; + + $objphoto = new Product($this->db); + $objphoto->fetch($object->lines[$i]->fk_product); + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { + $pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/"; + $dir = $conf->product->dir_output.'/'.$pdir; + } else { + $pdir = get_exdir(0, 2, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; + $dir = $conf->product->dir_output.'/'.$pdir; + } + + $realpath = ''; + + foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) { + if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) { + // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo + if ($obj['photo_vignette']) { + $filename = $obj['photo_vignette']; + } else { + $filename = $obj['photo']; + } + } else { + $filename = $obj['photo']; + } + + $realpath = $dir.$filename; + break; + } + + if ($realpath) $realpatharray[$i] = $realpath; + } + } + + if (count($realpatharray) == 0) $this->posxpicture = $this->posxweightvol; + + + if (!empty($this->atLeastOneBatch)) { + $this->posxpicture = $this->posxlot; + if (!empty($conf->global->MAIN_GENERATE_STOCKTRANSFER_WITH_PICTURE)) $this->posxpicture -= (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images + } + + if ($conf->stocktransfer->dir_output) { + // Definition de $dir et $file + if ($object->specimen) { + $dir = $conf->stocktransfer->dir_output; + $file = $dir."/SPECIMEN.pdf"; + } else { + $stocktransferref = dol_sanitizeFileName($object->ref); + $dir = $conf->stocktransfer->dir_output.'/'.$object->element."/".$stocktransferref; + $file = $dir."/".$stocktransferref.".pdf"; + } + + if (!file_exists($dir)) { + if (dol_mkdir($dir) < 0) { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } + + if (file_exists($dir)) { + // Add pdfgeneration hook + if (!is_object($hookmanager)) { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($this->db); + } + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + + // Set nblines with the new facture lines content after hook + $nblines = count($object->lines); + + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); + $heightforinfotot = 8; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin) + if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6; + $pdf->SetAutoPageBreak(1, 0); + + if (class_exists('TCPDF')) { + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + } + $pdf->SetFont(pdf_getPDFFont($outputlangs)); + // Set path to the background PDF File + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { + $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); + $tplidx = $pdf->importPage(1); + } + + $pdf->Open(); + $pagenb = 0; + $pdf->SetDrawColor(128, 128, 128); + + if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); + + $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); + $pdf->SetSubject($outputlangs->transnoentities("Shipment")); + $pdf->SetCreator("Dolibarr ".DOL_VERSION); + $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); + $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Shipment")); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; + $this->_pagehead($pdf, $object, 1, $outputlangs); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->SetTextColor(0, 0, 0); + + $tab_top = 90; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10); + $tab_height = 130; + $tab_height_newpage = 150; + + // Incoterm + $height_incoterms = 0; + if ($conf->incoterm->enabled) { + $desc_incoterms = $object->getIncotermsForPDF(); + if ($desc_incoterms) { + $tab_top = 88; + + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $nexY = $pdf->GetY(); + $height_incoterms = $nexY - $tab_top; + + // Rect takes a length in 3rd parameter + $pdf->SetDrawColor(192, 192, 192); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); + + $tab_top = $nexY + 6; + $height_incoterms += 4; + } + } + + if (!empty($object->note_public) || !empty($object->tracking_number)) { + $tab_top = 88 + $height_incoterms; + $tab_top_alt = $tab_top; + + $pdf->SetFont('', 'B', $default_font_size - 2); + + //$tab_top_alt += 1; + + // Tracking number + if (!empty($object->tracking_number)) { + $pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top - 1, $outputlangs->transnoentities("TrackingNumber")." : ".$object->tracking_number, 0, 1, false, true, 'L'); + $tab_top_alt = $pdf->GetY(); + + $object->getUrlTrackingStatus($object->tracking_number); + if (!empty($object->tracking_url)) { + if ($object->shipping_method_id > 0) { + // Get code using getLabelFromKey + $code = $outputlangs->getLabelFromKey($this->db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code'); + $label = ''; + if ($object->tracking_url != $object->tracking_number) $label .= $outputlangs->trans("LinkToTrackYourPackage")."
    "; + $label .= $outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code)); + //var_dump($object->tracking_url != $object->tracking_number);exit; + if ($object->tracking_url != $object->tracking_number) { + $label .= " : "; + $label .= $object->tracking_url; + } + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top_alt, $label, 0, 1, false, true, 'L'); + + $tab_top_alt = $pdf->GetY(); + } + } + } + + // Notes + if (!empty($object->note_public)) { + $pdf->SetFont('', '', $default_font_size - 1); // Dans boucle pour gerer multi-page + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1); + } + + $nexY = $pdf->GetY(); + $height_note = $nexY - $tab_top; + + // Rect takes a length in 3rd parameter + $pdf->SetDrawColor(192, 192, 192); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1); + + $tab_height = $tab_height - $height_note; + $tab_top = $nexY + 6; + } else { + $height_note = 0; + } + + $iniY = $tab_top + 7; + $curY = $tab_top + 7; + $nexY = $tab_top + 7; + + $TCacheEntrepots=array(); + // Loop on each lines + for ($i = 0; $i < $nblines; $i++) { + $curY = $nexY; + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetTextColor(0, 0, 0); + + // Define size of image if we need it + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + + $pdf->setTopMargin($tab_top_newpage); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); + + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + $posYAfterDescription = 0; + + // We start with Photo of product line + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // If photo too high, we moved completely on new page + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + $pdf->setPage($pageposbefore + 1); + + $curY = $tab_top_newpage; + + // Allows data in the first page if description is long enough to break in multiples pages + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + $showpricebeforepagebreak = 1; + else $showpricebeforepagebreak = 0; + } + + if (isset($imglinesize['width']) && isset($imglinesize['height'])) { + $curX = $this->posxpicture - 1; + $pdf->Image($realpatharray[$i], $curX + (($this->posxqty - $this->posxweightvol - $imglinesize['width'] + + (!empty($conf->global->STOCKTRANSFER_PDF_HIDE_WEIGHT_AND_VOLUME) ? (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) : 0)) / 2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + // $pdf->Image does not increase value return by getY, so we save it manually + $posYAfterImage = $curY + $imglinesize['height']; + } + + // Description of product line + $curX = $this->posxdesc - 1; + + $pdf->startTransaction(); + if (method_exists($object->lines[$i], 'fetch_product')) { + $object->lines[$i]->fetch_product(); + $object->lines[$i]->label = $object->lines[$i]->product->label; + $object->lines[$i]->description = $object->lines[$i]->product->description; + $object->lines[$i]->weight = $object->lines[$i]->product->weight; + $object->lines[$i]->weight_units = $object->lines[$i]->product->weight_units; + $object->lines[$i]->length = $object->lines[$i]->product->length; + $object->lines[$i]->length_units = $object->lines[$i]->product->length_units; + $object->lines[$i]->surface = $object->lines[$i]->product->surface; + $object->lines[$i]->surface_units = $object->lines[$i]->product->surface_units; + $object->lines[$i]->volume = $object->lines[$i]->product->volume; + $object->lines[$i]->volume_units = $object->lines[$i]->product->volume_units; + $object->lines[$i]->fk_unit = $object->lines[$i]->product->fk_unit; + //var_dump($object->lines[$i]);exit; + } + + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxpicture - $curX, 3, $curX, $curY, $hideref, $hidedesc); + + $pageposafter = $pdf->getPage(); + if ($pageposafter > $pageposbefore) { // There is a pagebreak + $pdf->rollbackTransaction(true); + $pageposafter = $pageposbefore; + //print $pageposafter.'-'.$pageposbefore;exit; + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxpicture - $curX, 3, $curX, $curY, $hideref, $hidedesc); + + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); + //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // There is no space left for total+free text + if ($i == ($nblines - 1)) { // No more lines, and no space left to show total, so we create a new page + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + $pdf->setPage($pageposafter + 1); + } + } else { + // We found a page break + + // Allows data in the first page if description is long enough to break in multiples pages + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + $showpricebeforepagebreak = 1; + else $showpricebeforepagebreak = 0; + } + } else // No pagebreak + { + $pdf->commitTransaction(); + } + $posYAfterDescription = $pdf->GetY(); + + $nexY = $pdf->GetY(); + $pageposafter = $pdf->getPage(); + + $pdf->setPage($pageposbefore); + $pdf->setTopMargin($this->marge_haute); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + + // We suppose that a too long description or photo were moved completely on next page + if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { + $pdf->setPage($pageposafter); $curY = $tab_top_newpage; + } + + // We suppose that a too long description is moved completely on next page + if ($pageposafter > $pageposbefore) { + $pdf->setPage($pageposafter); $curY = $tab_top_newpage; + } + + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + + // Lot / série + if (!empty($conf->productbatch->enabled)) { + $pdf->SetXY($this->posxlot, $curY); + $pdf->MultiCell(($this->posxweightvol - $this->posxlot), 3, $object->lines[$i]->batch, '', 'C'); + } + + // Weight + $pdf->SetXY($this->posxweightvol, $curY); + $weighttxt = ''; + if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->weight) { + $weighttxt = round($object->lines[$i]->weight * $object->lines[$i]->qty, 5).' '.measuringUnitString(0, "weight", $object->lines[$i]->weight_units, 1); + } + $voltxt = ''; + if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->volume) { + $voltxt = round($object->lines[$i]->volume * $object->lines[$i]->qty, 5).' '.measuringUnitString(0, "volume", $object->lines[$i]->volume_units ? $object->lines[$i]->volume_units : 0, 1); + } + + // Weight + if (empty($conf->global->STOCKTRANSFER_PDF_HIDE_WEIGHT_AND_VOLUME)) { + $pdf->writeHTMLCell($this->posxqty - $this->posxweightvol + 2, 3, $this->posxweightvol - 1, $curY, $weighttxt.(($weighttxt && $voltxt) ? '
    ' : '').$voltxt, 0, 0, false, true, 'C'); + //$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 3, $weighttxt.(($weighttxt && $voltxt)?'
    ':'').$voltxt,'','C'); + } + + // Qty + $pdf->SetXY($this->posxqty, $curY); + $pdf->writeHTMLCell($this->posxwarehousesource - $this->posxqty + 2, 3, $this->posxqty - 1, $curY, $object->lines[$i]->qty, 0, 0, false, true, 'C'); + //$pdf->MultiCell(($this->posxwarehousesource - $this->posxqty), 3, $weighttxt.(($weighttxt && $voltxt)?'
    ':'').$voltxt,'','C'); + + // Warehouse source + $wh_source = new Entrepot($db); + if (!empty($TCacheEntrepots[$object->lines[$i]->fk_warehouse_source])) $wh_source = $TCacheEntrepots[$object->lines[$i]->fk_warehouse_source]; + else { + $wh_source->fetch($object->lines[$i]->fk_warehouse_source); + $TCacheEntrepots[$object->lines[$i]->fk_warehouse_source] = $wh_source; + } + $pdf->SetXY($this->posxwarehousesource, $curY); + $pdf->MultiCell(($this->posxwarehousedestination - $this->posxwarehousesource), 3, $wh_source->ref.(!empty($wh_source->lieu) ? ' - '.$wh_source->lieu : ''), '', 'C'); + + // Warehouse destination + $wh_destination = new Entrepot($db); + if (!empty($TCacheEntrepots[$object->lines[$i]->fk_warehouse_destination])) $wh_destination = $TCacheEntrepots[$object->lines[$i]->fk_warehouse_destination]; + else { + $wh_destination->fetch($object->lines[$i]->fk_warehouse_destination); + $TCacheEntrepots[$object->lines[$i]->fk_warehouse_destination] = $wh_destination; + } + $pdf->SetXY($this->posxwarehousedestination, $curY); + $pdf->MultiCell(($this->posxpuht - $this->posxwarehousedestination), 3, $wh_destination->ref.(!empty($wh_destination->lieu) ? ' - '.$wh_destination->lieu : ''), '', 'C'); + + if (!empty($conf->global->STOCKTRANSFER_PDF_DISPLAY_AMOUNT_HT)) { + $pdf->SetXY($this->posxpuht, $curY); + $pdf->MultiCell(($this->posxtotalht - $this->posxpuht - 1), 3, price($object->lines[$i]->subprice, 0, $outputlangs), '', 'R'); + + $pdf->SetXY($this->posxtotalht, $curY); + $pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 3, price($object->lines[$i]->total_ht, 0, $outputlangs), '', 'R'); + } + + $nexY += 3; + if ($weighttxt && $voltxt) $nexY += 2; + + // Add line + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { + $pdf->setPage($pageposafter); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); + //$pdf->SetDrawColor(190,190,200); + $pdf->line($this->marge_gauche, $nexY - 1, $this->page_largeur - $this->marge_droite, $nexY - 1); + $pdf->SetLineStyle(array('dash'=>0)); + } + + // Detect if some page were added automatically and output _tableau for past pages + while ($pagenb < $pageposafter) { + $pdf->setPage($pagenb); + if ($pagenb == 1) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + $pagenb++; + $pdf->setPage($pagenb); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { + if ($pagenb == 1) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } + } + + // Show square + if ($pagenb == 1) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0); + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0); + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + } + + // Affiche zone totaux + $posy = $this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs); + + // Pied de page + $this->_pagefoot($pdf, $object, $outputlangs); + if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); + + $pdf->Close(); + + $pdf->Output($file, 'F'); + + // Add pdfgeneration hook + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) { + $this->error = $hookmanager->error; + $this->errors = $hookmanager->errors; + } + + if (!empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); + + $this->result = array('fullpath'=>$file); + + return 1; // No error + } else { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } else { + $this->error = $langs->transnoentities("ErrorConstantNotDefined", "EXP_OUTPUTDIR"); + return 0; + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Show total to pay + * + * @param PDF $pdf Object PDF + * @param Facture $object Object invoice + * @param int $deja_regle Montant deja regle + * @param int $posy Position depart + * @param Translate $outputlangs Objet langs + * @return int Position pour suite + */ + protected function _tableau_tot(&$pdf, $object, $deja_regle, $posy, $outputlangs) + { + // phpcs:enable + global $conf, $mysoc; + + $sign = 1; + + $default_font_size = pdf_getPDFFontSize($outputlangs); + + $tab2_top = $posy; + $tab2_hl = 4; + $pdf->SetFont('', 'B', $default_font_size - 1); + + // Tableau total + $col1x = $this->posxqty - 50; $col2x = $this->posxqty; + /*if ($this->page_largeur < 210) // To work with US executive format + { + $col2x-=20; + }*/ + if (empty($conf->global->STOCKTRANSFER_PDF_HIDE_ORDERED)) $largcol2 = ($this->posxwarehousesource - $this->posxqty); + else $largcol2 = ($this->posxwarehousedestination - $this->posxqty); + + $useborder = 0; + $index = 0; + + $totalWeighttoshow = ''; + $totalVolumetoshow = ''; + + // Load dim data + $tmparray = $object->getTotalWeightVolume(); + $totalWeight = $tmparray['weight']; + $totalVolume = $tmparray['volume']; + $totalQty = 0; + if (!empty($object->lines)) + foreach ($object->lines as $line) { + $totalQty+=$line->qty; + } + // Set trueVolume and volume_units not currently stored into database + if ($object->trueWidth && $object->trueHeight && $object->trueDepth) { + $object->trueVolume = price(($object->trueWidth * $object->trueHeight * $object->trueDepth), 0, $outputlangs, 0, 0); + $object->volume_units = $object->size_units * 3; + } + + if ($totalWeight != '') $totalWeighttoshow = showDimensionInBestUnit($totalWeight, 0, "weight", $outputlangs); + if ($totalVolume != '') $totalVolumetoshow = showDimensionInBestUnit($totalVolume, 0, "volume", $outputlangs); + if ($object->trueWeight) $totalWeighttoshow = showDimensionInBestUnit($object->trueWeight, $object->weight_units, "weight", $outputlangs); + if ($object->trueVolume) $totalVolumetoshow = showDimensionInBestUnit($object->trueVolume, $object->volume_units, "volume", $outputlangs); + + $pdf->SetFillColor(255, 255, 255); + $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("Total"), 0, 'L', 1); + + if (empty($conf->global->STOCKTRANSFER_PDF_HIDE_ORDERED)) { + $pdf->SetXY($this->posxqty, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($this->posxwarehousesource - $this->posxqty, $tab2_hl, $totalQty, 0, 'C', 1); + } + + if (!empty($conf->global->STOCKTRANSFER_PDF_DISPLAY_AMOUNT_HT)) { + $pdf->SetXY($this->posxpuht, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($this->posxtotalht - $this->posxpuht, $tab2_hl, '', 0, 'C', 1); + + $pdf->SetXY($this->posxtotalht, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxtotalht, $tab2_hl, price($object->total_ht, 0, $outputlangs), 0, 'C', 1); + } + + if (empty($conf->global->STOCKTRANSFER_PDF_HIDE_WEIGHT_AND_VOLUME)) { + // Total Weight + if ($totalWeighttoshow) { + $pdf->SetXY($this->posxweightvol, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell(($this->posxqty - $this->posxweightvol), $tab2_hl, $totalWeighttoshow, 0, 'C', 1); + + $index++; + } + if ($totalVolumetoshow) { + $pdf->SetXY($this->posxweightvol, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell(($this->posxqty - $this->posxweightvol), $tab2_hl, $totalVolumetoshow, 0, 'C', 1); + + $index++; + } + if (!$totalWeighttoshow && !$totalVolumetoshow) $index++; + } + + $pdf->SetTextColor(0, 0, 0); + + return ($tab2_top + ($tab2_hl * $index)); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Show table for lines + * + * @param PDF $pdf Object PDF + * @param string $tab_top Top position of table + * @param string $tab_height Height of table (rectangle) + * @param int $nexY Y + * @param Translate $outputlangs Langs object + * @param int $hidetop Hide top bar of array + * @param int $hidebottom Hide bottom bar of array + * @return void + */ + protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0) + { + // phpcs:enable + global $conf; + + // Force to disable hidetop and hidebottom + $hidebottom = 0; + if ($hidetop) $hidetop = -1; + + $default_font_size = pdf_getPDFFontSize($outputlangs); + + // Amount in (at tab_top - 1) + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', '', $default_font_size - 2); + + // Output Rect + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + + $pdf->SetDrawColor(128, 128, 128); + $pdf->SetFont('', '', $default_font_size - 1); + + if (empty($hidetop)) { + $pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5); + + $pdf->SetXY($this->posxdesc - 1, $tab_top + 1); + $pdf->MultiCell($this->posxlot - $this->posxdesc, 2, $outputlangs->transnoentities("Description"), '', 'L'); + } + + if (!empty($conf->productbatch->enabled) && $this->atLeastOneBatch) { + $pdf->line($this->posxlot - 1, $tab_top, $this->posxlot - 1, $tab_top + $tab_height); + if (empty($hidetop)) { + $pdf->SetXY($this->posxlot, $tab_top + 1); + $pdf->MultiCell(($this->posxweightvol - $this->posxlot), 2, $outputlangs->transnoentities("Batch"), '', 'C'); + } + } + + if (empty($conf->global->STOCKTRANSFER_PDF_HIDE_WEIGHT_AND_VOLUME)) { + $pdf->line($this->posxweightvol - 1, $tab_top, $this->posxweightvol - 1, $tab_top + $tab_height); + if (empty($hidetop)) { + $pdf->SetXY($this->posxweightvol - 1, $tab_top + 1); + $pdf->MultiCell(($this->posxqty - $this->posxweightvol), 2, $outputlangs->transnoentities("WeightVolShort"), '', 'C'); + } + } + + $pdf->line($this->posxqty - 1, $tab_top, $this->posxqty - 1, $tab_top + $tab_height); + if (empty($hidetop)) { + $pdf->SetXY($this->posxqty - 1, $tab_top + 1); + $pdf->MultiCell(($this->posxwarehousesource - $this->posxqty), 2, $outputlangs->transnoentities("Qty"), '', 'C'); + } + + $pdf->line($this->posxwarehousesource - 1, $tab_top, $this->posxwarehousesource - 1, $tab_top + $tab_height); + if (empty($hidetop)) { + $pdf->SetXY($this->posxwarehousesource - 1, $tab_top + 1); + $pdf->MultiCell(($this->posxwarehousedestination - $this->posxwarehousesource), 2, $outputlangs->transnoentities("WarehouseSource"), '', 'C'); + } + + + $pdf->line($this->posxwarehousedestination - 1, $tab_top, $this->posxwarehousedestination - 1, $tab_top + $tab_height); + if (empty($hidetop)) { + $pdf->SetXY($this->posxwarehousedestination-2.5, $tab_top + 1); + $pdf->MultiCell(($this->posxpuht - $this->posxwarehousedestination+4), 2, $outputlangs->transnoentities("WarehouseTarget"), '', 'C'); + } + + /*if (!empty($conf->global->STOCKTRANSFER_PDF_DISPLAY_AMOUNT_HT)) { + $pdf->line($this->posxpuht - 1, $tab_top, $this->posxpuht - 1, $tab_top + $tab_height); + if (empty($hidetop)) + { + $pdf->SetXY($this->posxpuht - 1, $tab_top + 1); + $pdf->MultiCell(($this->posxtotalht - $this->posxpuht), 2, $outputlangs->transnoentities("PriceUHT"), '', 'C'); + } + + $pdf->line($this->posxtotalht - 1, $tab_top, $this->posxtotalht - 1, $tab_top + $tab_height); + if (empty($hidetop)) + { + $pdf->SetXY($this->posxtotalht - 1, $tab_top + 1); + $pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 2, $outputlangs->transnoentities("TotalHT"), '', 'C'); + } + }*/ + } + + /** + * Used to know if at least one line of Stock Transfer object has a batch set + * + * @param Object $object Stock Transfer object + * @return boolean true if at least one line has batch set, false if not + */ + public function atLeastOneBatch($object) + { + + global $conf; + + $atLeastOneBatch = false; + + if (empty($conf->productbatch->enabled)) return false; + + foreach ($object->lines as $line) { + if (!empty($line->batch)) { + return true; + } + } + + return false; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Show top header of page. + * + * @param PDF $pdf Object PDF + * @param Object $object Object to show + * @param int $showaddress 0=no, 1=yes + * @param Translate $outputlangs Object lang for output + * @return void + */ + protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs) + { + // phpcs:enable + global $conf, $langs, $mysoc; + + $langs->load("orders"); + + $default_font_size = pdf_getPDFFontSize($outputlangs); + + pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); + + // Show Draft Watermark + if ($object->statut == 0 && (!empty($conf->global->SHIPPING_DRAFT_WATERMARK))) { + pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->SHIPPING_DRAFT_WATERMARK); + } + + //Prepare la suite + $pdf->SetTextColor(0, 0, 60); + $pdf->SetFont('', 'B', $default_font_size + 3); + + $w = 110; + + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - $w; + + $pdf->SetXY($this->marge_gauche, $posy); + + // Logo + $logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo; + if ($this->emetteur->logo) { + if (is_readable($logo)) { + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + } else { + $pdf->SetTextColor(200, 0, 0); + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L'); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L'); + } + } else { + $text = $this->emetteur->name; + $pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); + } + + // Show barcode + if (!empty($conf->barcode->enabled)) { + $posx = 105; + } else { + $posx = $this->marge_gauche + 3; + } + //$pdf->Rect($this->marge_gauche, $this->marge_haute, $this->page_largeur-$this->marge_gauche-$this->marge_droite, 30); + if (!empty($conf->barcode->enabled)) { + // TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref + //$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3); + //$pdf->Image($logo,10, 5, 0, 24); + } + + $pdf->SetDrawColor(128, 128, 128); + if (!empty($conf->barcode->enabled)) { + // TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref + //$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3); + //$pdf->Image($logo,10, 5, 0, 24); + } + + + $posx = $this->page_largeur - $w - $this->marge_droite; + $posy = $this->marge_haute; + + $pdf->SetFont('', 'B', $default_font_size + 2); + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $title = $outputlangs->transnoentities("StockTransferSheet"); + $pdf->MultiCell($w, 4, $title, '', 'R'); + + $pdf->SetFont('', '', $default_font_size + 1); + + $posy += 5; + + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("Ref")." : ".$object->ref, '', 'R'); + + // Date prévue depart + if (!empty($object->date_prevue_depart)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DatePrevueDepart")." : ".dol_print_date($object->date_prevue_depart, "day", false, $outputlangs, true), '', 'R'); + } + + // Date prévue arrivée + if (!empty($object->date_prevue_arrivee)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DatePrevueArrivee")." : ".dol_print_date($object->date_prevue_arrivee, "day", false, $outputlangs, true), '', 'R'); + } + + // Date reelle depart + if (!empty($object->date_reelle_depart)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateReelleDepart")." : ".dol_print_date($object->date_reelle_depart, "day", false, $outputlangs, true), '', 'R'); + } + + // Date reelle arrivée + if (!empty($object->date_reelle_arrivee)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateReelleArrivee")." : ".dol_print_date($object->date_reelle_arrivee, "day", false, $outputlangs, true), '', 'R'); + } + + if (!empty($object->thirdparty->code_client)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); + } + + + $pdf->SetFont('', '', $default_font_size + 3); + $Yoff = 25; + + // Add list of linked orders + $origin = $object->origin; + $origin_id = $object->origin_id; + + // TODO move to external function + if (!empty($conf->$origin->enabled)) { // commonly $origin='commande' + $outputlangs->load('orders'); + + $classname = ucfirst($origin); + $linkedobject = new $classname($this->db); + $result = $linkedobject->fetch($origin_id); + if ($result >= 0) { + //$linkedobject->fetchObjectLinked() Get all linked object to the $linkedobject (commonly order) into $linkedobject->linkedObjects + + $pdf->SetFont('', '', $default_font_size - 2); + $text = $linkedobject->ref; + if ($linkedobject->ref_client) $text .= ' ('.$linkedobject->ref_client.')'; + $Yoff = $Yoff + 8; + $pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff); + $pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder")." : ".$outputlangs->transnoentities($text), 0, 'R'); + $Yoff = $Yoff + 3; + $pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff); + $pdf->MultiCell($w, 2, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($linkedobject->date, "day", false, $outputlangs, true), 0, 'R'); + } + } + + if ($showaddress) { + // Sender properties + $carac_emetteur = ''; + // Add internal contact of origin element if defined + $arrayidcontact = array(); + $arrayidcontact = $object->getIdContact('external', 'STFROM'); + + $usecontact = false; + if (count($arrayidcontact) > 0) { + /*$object->fetch_user(reset($arrayidcontact)); + $carac_emetteur .= ($carac_emetteur ? "\n" : '').$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n";*/ + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); + } + + if ($usecontact) $thirdparty = $object->contact; + else $thirdparty = $this->emetteur; + + if (!empty($thirdparty)) $carac_emetteur_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); + + if ($usecontact) $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, $object->contact, 1, 'targetwithdetails', $object); + else $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); + + // Show sender + $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; + $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + + $hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40; + $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82; + + // Show sender frame + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posx, $posy - 5); + $pdf->MultiCell(66, 5, $outputlangs->transnoentities("Sender").":", 0, 'L'); + $pdf->SetXY($posx, $posy); + $pdf->SetFillColor(230, 230, 230); + $pdf->MultiCell($widthrecbox, $hautcadre, "", 0, 'R', 1); + $pdf->SetTextColor(0, 0, 60); + $pdf->SetFillColor(255, 255, 255); + + // Show sender name + $pdf->SetXY($posx + 2, $posy + 3); + $pdf->SetFont('', 'B', $default_font_size); + $pdf->MultiCell($widthrecbox - 2, 4, $outputlangs->convToOutputCharset($carac_emetteur_name), 0, 'L'); + $posy = $pdf->getY(); + + // Show sender information + $pdf->SetXY($posx + 2, $posy); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->MultiCell($widthrecbox - 2, 4, $carac_emetteur, 0, 'L'); + + + // If SHIPPING contact defined, we use it + $usecontact = false; + $arrayidcontact = $object->getIdContact('external', 'STDEST'); + if (count($arrayidcontact) > 0) { + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); + } + + //Recipient name + // On peut utiliser le nom de la societe du contact + if ($usecontact/* && !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)*/) { + $thirdparty = $object->contact; + } else { + $thirdparty = $object->thirdparty; + } + + if (!empty($thirdparty)) $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); + + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, (!empty($object->contact) ? $object->contact : null), $usecontact, 'targetwithdetails', $object); + + // Show recipient + $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; + + // Show recipient frame + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posx + 2, $posy - 5); + $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("Recipient").":", 0, 'L'); + $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); + + // Show recipient name + $pdf->SetXY($posx + 2, $posy + 3); + $pdf->SetFont('', 'B', $default_font_size); + $pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L'); + + $posy = $pdf->getY(); + + // Show recipient information + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->SetXY($posx + 2, $posy); + $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); + } + + $pdf->SetTextColor(0, 0, 0); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Show footer of page. Need this->emetteur object + * + * @param PDF $pdf PDF + * @param Object $object Object to show + * @param Translate $outputlangs Object lang for output + * @param int $hidefreetext 1=Hide free text + * @return int Return height of bottom margin including footer text + */ + protected function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0) + { + // phpcs:enable + global $conf; + $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; + return pdf_pagefoot($pdf, $outputlangs, 'SHIPPING_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext); + } +} diff --git a/htdocs/core/modules/stocktransfer/doc/pdf_eagle_proforma.modules.php b/htdocs/core/modules/stocktransfer/doc/pdf_eagle_proforma.modules.php new file mode 100644 index 00000000000..bd9e4d3f11a --- /dev/null +++ b/htdocs/core/modules/stocktransfer/doc/pdf_eagle_proforma.modules.php @@ -0,0 +1,1635 @@ + + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2008 Raphael Bertrand + * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2012 Christophe Battarel + * Copyright (C) 2012 Cedric Salvador + * Copyright (C) 2015 Marcos García + * Copyright (C) 2017 Ferran Marcet + * Copyright (C) 2018-2019 Frédéric France + * Copyright (C) 2021 Gauthier VERDOL + * + * 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 . + * or see https://www.gnu.org/ + */ + +/** + * \file htdocs/core/modules/commande/doc/pdf_eratosthene.modules.php + * \ingroup commande + * \brief File of Class to generate PDF orders with template Eratosthène + */ + +require_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; + + +/** + * Class to generate PDF orders with template Eratosthene + */ +class pdf_eagle_proforma extends ModelePDFCommandes +{ + /** + * @var DoliDb Database handler + */ + public $db; + + /** + * @var string model name + */ + public $name; + + /** + * @var string model description (short text) + */ + public $description; + + /** + * @var int Save the name of generated file as the main doc when generating a doc with this template + */ + public $update_main_doc_field; + + /** + * @var string document type + */ + public $type; + + /** + * @var array Minimum version of PHP required by module. + * e.g.: PHP ≥ 5.5 = array(5, 5) + */ + public $phpmin = array(5, 5); + + /** + * Dolibarr version of the loaded document + * @var string + */ + public $version = 'dolibarr'; + + /** + * @var int page_largeur + */ + public $page_largeur; + + /** + * @var int page_hauteur + */ + public $page_hauteur; + + /** + * @var array format + */ + public $format; + + /** + * @var int marge_gauche + */ + public $marge_gauche; + + /** + * @var int marge_droite + */ + public $marge_droite; + + /** + * @var int marge_haute + */ + public $marge_haute; + + /** + * @var int marge_basse + */ + public $marge_basse; + + /** + * Issuer + * @var Societe Object that emits + */ + public $emetteur; + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $conf, $langs, $mysoc; + + // Translations + $langs->loadLangs(array("main", "bills", "products")); + + $this->db = $db; + $this->name = $langs->trans("StockTransferSheetProforma"); + $this->description = $langs->trans('StockTransferSheetProforma'); + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template + + // Dimension page + $this->type = 'pdf'; + $formatarray = pdf_getFormat(); + $this->page_largeur = $formatarray['width']; + $this->page_hauteur = $formatarray['height']; + $this->format = array($this->page_largeur, $this->page_hauteur); + $this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10; + $this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10; + $this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10; + $this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10; + + $this->option_logo = 1; // Display logo + $this->option_tva = 1; // Manage the vat option FACTURE_TVAOPTION + $this->option_modereg = 1; // Display payment mode + $this->option_condreg = 1; // Display payment terms + $this->option_codeproduitservice = 1; // Display product-service code + $this->option_multilang = 1; // Available in several languages + $this->option_escompte = 0; // Displays if there has been a discount + $this->option_credit_note = 0; // Support credit notes + $this->option_freetext = 1; // Support add of a personalised text + $this->option_draft_watermark = 1; // Support add of a watermark on drafts + + // Get source company + $this->emetteur = $mysoc; + if (empty($this->emetteur->country_code)) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default, if was not defined + + // Define position of columns + $this->posxdesc = $this->marge_gauche + 1; + + + $this->tabTitleHeight = 5; // default height + + $this->tva = array(); + $this->localtax1 = array(); + $this->localtax2 = array(); + $this->atleastoneratenotnull = 0; + $this->atleastonediscount = 0; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Function to build pdf onto disk + * + * @param Object $object Object to generate + * @param Translate $outputlangs Lang output object + * @param string $srctemplatepath Full path of source filename for generator using a template file + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return int 1=OK, 0=KO + */ + public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + // phpcs:enable + global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; + + if (!is_object($outputlangs)) $outputlangs = $langs; + // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; + + // Load translation files required by the page + $outputlangs->loadLangs(array("main", "dict", "companies", "bills", "products", "orders", "deliveries")); + + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "orders", "deliveries")); + } + + $nblines = count($object->lines); + + $hidetop = 0; + if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { + $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; + } + + // Loop on each lines to detect if there is at least one image to show + $realpatharray = array(); + $this->atleastonephoto = false; + if (!empty($conf->global->MAIN_GENERATE_ORDERS_WITH_PICTURE)) { + $objphoto = new Product($this->db); + + for ($i = 0; $i < $nblines; $i++) { + if (empty($object->lines[$i]->fk_product)) continue; + + $objphoto->fetch($object->lines[$i]->fk_product); + //var_dump($objphoto->ref);exit; + if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { + $pdir[0] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; + $pdir[1] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; + } else { + $pdir[0] = get_exdir(0, 0, 0, 0, $objphoto, 'product').dol_sanitizeFileName($objphoto->ref).'/'; // default + $pdir[1] = get_exdir($objphoto->id, 2, 0, 0, $objphoto, 'product').$objphoto->id."/photos/"; // alternative + } + + $arephoto = false; + foreach ($pdir as $midir) { + if (!$arephoto) { + $dir = $conf->product->dir_output.'/'.$midir; + + foreach ($objphoto->liste_photos($dir, 1) as $key => $obj) { + if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) { // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo + if ($obj['photo_vignette']) { + $filename = $obj['photo_vignette']; + } else { + $filename = $obj['photo']; + } + } else { + $filename = $obj['photo']; + } + + $realpath = $dir.$filename; + $arephoto = true; + $this->atleastonephoto = true; + } + } + } + + if ($realpath && $arephoto) $realpatharray[$i] = $realpath; + } + } + + + + if ($conf->stocktransfer->dir_output) { + $object->fetch_thirdparty(); + + $deja_regle = 0; + + // Definition of $dir and $file + if ($object->specimen) { + $dir = $conf->stocktransfer->multidir_output[$conf->entity]; + $file = $dir."/SPECIMEN.pdf"; + } else { + $objectref = dol_sanitizeFileName($object->ref); + $dir = $conf->stocktransfer->multidir_output[$conf->entity]."/".$object->element."/".$objectref; + $file = $dir."/".$objectref."-proforma.pdf"; + } + + if (!file_exists($dir)) { + if (dol_mkdir($dir) < 0) { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } + + if (file_exists($dir)) { + // Add pdfgeneration hook + if (!is_object($hookmanager)) { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($this->db); + } + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + + // Create pdf instance + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $pdf->SetAutoPageBreak(1, 0); + + $heightforinfotot = 40; // Height reserved to output the info and total part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) + + if (class_exists('TCPDF')) { + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + } + $pdf->SetFont(pdf_getPDFFont($outputlangs)); + // Set path to the background PDF File + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) { + $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); + $tplidx = $pdf->importPage(1); + } + + $pdf->Open(); + $pagenb = 0; + $pdf->SetDrawColor(128, 128, 128); + + $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); + $pdf->SetSubject($outputlangs->transnoentities("PdfOrderTitle")); + $pdf->SetCreator("Dolibarr ".DOL_VERSION); + $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); + $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfOrderTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + + /// Does we have at least one line with discount $this->atleastonediscount + foreach ($object->lines as $line) { + if ($line->remise_percent) { + $this->atleastonediscount = true; + break; + } + } + + + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; + $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->SetTextColor(0, 0, 0); + + + $tab_top = 90 + $top_shift; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); + + // Incoterm + if ($conf->incoterm->enabled) { + $desc_incoterms = $object->getIncotermsForPDF(); + if ($desc_incoterms) { + $tab_top -= 2; + + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1); + $nexY = $pdf->GetY(); + $height_incoterms = $nexY - $tab_top; + + // Rect takes a length in 3rd parameter + $pdf->SetDrawColor(192, 192, 192); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1); + + $tab_top = $nexY + 6; + } + } + + // Displays notes + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + if (!empty($conf->global->MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE)) { + // Get first sale rep + if (is_object($object->thirdparty)) { + $salereparray = $object->thirdparty->getSalesRepresentatives($user); + $salerepobj = new User($this->db); + $salerepobj->fetch($salereparray[0]['id']); + if (!empty($salerepobj->signature)) $notetoshow = dol_concatdesc($notetoshow, $salerepobj->signature); + } + } + + // Extrafields in note + $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); + if (!empty($extranote)) { + $notetoshow = dol_concatdesc($notetoshow, $extranote); + } + + $pagenb = $pdf->getPage(); + if ($notetoshow) { + $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; + $pageposbeforenote = $pagenb; + + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); + complete_substitutions_array($substitutionarray, $outputlangs, $object); + $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); + $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); + + $tab_top -= 2; + + $pdf->startTransaction(); + + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); + // Description + $pageposafternote = $pdf->getPage(); + $posyafter = $pdf->GetY(); + + if ($pageposafternote > $pageposbeforenote) { + $pdf->rollbackTransaction(true); + + // prepare pages to receive notes + while ($pagenb < $pageposafternote) { + $pdf->AddPage(); + $pagenb++; + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + // $this->_pagefoot($pdf,$object,$outputlangs,1); + $pdf->setTopMargin($tab_top_newpage); + // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + } + + // back to start + $pdf->setPage($pageposbeforenote); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); + $pageposafternote = $pdf->getPage(); + + $posyafter = $pdf->GetY(); + + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { // There is no space left for total+free text + $pdf->AddPage('', '', true); + $pagenb++; + $pageposafternote++; + $pdf->setPage($pageposafternote); + $pdf->setTopMargin($tab_top_newpage); + // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + //$posyafter = $tab_top_newpage; + } + + + // apply note frame to previous pages + $i = $pageposbeforenote; + while ($i < $pageposafternote) { + $pdf->setPage($i); + + + $pdf->SetDrawColor(128, 128, 128); + // Draw note frame + if ($i > $pageposbeforenote) { + $height_note = $this->page_hauteur - ($tab_top_newpage + $heightforfooter); + $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); + } else { + $height_note = $this->page_hauteur - ($tab_top + $heightforfooter); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); + } + + // Add footer + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $this->_pagefoot($pdf, $object, $outputlangs, 1); + + $i++; + } + + // apply note frame to last page + $pdf->setPage($pageposafternote); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + $height_note = $posyafter - $tab_top_newpage; + $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); + } else // No pagebreak + { + $pdf->commitTransaction(); + $posyafter = $pdf->GetY(); + $height_note = $posyafter - $tab_top; + $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); + + + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) { + // not enough space, need to add page + $pdf->AddPage('', '', true); + $pagenb++; + $pageposafternote++; + $pdf->setPage($pageposafternote); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + + $posyafter = $tab_top_newpage; + } + } + + $tab_height = $tab_height - $height_note; + $tab_top = $posyafter + 6; + } else { + $height_note = 0; + } + + + // Use new auto column system + $this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); + + // tab simulation to know line height + $pdf->startTransaction(); + $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); + $pdf->rollbackTransaction(true); + + $nexY = $tab_top + $this->tabTitleHeight; + + // Loop on each lines + $pageposbeforeprintlines = $pdf->getPage(); + $pagenb = $pageposbeforeprintlines; + for ($i = 0; $i < $nblines; $i++) { + $curY = $nexY; + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetTextColor(0, 0, 0); + + // Define size of image if we need it + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + + $pdf->setTopMargin($tab_top_newpage); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); + + + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; + + if ($this->getColumnStatus('photo')) { + // We start with Photo of product line + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // If photo too high, we moved completely on new page + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposbefore + 1); + + $curY = $tab_top_newpage; + + // Allows data in the first page if description is long enough to break in multiples pages + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + $showpricebeforepagebreak = 1; + else $showpricebeforepagebreak = 0; + } + + if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) { + $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + // $pdf->Image does not increase value return by getY, so we save it manually + $posYAfterImage = $curY + $imglinesize['height']; + } + } + + if ($this->getColumnStatus('desc')) { + $pdf->startTransaction(); + + if (method_exists($object->lines[$i], 'fetch_product')) { + $object->lines[$i]->fetch_product(); + $object->lines[$i]->label = $object->lines[$i]->product->label; + $object->lines[$i]->description = $object->lines[$i]->product->description; + $object->lines[$i]->fk_unit = $object->lines[$i]->product->fk_unit; + } + + $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); + + $pageposafter = $pdf->getPage(); + if ($pageposafter > $pageposbefore) { // There is a pagebreak + $pdf->rollbackTransaction(true); + $pageposafter = $pageposbefore; + //print $pageposafter.'-'.$pageposbefore;exit; + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + + $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) { // There is no space left for total+free text + if ($i == ($nblines - 1)) { // No more lines, and no space left to show total, so we create a new page + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + //if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + $pdf->setPage($pageposafter + 1); + } + } else { + // We found a page break + // Allows data in the first page if description is long enough to break in multiples pages + if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) + $showpricebeforepagebreak = 1; + else $showpricebeforepagebreak = 0; + } + } else // No pagebreak + { + $pdf->commitTransaction(); + } + } + + + + $nexY = max($pdf->GetY(), $posYAfterImage); + + + $pageposafter = $pdf->getPage(); + + $pdf->setPage($pageposbefore); + $pdf->setTopMargin($this->marge_haute); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + + // We suppose that a too long description is moved completely on next page + if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { + $pdf->setPage($pageposafter); $curY = $tab_top_newpage; + } + + $pdf->SetFont('', '', $default_font_size - 1); // We reposition the default font + + // VAT Rate + if ($this->getColumnStatus('vat')) { + $vat_rate = pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails); + $this->printStdColumnContent($pdf, $curY, 'vat', $vat_rate); + $nexY = max($pdf->GetY(), $nexY); + } + + // Unit price before discount + if ($this->getColumnStatus('subprice')) { + $pmp = $object->lines[$i]->pmp; + $this->printStdColumnContent($pdf, $curY, 'subprice', price($pmp)); + $nexY = max($pdf->GetY(), $nexY); + } + + // Quantity + // Enough for 6 chars + if ($this->getColumnStatus('qty')) { + $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); + $this->printStdColumnContent($pdf, $curY, 'qty', $qty); + $nexY = max($pdf->GetY(), $nexY); + } + + + // Unit + if ($this->getColumnStatus('unit')) { + $unit = pdf_getlineunit($object, $i, $outputlangs, $hidedetails, $hookmanager); + $this->printStdColumnContent($pdf, $curY, 'unit', $unit); + $nexY = max($pdf->GetY(), $nexY); + } + + // Discount on line + if ($this->getColumnStatus('discount') && $object->lines[$i]->remise_percent) { + $remise_percent = pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails); + $this->printStdColumnContent($pdf, $curY, 'discount', $remise_percent); + $nexY = max($pdf->GetY(), $nexY); + } + + // Total HT line + if ($this->getColumnStatus('totalexcltax')) { + $pmp_qty = $pmp * $object->lines[$i]->qty; + $this->printStdColumnContent($pdf, $curY, 'totalexcltax', price($pmp_qty)); + $nexY = max($pdf->GetY(), $nexY); + } + + // Extrafields + if (!empty($object->lines[$i]->array_options)) { + foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { + if ($this->getColumnStatus($extrafieldColKey)) { + $extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey); + $this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue); + $nexY = max($pdf->GetY(), $nexY); + } + } + } + + $parameters = array( + 'object' => $object, + 'i' => $i, + 'pdf' =>& $pdf, + 'curY' =>& $curY, + 'nexY' =>& $nexY, + 'outputlangs' => $outputlangs, + 'hidedetails' => $hidedetails + ); + $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook + + + // Collection of totals by value of vat in $this->tva["rate"] = total_tva + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $object->lines[$i]->total_tva; + + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; + + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; + + $vatrate = (string) $object->lines[$i]->tva_tx; + + // Retrieve type from database for backward compatibility with old records + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) { // and there is local tax + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtax1_type = $localtaxtmp_array[0]; + $localtax2_type = $localtaxtmp_array[2]; + } + + // retrieve global local tax + if ($localtax1_type && $localtax1ligne != 0) + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; + if ($localtax2_type && $localtax2ligne != 0) + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; + + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; + $this->tva[$vatrate] += $tvaligne; + + // Add line + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { + $pdf->setPage($pageposafter); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); + //$pdf->SetDrawColor(190,190,200); + $pdf->line($this->marge_gauche, $nexY, $this->page_largeur - $this->marge_droite, $nexY); + $pdf->SetLineStyle(array('dash'=>0)); + } + + + // Detect if some page were added automatically and output _tableau for past pages + while ($pagenb < $pageposafter) { + $pdf->setPage($pagenb); + if ($pagenb == $pageposbeforeprintlines) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + $pagenb++; + $pdf->setPage($pagenb); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { + if ($pagenb == $pageposafter) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } + } + + // Show square + if ($pagenb == $pageposbeforeprintlines) + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code); + else $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code); + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + + // Affiche zone infos + // ! No paiement information for this model ! + //$posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); + + // Affiche zone totaux + $posy = $this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); + + // Affiche zone versements + /* + if ($deja_regle) + { + $posy=$this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); + } + */ + + // Pied de page + $this->_pagefoot($pdf, $object, $outputlangs); + if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); + + $pdf->Close(); + + $pdf->Output($file, 'F'); + + // Add pdfgeneration hook + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) { + $this->error = $hookmanager->error; + $this->errors = $hookmanager->errors; + } + + if (!empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); + + $this->result = array('fullpath'=>$file); + + return 1; // No error + } else { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } else { + $this->error = $langs->transnoentities("ErrorConstantNotDefined", "STOCKTRANSFER_OUTPUTDIR"); + return 0; + } + } + + /** + * Show payments table + * + * @param TCPDF $pdf Object PDF + * @param Object $object Object order + * @param int $posy Position y in PDF + * @param Translate $outputlangs Object langs for output + * @return int <0 if KO, >0 if OK + */ + protected function drawPaymentsTable(&$pdf, $object, $posy, $outputlangs) + { + } + + /** + * Show miscellaneous information (payment mode, payment term, ...) + * + * @param TCPDF $pdf Object PDF + * @param Object $object Object to show + * @param int $posy Y + * @param Translate $outputlangs Langs object + * @return int Pos y + */ + protected function drawInfoTable(&$pdf, $object, $posy, $outputlangs) + { + global $conf, $mysoc; + $default_font_size = pdf_getPDFFontSize($outputlangs); + + $pdf->SetFont('', '', $default_font_size - 1); + + // If France, show VAT mention if not applicable + if ($this->emetteur->country_code == 'FR' && empty($mysoc->tva_assuj)) { + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->SetXY($this->marge_gauche, $posy); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("VATIsNotUsedForInvoice"), 0, 'L', 0); + + $posy = $pdf->GetY() + 4; + } + + $posxval = 52; + + // Show payments conditions + if ($object->cond_reglement_code || $object->cond_reglement) { + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->SetXY($this->marge_gauche, $posy); + $titre = $outputlangs->transnoentities("PaymentConditions").':'; + $pdf->MultiCell(43, 4, $titre, 0, 'L'); + + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posxval, $posy); + $lib_condition_paiement = $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) != ('PaymentCondition'.$object->cond_reglement_code) ? $outputlangs->transnoentities("PaymentCondition".$object->cond_reglement_code) : $outputlangs->convToOutputCharset($object->cond_reglement_doc); + $lib_condition_paiement = str_replace('\n', "\n", $lib_condition_paiement); + $pdf->MultiCell(67, 4, $lib_condition_paiement, 0, 'L'); + + $posy = $pdf->GetY() + 3; + } + + // Check a payment mode is defined + /* Not used with orders + if (empty($object->mode_reglement_code) + && ! $conf->global->FACTURE_CHQ_NUMBER + && ! $conf->global->FACTURE_RIB_NUMBER) + { + $pdf->SetXY($this->marge_gauche, $posy); + $pdf->SetTextColor(200,0,0); + $pdf->SetFont('','B', $default_font_size - 2); + $pdf->MultiCell(80, 3, $outputlangs->transnoentities("ErrorNoPaiementModeConfigured"),0,'L',0); + $pdf->SetTextColor(0,0,0); + + $posy=$pdf->GetY()+1; + } + */ + /* TODO + else if (! empty($object->availability_code)) + { + $pdf->SetXY($this->marge_gauche, $posy); + $pdf->SetTextColor(200,0,0); + $pdf->SetFont('','B', $default_font_size - 2); + $pdf->MultiCell(80, 3, $outputlangs->transnoentities("AvailabilityPeriod").': '.,0,'L',0); + $pdf->SetTextColor(0,0,0); + + $posy=$pdf->GetY()+1; + }*/ + + // Show planed date of delivery + if (!empty($object->date_livraison)) { + $outputlangs->load("sendings"); + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->SetXY($this->marge_gauche, $posy); + $titre = $outputlangs->transnoentities("DateDeliveryPlanned").':'; + $pdf->MultiCell(80, 4, $titre, 0, 'L'); + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posxval, $posy); + $dlp = dol_print_date($object->date_livraison, "daytext", false, $outputlangs, true); + $pdf->MultiCell(80, 4, $dlp, 0, 'L'); + + $posy = $pdf->GetY() + 1; + } elseif ($object->availability_code || $object->availability) { // Show availability conditions + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->SetXY($this->marge_gauche, $posy); + $titre = $outputlangs->transnoentities("AvailabilityPeriod").':'; + $pdf->MultiCell(80, 4, $titre, 0, 'L'); + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posxval, $posy); + $lib_availability = $outputlangs->transnoentities("AvailabilityType".$object->availability_code) != ('AvailabilityType'.$object->availability_code) ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : ''); + $lib_availability = str_replace('\n', "\n", $lib_availability); + $pdf->MultiCell(80, 4, $lib_availability, 0, 'L'); + + $posy = $pdf->GetY() + 1; + } + + // Show payment mode + if ($object->mode_reglement_code + && $object->mode_reglement_code != 'CHQ' + && $object->mode_reglement_code != 'VIR') { + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->SetXY($this->marge_gauche, $posy); + $titre = $outputlangs->transnoentities("PaymentMode").':'; + $pdf->MultiCell(80, 5, $titre, 0, 'L'); + + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posxval, $posy); + $lib_mode_reg = $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) != ('PaymentType'.$object->mode_reglement_code) ? $outputlangs->transnoentities("PaymentType".$object->mode_reglement_code) : $outputlangs->convToOutputCharset($object->mode_reglement); + $pdf->MultiCell(80, 5, $lib_mode_reg, 0, 'L'); + + $posy = $pdf->GetY() + 2; + } + + // Show payment mode CHQ + if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'CHQ') { + // Si mode reglement non force ou si force a CHQ + if (!empty($conf->global->FACTURE_CHQ_NUMBER)) { + if ($conf->global->FACTURE_CHQ_NUMBER > 0) { + $account = new Account($this->db); + $account->fetch($conf->global->FACTURE_CHQ_NUMBER); + + $pdf->SetXY($this->marge_gauche, $posy); + $pdf->SetFont('', 'B', $default_font_size - 3); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByChequeOrderedTo', $account->proprio), 0, 'L', 0); + $posy = $pdf->GetY() + 1; + + if (empty($conf->global->MAIN_PDF_HIDE_CHQ_ADDRESS)) { + $pdf->SetXY($this->marge_gauche, $posy); + $pdf->SetFont('', '', $default_font_size - 3); + $pdf->MultiCell(100, 3, $outputlangs->convToOutputCharset($account->owner_address), 0, 'L', 0); + $posy = $pdf->GetY() + 2; + } + } + if ($conf->global->FACTURE_CHQ_NUMBER == -1) { + $pdf->SetXY($this->marge_gauche, $posy); + $pdf->SetFont('', 'B', $default_font_size - 3); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByChequeOrderedTo', $this->emetteur->name), 0, 'L', 0); + $posy = $pdf->GetY() + 1; + + if (empty($conf->global->MAIN_PDF_HIDE_CHQ_ADDRESS)) { + $pdf->SetXY($this->marge_gauche, $posy); + $pdf->SetFont('', '', $default_font_size - 3); + $pdf->MultiCell(100, 3, $outputlangs->convToOutputCharset($this->emetteur->getFullAddress()), 0, 'L', 0); + $posy = $pdf->GetY() + 2; + } + } + } + } + + // If payment mode not forced or forced to VIR, show payment with BAN + if (empty($object->mode_reglement_code) || $object->mode_reglement_code == 'VIR') { + if (!empty($object->fk_account) || !empty($object->fk_bank) || !empty($conf->global->FACTURE_RIB_NUMBER)) { + $bankid = (empty($object->fk_account) ? $conf->global->FACTURE_RIB_NUMBER : $object->fk_account); + if (!empty($object->fk_bank)) $bankid = $object->fk_bank; // For backward compatibility when object->fk_account is forced with object->fk_bank + $account = new Account($this->db); + $account->fetch($bankid); + + $curx = $this->marge_gauche; + $cury = $posy; + + $posy = pdf_bank($pdf, $outputlangs, $curx, $cury, $account, 0, $default_font_size); + + $posy += 2; + } + } + + return $posy; + } + + + /** + * Show total to pay + * + * @param TCPDF $pdf Object PDF + * @param Facture $object Object invoice + * @param int $deja_regle Montant deja regle + * @param int $posy Position depart + * @param Translate $outputlangs Objet langs + * @return int Position pour suite + */ + protected function drawTotalTable(&$pdf, $object, $deja_regle, $posy, $outputlangs) + { + global $conf, $mysoc; + + $default_font_size = pdf_getPDFFontSize($outputlangs); + + $tab2_top = $posy; + $tab2_hl = 4; + $pdf->SetFont('', '', $default_font_size - 1); + + // Tableau total + $col1x = 120; $col2x = 170; + if ($this->page_largeur < 210) { // To work with US executive format + $col2x -= 20; + } + $largcol2 = ($this->page_largeur - $this->marge_droite - $col2x); + $useborder = 0; + $index = 0; + + $outputlangsbis = null; + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "dict", "companies", "bills", "products", "propal")); + } + + // Total HT + /*$pdf->SetFillColor(255, 255, 255); + $pdf->SetXY($col1x, $tab2_top + 0); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("TotalHT").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("TotalHT") : ''), 0, 'L', 1); + $total_ht = (($conf->multicurrency->enabled && isset($object->multicurrency_tx) && $object->multicurrency_tx != 1) ? $object->multicurrency_total_ht : $object->total_ht); + $pdf->SetXY($col2x, $tab2_top + 0); + $pdf->MultiCell($largcol2, $tab2_hl, price($total_ht + (!empty($object->remise) ? $object->remise : 0), 0, $outputlangs), 0, 'R', 1);*/ + + // Show VAT by rates and total + $pdf->SetFillColor(248, 248, 248); + + $total_ttc = $object->getValorisationTotale(); + + $this->atleastoneratenotnull = 0; + + // Total TTC + $index++; + $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); + $pdf->SetTextColor(0, 0, 60); + $pdf->SetFillColor(224, 224, 224); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("Total").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transcountrynoentities("Total", $mysoc->country_code) : ''), $useborder, 'L', 1); + + $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($largcol2, $tab2_hl, price($total_ttc, 0, $outputlangs), $useborder, 'R', 1); + + $pdf->SetTextColor(0, 0, 0); + + $creditnoteamount = 0; + $depositsamount = 0; + //$creditnoteamount=$object->getSumCreditNotesUsed(); + //$depositsamount=$object->getSumDepositsUsed(); + //print "x".$creditnoteamount."-".$depositsamount;exit; + $resteapayer = price2num($total_ttc - $deja_regle - $creditnoteamount - $depositsamount, 'MT'); + if (!empty($object->paye)) $resteapayer = 0; + + if ($deja_regle > 0) { + // Already paid + Deposits + $index++; + + $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("AlreadyPaid").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("AlreadyPaid") : ''), 0, 'L', 0); + $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($largcol2, $tab2_hl, price($deja_regle, 0, $outputlangs), 0, 'R', 0); + + $index++; + $pdf->SetTextColor(0, 0, 60); + $pdf->SetFillColor(224, 224, 224); + $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("RemainderToPay").(is_object($outputlangsbis) ? ' / '.$outputlangsbis->transnoentities("AlreadyPaid") : ''), $useborder, 'L', 1); + + $pdf->SetXY($col2x, $tab2_top + $tab2_hl * $index); + $pdf->MultiCell($largcol2, $tab2_hl, price($resteapayer, 0, $outputlangs), $useborder, 'R', 1); + + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->SetTextColor(0, 0, 0); + } + + $index++; + return ($tab2_top + ($tab2_hl * $index)); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Show table for lines + * + * @param TCPDF $pdf Object PDF + * @param string $tab_top Top position of table + * @param string $tab_height Height of table (rectangle) + * @param int $nexY Y (not used) + * @param Translate $outputlangs Langs object + * @param int $hidetop 1=Hide top bar of array and title, 0=Hide nothing, -1=Hide only title + * @param int $hidebottom Hide bottom bar of array + * @param string $currency Currency code + * @return void + */ + protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0, $currency = '') + { + global $conf; + + // Force to disable hidetop and hidebottom + $hidebottom = 0; + if ($hidetop) $hidetop = -1; + + $currency = !empty($currency) ? $currency : $conf->currency; + $default_font_size = pdf_getPDFFontSize($outputlangs); + + // Amount in (at tab_top - 1) + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', '', $default_font_size - 2); + + if (empty($hidetop)) { + $titre = $outputlangs->transnoentities("AmountInCurrency", $outputlangs->transnoentitiesnoconv("Currency".$currency)); + $pdf->SetXY($this->page_largeur - $this->marge_droite - ($pdf->GetStringWidth($titre) + 3), $tab_top - 4); + $pdf->MultiCell(($pdf->GetStringWidth($titre) + 3), 2, $titre); + + //$conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR='230,230,230'; + if (!empty($conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)) { + $pdf->Rect($this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_droite - $this->marge_gauche, $this->tabTitleHeight, 'F', null, explode(',', $conf->global->MAIN_PDF_TITLE_BACKGROUND_COLOR)); + } + } + + $pdf->SetDrawColor(128, 128, 128); + $pdf->SetFont('', '', $default_font_size - 1); + + // Output Rect + $this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect takes a length in 3rd parameter and 4th parameter + + + $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); + + if (empty($hidetop)) { + $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter + } + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Show top header of page. + * + * @param TCPDF $pdf Object PDF + * @param Object $object Object to show + * @param int $showaddress 0=no, 1=yes + * @param Translate $outputlangs Object lang for output + * @param string $titlekey Translation key to show as title of document + * @return int Return topshift value + */ + protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $titlekey = "StockTransferSheetProforma") + { + // phpcs:enable + global $conf, $langs, $hookmanager; + + // Load traductions files required by page + $outputlangs->loadLangs(array("main", "bills", "propal", "orders", "companies")); + + $default_font_size = pdf_getPDFFontSize($outputlangs); + + pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); + + // Show Draft Watermark + if ($object->statut == 0 && (!empty($conf->global->COMMANDE_DRAFT_WATERMARK))) { + pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->COMMANDE_DRAFT_WATERMARK); + } + + $pdf->SetTextColor(0, 0, 60); + $pdf->SetFont('', 'B', $default_font_size + 3); + + $posy = $this->marge_haute; + $posx = $this->page_largeur - $this->marge_droite - 100; + + $pdf->SetXY($this->marge_gauche, $posy); + + // Logo + if (empty($conf->global->PDF_DISABLE_MYCOMPANY_LOGO)) { + if ($this->emetteur->logo) { + $logodir = $conf->mycompany->dir_output; + if (!empty($conf->mycompany->multidir_output[$object->entity])) $logodir = $conf->mycompany->multidir_output[$object->entity]; + if (empty($conf->global->MAIN_PDF_USE_LARGE_LOGO)) { + $logo = $logodir.'/logos/thumbs/'.$this->emetteur->logo_small; + } else { + $logo = $logodir.'/logos/'.$this->emetteur->logo; + } + if (is_readable($logo)) { + $height = pdf_getHeightForLogo($logo); + $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) + } else { + $pdf->SetTextColor(200, 0, 0); + $pdf->SetFont('', 'B', $default_font_size - 2); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L'); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L'); + } + } else { + $text = $this->emetteur->name; + $pdf->MultiCell(100, 4, $outputlangs->convToOutputCharset($text), 0, 'L'); + } + } + + $pdf->SetFont('', 'B', $default_font_size + 3); + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $title = $outputlangs->transnoentities($titlekey); + $pdf->MultiCell(100, 3, $title, '', 'R'); + + $pdf->SetFont('', 'B', $default_font_size); + + $posy += 5; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell(100, 4, $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref), '', 'R'); + + $posy += 1; + $pdf->SetFont('', '', $default_font_size - 1); + + // Date prévue depart + if (!empty($object->date_prevue_depart)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DatePrevueDepart")." : ".dol_print_date($object->date_prevue_depart, "day", false, $outputlangs, true), '', 'R'); + } + + // Date prévue arrivée + if (!empty($object->date_prevue_arrivee)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DatePrevueArrivee")." : ".dol_print_date($object->date_prevue_arrivee, "day", false, $outputlangs, true), '', 'R'); + } + + // Date reelle depart + if (!empty($object->date_reelle_depart)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateReelleDepart")." : ".dol_print_date($object->date_reelle_depart, "day", false, $outputlangs, true), '', 'R'); + } + + // Date reelle arrivée + if (!empty($object->date_reelle_arrivee)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateReelleArrivee")." : ".dol_print_date($object->date_reelle_arrivee, "day", false, $outputlangs, true), '', 'R'); + } + + if ($object->ref_client) { + $posy += 5; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("RefCustomer")." : ".$outputlangs->convToOutputCharset($object->ref_client), '', 'R'); + } + + if (!empty($conf->global->PDF_SHOW_PROJECT_TITLE)) { + $object->fetch_projet(); + if (!empty($object->project->ref)) { + $posy += 3; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("Project")." : ".(empty($object->project->title) ? '' : $object->projet->title), '', 'R'); + } + } + + if (!empty($conf->global->PDF_SHOW_PROJECT)) { + $object->fetch_projet(); + if (!empty($object->project->ref)) { + $posy += 3; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefProject")." : ".(empty($object->project->ref) ? '' : $object->projet->ref), '', 'R'); + } + } + + if (!empty($conf->global->DOC_SHOW_CUSTOMER_CODE) && !empty($object->thirdparty->code_client)) { + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell(100, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R'); + } + + // Get contact + if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); + if (count($arrayidcontact) > 0) { + $usertmp = new User($this->db); + $usertmp->fetch($arrayidcontact[0]); + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell(100, 3, $langs->trans("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); + } + } + + $posy += 2; + + $top_shift = 0; + // Show list of linked objects + $current_y = $pdf->getY(); + $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, 100, 3, 'R', $default_font_size); + if ($current_y < $pdf->getY()) { + $top_shift = $pdf->getY() - $current_y; + } + + if ($showaddress) { + // Sender properties + $carac_emetteur = ''; + // Add internal contact of origin element if defined + $arrayidcontact = array(); + $arrayidcontact = $object->getIdContact('external', 'STFROM'); + + $usecontact = false; + if (count($arrayidcontact) > 0) { + /*$object->fetch_user(reset($arrayidcontact)); + $carac_emetteur .= ($carac_emetteur ? "\n" : '').$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n";*/ + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); + } + + if ($usecontact) $thirdparty = $object->contact; + else $thirdparty = $this->emetteur; + + if (!empty($thirdparty)) $carac_emetteur_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); + + if ($usecontact) $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, $object->contact, 1, 'targetwithdetails', $object); + else $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object); + + // Show sender + $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; + $posx = $this->marge_gauche; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80; + + $hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40; + $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82; + + // Show sender frame + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posx, $posy - 5); + $pdf->MultiCell(66, 5, $outputlangs->transnoentities("Sender").":", 0, 'L'); + $pdf->SetXY($posx, $posy); + $pdf->SetFillColor(230, 230, 230); + $pdf->MultiCell($widthrecbox, $hautcadre, "", 0, 'R', 1); + $pdf->SetTextColor(0, 0, 60); + $pdf->SetFillColor(255, 255, 255); + + // Show sender name + $pdf->SetXY($posx + 2, $posy + 3); + $pdf->SetFont('', 'B', $default_font_size); + $pdf->MultiCell($widthrecbox - 2, 4, $outputlangs->convToOutputCharset($carac_emetteur_name), 0, 'L'); + $posy = $pdf->getY(); + + // Show sender information + $pdf->SetXY($posx + 2, $posy); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->MultiCell($widthrecbox - 2, 4, $carac_emetteur, 0, 'L'); + + + // If SHIPPING contact defined, we use it + $usecontact = false; + $arrayidcontact = $object->getIdContact('external', 'STDEST'); + if (count($arrayidcontact) > 0) { + $usecontact = true; + $result = $object->fetch_contact($arrayidcontact[0]); + } + + //Recipient name + // On peut utiliser le nom de la societe du contact + if ($usecontact/* && !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)*/) { + $thirdparty = $object->contact; + } else { + $thirdparty = $object->thirdparty; + } + + if (!empty($thirdparty)) $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); + + $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, (!empty($object->contact) ? $object->contact : null), $usecontact, 'targetwithdetails', $object); + + // Show recipient + $widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100; + if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format + $posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42; + $posx = $this->page_largeur - $this->marge_droite - $widthrecbox; + if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche; + + // Show recipient frame + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', '', $default_font_size - 2); + $pdf->SetXY($posx + 2, $posy - 5); + $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("Recipient").":", 0, 'L'); + $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre); + + // Show recipient name + $pdf->SetXY($posx + 2, $posy + 3); + $pdf->SetFont('', 'B', $default_font_size); + $pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L'); + + $posy = $pdf->getY(); + + // Show recipient information + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->SetXY($posx + 2, $posy); + $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L'); + } + + $pdf->SetTextColor(0, 0, 0); + return $top_shift; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Show footer of page. Need this->emetteur object + * + * @param TCPDF $pdf PDF + * @param Object $object Object to show + * @param Translate $outputlangs Object lang for output + * @param int $hidefreetext 1=Hide free text + * @return int Return height of bottom margin including footer text + */ + protected function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0) + { + // phpcs:enable + global $conf; + $showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; + return pdf_pagefoot($pdf, $outputlangs, 'ORDER_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext); + } + + + + /** + * Define Array Column Field + * + * @param object $object common object + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return null + */ + public function defineColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + global $conf, $hookmanager; + + // Default field style for content + $this->defaultContentsFieldsStyle = array( + 'align' => 'R', // R,C,L + 'padding' => array(1, 0.5, 1, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ); + + // Default field style for content + $this->defaultTitlesFieldsStyle = array( + 'align' => 'C', // R,C,L + 'padding' => array(0.5, 0, 0.5, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ); + + /* + * For exemple + $this->cols['theColKey'] = array( + 'rank' => $rank, // int : use for ordering columns + 'width' => 20, // the column width in mm + 'title' => array( + 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label + 'label' => ' ', // the final label : used fore final generated text + 'align' => 'L', // text alignement : R,C,L + 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'content' => array( + 'align' => 'L', // text alignement : R,C,L + 'padding' => array(0.5,0.5,0.5,0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + ); + */ + + $rank = 0; // do not use negative rank + $this->cols['desc'] = array( + 'rank' => $rank, + 'width' => false, // only for desc + 'status' => true, + 'title' => array( + 'textkey' => 'Designation', // use lang key is usefull in somme case with module + 'align' => 'L', + // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label + // 'label' => ' ', // the final label + 'padding' => array(0.5, 1, 0.5, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'content' => array( + 'align' => 'L', + 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + ); + + $rank = $rank + 10; + $this->cols['photo'] = array( + 'rank' => $rank, + 'width' => (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH), // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Photo', + 'label' => ' ' + ), + 'content' => array( + 'padding' => array(0, 0, 0, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'border-left' => false, // remove left line separator + ); + + if (!empty($conf->global->MAIN_GENERATE_ORDERS_WITH_PICTURE)) { + $this->cols['photo']['status'] = true; + } + + + $rank = $rank + 10; + $this->cols['vat'] = array( + 'rank' => $rank, + 'status' => false, + 'width' => 16, // in mm + 'title' => array( + 'textkey' => 'VAT' + ), + 'border-left' => true, // add left line separator + ); + + /*if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) + { + $this->cols['vat']['status'] = true; + }*/ + + $rank = $rank + 10; + $this->cols['subprice'] = array( + 'rank' => $rank, + 'width' => 19, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'PMPValueShort' + ), + 'border-left' => true, // add left line separator + ); + + // Adapt dynamically the width of subprice, if text is too long. + $tmpwidth = 0; + $nblines = count($object->lines); + for ($i = 0; $i < $nblines; $i++) { + $tmpwidth2 = dol_strlen(dol_string_nohtmltag(pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails))); + $tmpwidth = max($tmpwidth, $tmpwidth2); + } + if ($tmpwidth > 10) { + $this->cols['subprice']['width'] += (2 * ($tmpwidth - 10)); + } + + $rank = $rank + 10; + $this->cols['qty'] = array( + 'rank' => $rank, + 'width' => 16, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'Qty' + ), + 'border-left' => true, // add left line separator + ); + + $rank = $rank + 10; + $this->cols['unit'] = array( + 'rank' => $rank, + 'width' => 11, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Unit' + ), + 'border-left' => true, // add left line separator + ); + if ($conf->global->PRODUCT_USE_UNITS) { + $this->cols['unit']['status'] = true; + } + + $rank = $rank + 10; + $this->cols['discount'] = array( + 'rank' => $rank, + 'width' => 13, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'ReductionShort' + ), + 'border-left' => true, // add left line separator + ); + if ($this->atleastonediscount) { + $this->cols['discount']['status'] = true; + } + + $rank = $rank + 1000; // add a big offset to be sure is the last col because default extrafield rank is 100 + $this->cols['totalexcltax'] = array( + 'rank' => $rank, + 'width' => 26, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'PMPValue' + ), + 'border-left' => true, // add left line separator + ); + + // Add extrafields cols + if (!empty($object->lines)) { + $line = reset($object->lines); + $this->defineColumnExtrafield($line, $outputlangs, $hidedetails); + } + + $parameters = array( + 'object' => $object, + 'outputlangs' => $outputlangs, + 'hidedetails' => $hidedetails, + 'hidedesc' => $hidedesc, + 'hideref' => $hideref + ); + + $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } elseif (empty($reshook)) { + $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys + } else { + $this->cols = $hookmanager->resArray; + } + } +} diff --git a/htdocs/core/modules/stocktransfer/mod_stocktransfer_advanced.php b/htdocs/core/modules/stocktransfer/mod_stocktransfer_advanced.php new file mode 100644 index 00000000000..fab0952e894 --- /dev/null +++ b/htdocs/core/modules/stocktransfer/mod_stocktransfer_advanced.php @@ -0,0 +1,149 @@ + + * Copyright (C) 2004-2007 Laurent Destailleur + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2008 Raphael Bertrand (Resultic) + * Copyright (C) 2019 Frédéric France + * Copyright (C) 2021 Gauthier VERDOL + * + * 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 . + * or see https://www.gnu.org/ + */ + +/** + * \file htdocs/core/modules/stocktransfer/mod_stocktransfer_advanced.php + * \ingroup stocktransfer + * \brief File containing class for advanced numbering model of StockTransfer + */ + +require_once DOL_DOCUMENT_ROOT . '/core/modules/stocktransfer/modules_stocktransfer.php'; + + +/** + * Class to manage customer Bom numbering rules advanced + */ +class mod_stocktransfer_advanced extends ModeleNumRefStockTransfer +{ + /** + * Dolibarr version of the loaded document + * @var string + */ + public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' + + /** + * @var string Error message + */ + public $error = ''; + + /** + * @var string name + */ + public $name = 'got2be'; + + + /** + * Returns the description of the numbering model + * + * @return string Texte descripif + */ + public function info() + { + global $conf, $langs, $db; + + $langs->load("bills"); + + $form = new Form($db); + + $texte = $langs->trans('GenericNumRefModelDesc')."
    \n"; + $texte .= '
    '; + $texte .= ''; + $texte .= ''; + $texte .= ''; + $texte .= ''; + + $tooltip = $langs->trans("GenericMaskCodes", $langs->transnoentities("StockTransfer"), $langs->transnoentities("StockTransfer")); + $tooltip .= $langs->trans("GenericMaskCodes2"); + $tooltip .= $langs->trans("GenericMaskCodes3"); + $tooltip .= $langs->trans("GenericMaskCodes4a", $langs->transnoentities("StockTransfer"), $langs->transnoentities("StockTransfer")); + $tooltip .= $langs->trans("GenericMaskCodes5"); + + // Parametrage du prefix + $texte .= ''; + $texte .= ''; + + $texte .= ''; + + $texte .= ''; + + $texte .= '
    '.$langs->trans("Mask").':'.$form->textwithpicto('', $tooltip, 1, 1).' 
    '; + $texte .= '
    '; + + return $texte; + } + + /** + * Return an example of numbering + * + * @return string Example + */ + public function getExample() + { + global $conf, $db, $langs, $mysoc; + + $object = new StockTransfer($db); + $object->initAsSpecimen(); + + /*$old_code_client = $mysoc->code_client; + $old_code_type = $mysoc->typent_code; + $mysoc->code_client = 'CCCCCCCCCC'; + $mysoc->typent_code = 'TTTTTTTTTT';*/ + + $numExample = $this->getNextValue($object); + + /*$mysoc->code_client = $old_code_client; + $mysoc->typent_code = $old_code_type;*/ + + if (!$numExample) { + $numExample = $langs->trans('NotConfigured'); + } + return $numExample; + } + + /** + * Return next free value + * + * @param Object $object Object we need next value for + * @return string Value if KO, <0 if KO + */ + public function getNextValue($object) + { + global $db, $conf; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + + // We get cursor rule + $mask = $conf->global->STOCKTRANSFER_STOCKTRANSFER_ADVANCED_MASK; + + if (!$mask) { + $this->error = 'NotConfigured'; + return 0; + } + + $date = $object->date; + + $numFinal = get_next_value($db, $mask, 'stocktransfer_stocktransfer', 'ref', '', null, $date); + + return $numFinal; + } +} diff --git a/htdocs/core/modules/stocktransfer/mod_stocktransfer_standard.php b/htdocs/core/modules/stocktransfer/mod_stocktransfer_standard.php new file mode 100644 index 00000000000..6a6c7c556e6 --- /dev/null +++ b/htdocs/core/modules/stocktransfer/mod_stocktransfer_standard.php @@ -0,0 +1,154 @@ + + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2021 Gauthier VERDOL + * + * 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 . + * or see https://www.gnu.org/ + */ + +/** + * \file htdocs/core/modules/stocktransfer/mod_stocktransfer_standard.php + * \ingroup stocktransfer + * \brief File of class to manage StockTransfer numbering rules standard + */ +require_once DOL_DOCUMENT_ROOT . '/core/modules/stocktransfer/modules_stocktransfer.php'; + + +/** + * Class to manage customer order numbering rules standard + */ +class mod_stocktransfer_standard extends ModeleNumRefStockTransfer +{ + /** + * Dolibarr version of the loaded document + * @var string + */ + public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' + + public $prefix = 'ST'; + + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * @var string name + */ + public $name = 'standard'; + + + /** + * Return description of numbering module + * + * @return string Text with description + */ + public function info() + { + global $langs; + return $langs->trans("SimpleNumRefModelDesc", $this->prefix); + } + + + /** + * Return an example of numbering + * + * @return string Example + */ + public function getExample() + { + return $this->prefix."0501-0001"; + } + + + /** + * Checks if the numbers already in the database do not + * cause conflicts that would prevent this numbering working. + * + * @param Object $object Object we need next value for + * @return boolean false if conflict, true if ok + */ + public function canBeActivated($object) + { + global $conf, $langs, $db; + + $coyymm = ''; $max = ''; + + $posindice = strlen($this->prefix) + 6; + $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max"; + $sql .= " FROM ".MAIN_DB_PREFIX."stocktransfer_stocktransfer"; + $sql .= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'"; + if ($object->ismultientitymanaged == 1) { + $sql .= " AND entity = ".$conf->entity; + } elseif ($object->ismultientitymanaged == 2) { + // TODO + } + + $resql = $db->query($sql); + if ($resql) { + $row = $db->fetch_row($resql); + if ($row) { $coyymm = substr($row[0], 0, 6); $max = $row[0]; } + } + if ($coyymm && !preg_match('/'.$this->prefix.'[0-9][0-9][0-9][0-9]/i', $coyymm)) { + $langs->load("errors"); + $this->error = $langs->trans('ErrorNumRefModel', $max); + return false; + } + + return true; + } + + /** + * Return next free value + * + * @param Object $object Object we need next value for + * @return string Value if KO, <0 if KO + */ + public function getNextValue($object) + { + global $db, $conf; + + // first we get the max value + $posindice = strlen($this->prefix) + 6; + $sql = "SELECT MAX(CAST(SUBSTRING(ref FROM ".$posindice.") AS SIGNED)) as max"; + $sql .= " FROM ".MAIN_DB_PREFIX."stocktransfer_stocktransfer"; + $sql .= " WHERE ref LIKE '".$db->escape($this->prefix)."____-%'"; + if ($object->ismultientitymanaged == 1) { + $sql .= " AND entity = ".$conf->entity; + } elseif ($object->ismultientitymanaged == 2) { + // TODO + } + + $resql = $db->query($sql); + if ($resql) { + $obj = $db->fetch_object($resql); + if ($obj) $max = intval($obj->max); + else $max = 0; + } else { + dol_syslog("mod_stocktransfer_standard::getNextValue", LOG_DEBUG); + return -1; + } + + //$date=time(); + $date = $object->date_creation; + $yymm = strftime("%y%m", $date); + + if ($max >= (pow(10, 4) - 1)) $num = $max + 1; // If counter > 9999, we do not format on 4 chars, we take number as it is + else $num = sprintf("%04s", $max + 1); + + dol_syslog("mod_stocktransfer_standard::getNextValue return ".$this->prefix.$yymm."-".$num); + return $this->prefix.$yymm."-".$num; + } +} diff --git a/htdocs/core/modules/stocktransfer/modules_stocktransfer.php b/htdocs/core/modules/stocktransfer/modules_stocktransfer.php new file mode 100644 index 00000000000..3da0a0ae644 --- /dev/null +++ b/htdocs/core/modules/stocktransfer/modules_stocktransfer.php @@ -0,0 +1,151 @@ + + * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2006 Andre Cianfarani + * Copyright (C) 2012 Juanjo Menent + * Copyright (C) 2014 Marcos García + * Copyright (C) 2021 Gauthier VERDOL + * + * 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 . + * or see https://www.gnu.org/ + */ + +/** + * \file htdocs/core/modules/stocktransfer/modules_stocktransfer.php + * \ingroup stocktransfer + * \brief File that contains parent class for stocktransfers document models and parent class for stocktransfers numbering models + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/commondocgenerator.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; // required for use by classes that inherit + + +/** + * Parent class for documents models + */ +abstract class ModelePDFStockTransfer extends CommonDocGenerator +{ + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of active generation modules + * + * @param DoliDB $db Database handler + * @param integer $maxfilenamelength Max length of value to show + * @return array List of templates + */ + public static function liste_modeles($db, $maxfilenamelength = 0) + { + // phpcs:enable + global $conf; + + $type = 'stocktransfer'; + $list = array(); + + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + $list = getListOfModels($db, $type, $maxfilenamelength); + + return $list; + } +} + + + +/** + * Parent class to manage numbering of StockTransfer + */ +abstract class ModeleNumRefStockTransfer +{ + /** + * @var string Error code (or message) + */ + public $error = ''; + + /** + * Return if a module can be used or not + * + * @return boolean true if module can be used + */ + public function isEnabled() + { + return true; + } + + /** + * Returns the default description of the numbering template + * + * @return string Texte descripif + */ + public function info() + { + global $langs; + $langs->load("stocktransfer@stocktransfer"); + return $langs->trans("NoDescription"); + } + + /** + * Returns an example of numbering + * + * @return string Example + */ + public function getExample() + { + global $langs; + $langs->load("stocktransfer@stocktransfer"); + return $langs->trans("NoExample"); + } + + /** + * Checks if the numbers already in the database do not + * cause conflicts that would prevent this numbering working. + * + * @param Object $object Object we need next value for + * @return boolean false if conflict, true if ok + */ + public function canBeActivated($object) + { + return true; + } + + /** + * Returns next assigned value + * + * @param Object $object Object we need next value for + * @return string Valeur + */ + public function getNextValue($object) + { + global $langs; + return $langs->trans("NotAvailable"); + } + + /** + * Returns version of numbering module + * + * @return string Valeur + */ + public function getVersion() + { + global $langs; + $langs->load("admin"); + + if ($this->version == 'development') return $langs->trans("VersionDevelopment"); + if ($this->version == 'experimental') return $langs->trans("VersionExperimental"); + if ($this->version == 'dolibarr') return DOL_VERSION; + if ($this->version) return $this->version; + return $langs->trans("NotAvailable"); + } +} diff --git a/htdocs/core/tpl/login.tpl.php b/htdocs/core/tpl/login.tpl.php index ccec4352e89..5965132d68c 100644 --- a/htdocs/core/tpl/login.tpl.php +++ b/htdocs/core/tpl/login.tpl.php @@ -1,6 +1,6 @@ - * Copyright (C) 2011-2021 Laurent Destailleur + * Copyright (C) 2011-2022 Laurent Destailleur * * 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 @@ -18,7 +18,7 @@ // Need global variable $urllogo, $title and $titletruedolibarrversion to be defined by caller (like dol_loginfunction in security2.lib.php) // Caller can also set $morelogincontent = array(['options']=>array('js'=>..., 'table'=>...); - +// $titletruedolibarrversion must be defined if (!defined('NOBROWSERNOTIF')) { define('NOBROWSERNOTIF', 1); @@ -71,6 +71,12 @@ $php_self .= dol_escape_htmltag($_SERVER["QUERY_STRING"]) ? '?'.dol_escape_htmlt if (!preg_match('/mainmenu=/', $php_self)) { $php_self .= (preg_match('/\?/', $php_self) ? '&' : '?').'mainmenu=home'; } +if (preg_match('/'.preg_quote('core/modules/oauth', '/').'/', $php_self)) { + $php_self = DOL_URL_ROOT.'/index.php?mainmenu=home'; +} +$php_self = preg_replace('/(\?|&|&)action=[^&]+/', '\1', $php_self); +$php_self = preg_replace('/(\?|&|&)massaction=[^&]+/', '\1', $php_self); +$php_self = preg_replace('/(\?|&|&)token=[^&]+/', '\1', $php_self); // Javascript code on logon page only to detect user tz, dst_observed, dst_first, dst_second $arrayofjs = array( diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index edbffca0df5..6e2bee75e6e 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -394,11 +394,15 @@ if (empty($reshook)) { } } } else { - $mesg = $srcobject->error; + $langs->load("errors"); + setEventMessages($srcobject->error, $srcobject->errors, 'errors'); + $action = 'create'; $error++; } } else { - $mesg = $object->error; + $langs->load("errors"); + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; $error++; } } else { @@ -422,12 +426,14 @@ if (empty($reshook)) { $langs->load("errors"); setEventMessages($object->error, $object->errors, 'errors'); $action = 'create'; + $error++; } } } } else { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")); $action = 'create'; + $error++; } } elseif ($action == 'update' && $user->rights->ficheinter->creer) { $object->socid = $socid; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 0630d2df6a4..948e1c01deb 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -2354,14 +2354,6 @@ class FactureFournisseur extends CommonInvoice $info_bits = 0; } - if ($idproduct) { - $product = new Product($this->db); - $result = $product->fetch($idproduct); - $product_type = $product->type; - } else { - $product_type = $type; - } - //Fetch current line from the database and then clone the object and set it in $oldline property $line = new SupplierInvoiceLine($this->db); $line->fetch($id); @@ -2369,6 +2361,15 @@ class FactureFournisseur extends CommonInvoice $staticline = clone $line; + if ($idproduct) { + $product = new Product($this->db); + $result = $product->fetch($idproduct); + $product_type = $product->type; + } else { + $idproduct = $staticline->fk_product; + $product_type = $type; + } + $line->oldline = $staticline; $line->context = $this->context; diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 55aabde8141..d113eadd8a7 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -448,11 +448,11 @@ class ProductFournisseur extends Product // Add price for this quantity to supplier $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price("; $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,"; - $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type)"; + $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type"; if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= ", packaging"; } - $sql .= " values("; + $sql .= ") values("; $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').","; $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').","; $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').","; diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index a945a03b85d..6ab316edb56 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -143,9 +143,9 @@ $usercandelete = (($user->rights->fournisseur->commande->supprimer || $user->rig $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate))); // Additional area permissions -$usercanapprove = $user->rights->fournisseur->commande->approuver; -$usercanapprovesecond = $user->rights->fournisseur->commande->approve2; -$usercanorder = $user->rights->fournisseur->commande->commander; +$usercanapprove = !empty($user->rights->fournisseur->commande->approuver) ? $user->rights->fournisseur->commande->approuver : 0; +$usercanapprovesecond = !empty($user->rights->fournisseur->commande->approve2) ? $user->rights->fournisseur->commande->approve2 : 0; +$usercanorder = !empty($user->rights->fournisseur->commande->commander) ? $user->rights->fournisseur->commande->commander : 0; if (empty($conf->reception->enabled)) { $usercanreceive = $user->rights->fournisseur->commande->receptionner; } else { @@ -1627,8 +1627,8 @@ if ($action == 'create') { // Object source contacts list $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1); } else { - $cond_reglement_id = $societe->cond_reglement_supplier_id; - $mode_reglement_id = $societe->mode_reglement_supplier_id; + $cond_reglement_id = !empty($societe->cond_reglement_supplier_id) ? $societe->cond_reglement_supplier_id : 0; + $mode_reglement_id = !empty($societe->mode_reglement_supplier_id) ? $societe->mode_reglement_supplier_id : 0; if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) { $currency_code = $societe->multicurrency_code; @@ -1674,7 +1674,7 @@ if ($action == 'create') { print ''.$langs->trans('Supplier').''; print ''; - if ($societe->id > 0) { + if (!empty($societe->id) && $societe->id > 0) { print $societe->getNomUrl(1, 'supplier'); print ''; } else { @@ -1696,7 +1696,7 @@ if ($action == 'create') { } print ''; - if ($societe->id > 0) { + if (!empty($societe->id) && $societe->id > 0) { // Discounts for third party print ''.$langs->trans('Discounts').''; @@ -1752,7 +1752,7 @@ if ($action == 'create') { $langs->load('projects'); print ''.$langs->trans('Project').''; print img_picto('', 'project').$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500'); - print '   id).'">'; + print '   id) ? '&socid='.$societe->id : "")).'">'; print ''; } diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index ed6e421d302..5978b6a31be 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -101,7 +101,7 @@ if (!$sortorder) { $sortorder = "DESC"; } if (!$sortfield) { - $sortfield = "cp.rowid"; + $sortfield = "cp.ref"; } $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php index 427e6a4dea6..05d1dd89a88 100644 --- a/htdocs/imports/import.php +++ b/htdocs/imports/import.php @@ -799,6 +799,7 @@ if ($step == 4 && $datatoimport) { $minpos = min(count($fieldssource), count($fieldstarget)); //var_dump($array_match_file_to_database); + $initialloadofstep4 = false; if (empty($_SESSION['dol_array_match_file_to_database_select'])) { $initialloadofstep4 = true; @@ -971,6 +972,7 @@ if ($step == 4 && $datatoimport) { print ''; print img_mime($file, '', 'pictofixedwidth'); print $filetoimport; + print img_picto($langs->trans("Download"), 'download', 'class="paddingleft opacitymedium"'); print ''; print ''; @@ -1052,21 +1054,19 @@ if ($step == 4 && $datatoimport) { print ''; // Set the list of all possible target fields in Dolibarr. - $optionsnotused = ""; $optionsall = array(); foreach ($fieldstarget as $code => $line) { - $text = ''; - if (!$line["imported"]) { - $optionsnotused .= $text; - } - $optionsall[$code] = array('label'=>$langs->trans($line["label"]), 'required'=>(empty($line["required"]) ? 0 : 1), 'position'=>!empty($line['position']) ? $line['position'] : 0); } - // $optionsall is an array of all possible fields. key=>array('label'=>..., 'xxx') + // $optionsall is an array of all possible target fields. key=>array('label'=>..., 'xxx') $height = '32px'; //needs px for css height attribute below $i = 0; @@ -1119,7 +1119,11 @@ if ($step == 4 && $datatoimport) { $j = 0; foreach ($optionsall as $tmpcode => $tmpval) { // Loop on each entry to add into each combo list. - $label = $tmpval['required'] ? '' : ''; + $label = ''; + if (!empty($tmpval['picto'])) { + $label .= img_picto('', $tmpval['picto'], 'class="pictofixedwidth"'); + } + $label .= $tmpval['required'] ? '' : ''; $label .= $tmpval['label']; $label .= $tmpval['required'] ? '*' : ''; @@ -1599,6 +1603,7 @@ if ($step == 5 && $datatoimport) { print ''; print img_mime($file, '', 'pictofixedwidth'); print $filetoimport; + print img_picto($langs->trans("Download"), 'download', 'class="paddingleft opacitymedium"'); print ''; print ''; @@ -1743,9 +1748,9 @@ if ($step == 5 && $datatoimport) { } //print $code.'-'.$label; $alias = preg_replace('/(\..*)$/i', '', $label); - $listfields[$i] = $langs->trans("Field").' '.$code.'->'.$label; + $listfields[$i] = $langs->trans("Column").' '.num2Alpha($code - 1).' -> '.$label; } - print count($listfields) ? (join(', ', $listfields)) : $langs->trans("Error"); + print count($listfields) ? (join(',  ', $listfields)) : $langs->trans("Error"); print ''; print ''; @@ -2349,20 +2354,6 @@ function show_elem($fieldssource, $pos, $key, $var, $nostyle = '') } -/** - * Return a numeric into an Excel like column number - * - * @param string $n Numeric value - * @return string Column in Excel format - */ -function num2Alpha($n) -{ - for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) - $r = chr($n%26 + 0x41) . $r; - return $r; -} - - /** * Return not used field number * diff --git a/htdocs/install/doctemplates/boms/template_bom.odt b/htdocs/install/doctemplates/boms/template_bom.odt index 701753c3dba..573e97a0a84 100644 Binary files a/htdocs/install/doctemplates/boms/template_bom.odt and b/htdocs/install/doctemplates/boms/template_bom.odt differ diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer-stocktransfer.key.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer-stocktransfer.key.sql new file mode 100644 index 00000000000..74108a5face --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer-stocktransfer.key.sql @@ -0,0 +1,29 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + + +-- BEGIN MODULEBUILDER INDEXES +ALTER TABLE llx_stocktransfer_stocktransfer ADD INDEX idx_stocktransfer_stocktransfer_rowid (rowid); +ALTER TABLE llx_stocktransfer_stocktransfer ADD INDEX idx_stocktransfer_stocktransfer_ref (ref); +ALTER TABLE llx_stocktransfer_stocktransfer ADD INDEX idx_stocktransfer_stocktransfer_fk_soc (fk_soc); +ALTER TABLE llx_stocktransfer_stocktransfer ADD INDEX idx_stocktransfer_stocktransfer_fk_project (fk_project); +ALTER TABLE llx_stocktransfer_stocktransfer ADD CONSTRAINT llx_stocktransfer_stocktransfer_fk_user_creat FOREIGN KEY (fk_user_creat) REFERENCES llx_user(rowid); +ALTER TABLE llx_stocktransfer_stocktransfer ADD INDEX idx_stocktransfer_stocktransfer_status (status); +-- END MODULEBUILDER INDEXES + +--ALTER TABLE llx_stocktransfer_stocktransfer ADD UNIQUE INDEX uk_stocktransfer_stocktransfer_fieldxy(fieldx, fieldy); + +--ALTER TABLE llx_stocktransfer_stocktransfer ADD CONSTRAINT llx_stocktransfer_stocktransfer_fk_field FOREIGN KEY (fk_field) REFERENCES llx_stocktransfer_myotherobject(rowid); + diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer-stocktransfer.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer-stocktransfer.sql new file mode 100644 index 00000000000..e04a6dcb1ec --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer-stocktransfer.sql @@ -0,0 +1,46 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + + +CREATE TABLE llx_stocktransfer_stocktransfer( + -- BEGIN MODULEBUILDER FIELDS + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + entity integer DEFAULT 1 NOT NULL, + ref varchar(128) DEFAULT '(PROV)' NOT NULL, + label varchar(255), + fk_soc integer, + fk_project integer, + fk_warehouse_source integer, + fk_warehouse_destination integer, + description text, + note_public text, + note_private text, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + date_creation datetime NOT NULL, + date_prevue_depart date DEFAULT NULL, + date_reelle_depart date DEFAULT NULL, + date_prevue_arrivee date DEFAULT NULL, + date_reelle_arrivee date DEFAULT NULL, + lead_time_for_warning integer DEFAULT NULL, + fk_user_creat integer NOT NULL, + fk_user_modif integer, + import_key varchar(14), + model_pdf varchar(255), + last_main_doc varchar(255), + status smallint NOT NULL, + fk_incoterms integer, -- for incoterms + location_incoterms varchar(255) + -- END MODULEBUILDER FIELDS +) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer_extrafields-stocktransfer.key.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer_extrafields-stocktransfer.key.sql new file mode 100644 index 00000000000..36850341a6c --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer_extrafields-stocktransfer.key.sql @@ -0,0 +1,19 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + + +-- BEGIN MODULEBUILDER INDEXES +ALTER TABLE llx_stocktransfer_stocktransfer_extrafields ADD INDEX idx_fk_object(fk_object); +-- END MODULEBUILDER INDEXES diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer_extrafields-stocktransfer.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer_extrafields-stocktransfer.sql new file mode 100644 index 00000000000..e03a0bf5343 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransfer_extrafields-stocktransfer.sql @@ -0,0 +1,23 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + +create table llx_stocktransfer_stocktransfer_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_object integer NOT NULL, + import_key varchar(14) -- import key +) ENGINE=innodb; + diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline-stocktransfer.key.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline-stocktransfer.key.sql new file mode 100644 index 00000000000..32dfbd8bcd2 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline-stocktransfer.key.sql @@ -0,0 +1,24 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + + +-- BEGIN MODULEBUILDER INDEXES +ALTER TABLE llx_stocktransfer_stocktransferline ADD INDEX idx_stocktransfer_stocktransferline_rowid (rowid); +-- END MODULEBUILDER INDEXES + +--ALTER TABLE llx_stocktransfer_stocktransferline ADD UNIQUE INDEX uk_stocktransfer_stocktransferline_fieldxy(fieldx, fieldy); + +--ALTER TABLE llx_stocktransfer_stocktransferline ADD CONSTRAINT llx_stocktransfer_stocktransferline_fk_field FOREIGN KEY (fk_field) REFERENCES llx_stocktransfer_myotherobject(rowid); + diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline-stocktransfer.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline-stocktransfer.sql new file mode 100644 index 00000000000..10c22fed32c --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline-stocktransfer.sql @@ -0,0 +1,31 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + + +CREATE TABLE llx_stocktransfer_stocktransferline( + -- BEGIN MODULEBUILDER FIELDS + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + amount double DEFAULT NULL, + qty real, + fk_warehouse_source integer NOT NULL, + fk_warehouse_destination integer NOT NULL, + fk_stocktransfer integer NOT NULL, + fk_product integer NOT NULL, + batch varchar(128) DEFAULT NULL, -- Lot or serial number + pmp double, + rang integer DEFAULT 0, + fk_parent_line integer NULL + -- END MODULEBUILDER FIELDS +) ENGINE=innodb; diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline_extrafields-stocktransfer.key.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline_extrafields-stocktransfer.key.sql new file mode 100644 index 00000000000..a35079cbf0c --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline_extrafields-stocktransfer.key.sql @@ -0,0 +1,19 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + + +-- BEGIN MODULEBUILDER INDEXES +ALTER TABLE llx_stocktransfer_stocktransferline_extrafields ADD INDEX idx_fk_object(fk_object); +-- END MODULEBUILDER INDEXES diff --git a/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline_extrafields-stocktransfer.sql b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline_extrafields-stocktransfer.sql new file mode 100644 index 00000000000..ecb256699b5 --- /dev/null +++ b/htdocs/install/mysql/tables/llx_stocktransfer_stocktransferline_extrafields-stocktransfer.sql @@ -0,0 +1,23 @@ +-- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2021 Gauthier VERDOL +-- 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 https://www.gnu.org/licenses/. + +create table llx_stocktransfer_stocktransferline_extrafields +( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + fk_object integer NOT NULL, + import_key varchar(14) -- import key +) ENGINE=innodb; + diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index 8f44b999a3a..c4a964b6b62 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -163,14 +163,14 @@ ProfId5CL=- ProfId6CL=- ProfId1CM=Id. prof. 1 (Trade Register) ProfId2CM=Id. prof. 2 (Taxpayer No.) -ProfId3CM=Id. prof. 3 (Decree of creation) -ProfId4CM=Id. prof. 4 (Certificate of deposits) +ProfId3CM=Id. prof. 3 (No. of creation decree) +ProfId4CM=Id. prof. 4 (Deposit certificate No.) ProfId5CM=Id. prof. 5 (Others) ProfId6CM=- ProfId1ShortCM=Trade Register ProfId2ShortCM=Taxpayer No. -ProfId3ShortCM=Decree of creation -ProfId4ShortCM=Certificate of deposits +ProfId3ShortCM=No. of creation decree +ProfId4ShortCM=Deposit certificate No. ProfId5ShortCM=Others ProfId6ShortCM=- ProfId1CO=Prof Id 1 (R.U.T.) diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang index b39d3243376..13f480be0ed 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -322,11 +322,6 @@ WarningAvailableOnlyForHTTPSServers=Available only if using HTTPS secured connec WarningModuleXDisabledSoYouMayMissEventHere=Module %s has not been enabled. So you may miss a lot of event here. WarningPaypalPaymentNotCompatibleWithStrict=The value 'Strict' makes the online payment features not working correctly. Use 'Lax' instead. -<<<<<<< HEAD -======= -<<<<<<< HEAD -<<<<<<< HEAD ->>>>>>> branch '15.0' of git@github.com:Dolibarr/dolibarr.git # Validate RequireValidValue = Value not valid RequireAtLeastXString = Requires at least %s character(s) @@ -347,12 +342,3 @@ BadSetupOfField = Error bad setup of field BadSetupOfFieldClassNotFoundForValidation = Error bad setup of field : Class not found for validation BadSetupOfFieldFileNotFound = Error bad setup of field : File not found for inclusion BadSetupOfFieldFetchNotCallable = Error bad setup of field : Fetch not callable on class -<<<<<<< HEAD -======= -======= -======= ->>>>>>> branch '13.0' of git@github.com:Dolibarr/dolibarr.git ->>>>>>> branch '14.0' of git@github.com:Dolibarr/dolibarr.git -======= ->>>>>>> branch '14.0' of git@github.com:Dolibarr/dolibarr.git ->>>>>>> branch '15.0' of git@github.com:Dolibarr/dolibarr.git diff --git a/htdocs/langs/en_US/exports.lang b/htdocs/langs/en_US/exports.lang index 9dc400f91f7..c6dd04fd488 100644 --- a/htdocs/langs/en_US/exports.lang +++ b/htdocs/langs/en_US/exports.lang @@ -82,7 +82,7 @@ SelectFormat=Choose this import file format RunImportFile=Import Data NowClickToRunTheImport=Check the results of the import simulation. Correct any errors and re-test.
    When the simulation reports no errors you may proceed to import the data into the database. DataLoadedWithId=The imported data will have an additional field in each database table with this import id: %s, to allow it to be searchable in the case of investigating a problem related to this import. -ErrorMissingMandatoryValue=Mandatory data is empty in the source file for field %s. +ErrorMissingMandatoryValue=Mandatory data is empty in the source file in column %s. TooMuchErrors=There are still %s other source lines with errors but output has been limited. TooMuchWarnings=There are still %s other source lines with warnings but output has been limited. EmptyLine=Empty line (will be discarded) @@ -92,9 +92,9 @@ YouCanUseImportIdToFindRecord=You can find all the imported records in your data NbOfLinesOK=Number of lines with no errors and no warnings: %s. NbOfLinesImported=Number of lines successfully imported: %s. DataComeFromNoWhere=Value to insert comes from nowhere in source file. -DataComeFromFileFieldNb=Value to insert comes from field number %s in source file. -DataComeFromIdFoundFromRef=Value that comes from field number %s of source file will be used to find the id of the parent object to use (so the object %s that has the ref. from source file must exist in the database). -DataComeFromIdFoundFromCodeId=Code that comes from field number %s of source file will be used to find the id of the parent object to use (so the code from source file must exist in the dictionary %s). Note that if you know the id, you can also use it in the source file instead of the code. Import should work in both cases. +DataComeFromFileFieldNb=Value to insert comes from column %s in source file. +DataComeFromIdFoundFromRef=Value that comes from column %s of source file will be used to find the id of the parent object to use (so the object %s that has the ref. from source file must exist in the database). +DataComeFromIdFoundFromCodeId=Code that comes from column %s of source file will be used to find the id of the parent object to use (so the code from source file must exist in the dictionary %s). Note that if you know the id, you can also use it in the source file instead of the code. Import should work in both cases. DataIsInsertedInto=Data coming from source file will be inserted into the following field: DataIDSourceIsInsertedInto=The id of the parent object, that was found using the data in the source file, will be inserted into the following field: DataCodeIDSourceIsInsertedInto=The id of the parent line, that was found from code, will be inserted into the following field: diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index af9894a7897..05d0ec1e060 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -1176,4 +1176,5 @@ CommercialsAffected=Sales representatives affected CommercialAffected=Sales representative affected YourMessage=Votre message YourMessageHasBeenReceived=Your message has been received. We will answer or contact you as soon as possible. -UrlToCheck=Url to check \ No newline at end of file +UrlToCheck=Url to check +Automation=Automation \ No newline at end of file diff --git a/htdocs/langs/en_US/stocks.lang b/htdocs/langs/en_US/stocks.lang index 0c412beed6e..dbd15ec4da2 100644 --- a/htdocs/langs/en_US/stocks.lang +++ b/htdocs/langs/en_US/stocks.lang @@ -271,4 +271,46 @@ ErrorCantFindCodeInInventory=Can't find the following code in inventory QtyWasAddedToTheScannedBarcode=Success !! The quantity was added to all the requested barcode. You can close the Scanner tool. StockChangeDisabled=Change on stock disabled NoWarehouseDefinedForTerminal=No warehouse defined for terminal -ClearQtys=Clear all quantities \ No newline at end of file +ClearQtys=Clear all quantities +ModuleStockTransferName=Advanced Stock Transfer +ModuleStockTransferDesc=Advanced management of Stock Transfer, with generation of transfer sheet +StockTransferNew=New stocks transfer +StockTransferList=Stocks transfers list +ConfirmValidateStockTransfer=Are you sure you want to validate this stocks transfer with reference %s ? +ConfirmDestock=Decrease of stocks with transfer %s +ConfirmDestockCancel=Cancel decrease of stocks with transfer %s +DestockAllProduct=Decrease of stocks +DestockAllProductCancel=Cancel decrease of stocks +ConfirmAddStock=Increase stocks with transfer %s +ConfirmAddStockCancel=Cancel increase of stocks with transfer %s +AddStockAllProduct=Increase of stocks +AddStockAllProductCancel=Cancel increase of stocks +DatePrevueDepart=Intended date of departure +DateReelleDepart=Real date of departure +DatePrevueArrivee=Intended date of arrival +DateReelleArrivee=Real date of arrival +HelpWarehouseStockTransferSource=If this warehouse is set, only itself and its children will be available as source warehouse +HelpWarehouseStockTransferDestination=If this warehouse is set, only itself and its children will be available as destination warehouse +LeadTimeForWarning=Lead time before alert (in days) +TypeContact_stocktransfer_internal_STFROM=Sender of stocks transfer +TypeContact_stocktransfer_internal_STDEST=Recipient of stocks transfer +TypeContact_stocktransfer_internal_STRESP=Responsible of stocks transfer +StockTransferSheet=Stocks transfer sheet +StockTransferSheetProforma=Proforma stocks transfer sheet +StockTransferDecrementation=Decrease source warehouses +StockTransferIncrementation=Increase destination warehouses +StockTransferDecrementationCancel=Cancel decrease of source warehouses +StockTransferIncrementationCancel=Cancel increase of destination warehouses +StockStransferDecremented=Source warehouses decreased +StockStransferDecrementedCancel=Decrease of source warehouses canceled +StockStransferIncremented=Closed - Stocks transfered +StockStransferIncrementedShort=Stocks transfered +StockStransferIncrementedShortCancel=Increase of destination warehouses canceled +StockTransferNoBatchForProduct=Product %s doesn't use batch, clear batch on line and retry +StockTransferSetup = Stocks Transfer module configuration +Settings=Settings +StockTransferSetupPage = Configuration page for stocks transfer module +StockTransferRightRead=Read stocks transfers +StockTransferRightCreateUpdate=Create/Update stocks transfers +StockTransferRightDelete=Delete stocks transfers +BatchNotFound=Lot / serial not found for this product diff --git a/htdocs/langs/fr_FR/stocks.lang b/htdocs/langs/fr_FR/stocks.lang index 8eb7b4dc9a8..65a7495880e 100644 --- a/htdocs/langs/fr_FR/stocks.lang +++ b/htdocs/langs/fr_FR/stocks.lang @@ -271,4 +271,45 @@ ErrorCantFindCodeInInventory=Impossible de trouver le code suivant dans l'invent QtyWasAddedToTheScannedBarcode=Succès !! La quantité a été ajoutée à tous les codes-barres demandés. Vous pouvez fermer l'outil Scanner. StockChangeDisabled=Changement sur stock désactivé NoWarehouseDefinedForTerminal=Aucun entrepôt défini pour le terminal +ModuleStockTransferName = Transferts de stocks +ModuleStockTransferDesc = Création d'objets transfert de stocks, avec génération de bons de transfert +StockTransferNew=Nouveau transfert de stocks +StockTransferList=Liste des transferts de stocks +ConfirmValidateStockTransfer=Êtes-vous sûr de vouloir valider ce transfert de stocks sous la référence %s ? +ConfirmDestock=Décrémentation des stocks via transfert %s +ConfirmDestockCancel=Annulation décrémentation des stocks via transfert %s +DestockAllProduct=Décrémentation des stocks +DestockAllProductCancel=Annulation décrémentation des stocks +ConfirmAddStock=Incrémentation des stocks via transfert %s +ConfirmAddStockCancel=Annulation incrémentation des stocks via transfert %s +AddStockAllProduct=Incrémentation des stocks +AddStockAllProductCancel=Annulation incrémentation des stocks +DatePrevueDepart=Date prévue de départ +DateReelleDepart=Date réelle de départ +DatePrevueArrivee=Date prévue d'arrivée +DateReelleArrivee=Date réelle d'arrivée +HelpWarehouseStockTransferSource=Si renseigné, seul cet entrepôt source et ses enfants seront sélectionnables pour l'ajout des lignes +HelpWarehouseStockTransferDestination=Si renseigné, seul cet entrepôt de destination et ses enfants seront sélectionnables pour l'ajout des lignes +LeadTimeForWarning=Délai pour alerte (en jours) +TypeContact_stocktransfer_internal_STFROM=Contact expéditeur transfert de stocks +TypeContact_stocktransfer_internal_STDEST=Contact destinataire transfert de stocks +TypeContact_stocktransfer_internal_STRESP=Responsable du transfert de stocks +StockTransferSheet=Bon de transfert +StockTransferSheetProforma=Bon de transfert proforma +StockTransferDecrementation=Décrémenter les entrepôts sources +StockTransferIncrementation=Incrémenter les entrepôts de destination +StockTransferDecrementationCancel=Annuler décrémentation des entrepôts sources +StockTransferIncrementationCancel=Annuler incrémentation des entrepôts de destination +StockStransferDecremented=Entrepôts sources décrémentés +StockStransferDecrementedCancel=Décrémentation entrepôts source annulée +StockStransferIncremented=Clôturé - Stocks transférés +StockStransferIncrementedShort=Stocks transférés +StockStransferIncrementedShortCancel=Incrémentation entrepôts de destination annulée +StockTransferNoBatchForProduct=Le produit %s ne gère pas les numéros de lot, retirez le lot sur la ligne avant d'exécuter à nouveau cette action +StockTransferSetup = Configuration du module transferts de stocks +StockTransferSetupPage = Page de configuration du module transferts de stocks +StockTransferRightRead=Lire les transferts de stocks +StockTransferRightCreateUpdate=Créer/Mettre à jour les transferts de stocks +StockTransferRightDelete=Supprimer les transferts de stocks +BatchNotFound=Lot / série non trouvé(e) pour ce produit ClearQtys=Effacer toutes les quantités diff --git a/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php b/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php index b50f4acf741..290048785fd 100644 --- a/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php +++ b/htdocs/modulebuilder/template/core/modules/mailings/mailinglist_mymodule_myobject.modules.php @@ -24,7 +24,8 @@ class mailing_mailinglist_mymodule_myobject extends MailingTargets // CHANGE THIS: Set to 1 if selector is available for admin users only public $require_admin = 0; - public $enabled = 0; + public $enabled = '$conf->mymodule->enabled'; + public $require_module = array(); /** diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php index c03302551e3..595dd077b0e 100644 --- a/htdocs/modulebuilder/template/myobject_list.php +++ b/htdocs/modulebuilder/template/myobject_list.php @@ -477,7 +477,7 @@ $arrayofmassactions = array( //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"), //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"), ); -if ($permissiontodelete) { +if (!empty($permissiontodelete)) { $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); } if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { @@ -500,8 +500,8 @@ print ''; $newcardbutton = ''; -$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); $newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); $newcardbutton .= dolGetButtonTitleSeparator(); $newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/mymodule/myobject_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); @@ -674,6 +674,7 @@ if (isset($extrafields->attributes[$object->table_element]['computed']) && is_ar // -------------------------------------------------------------------- $i = 0; $savnbfield = $totalarray['nbfield']; +$totalarray = array(); $totalarray['nbfield'] = 0; $imaxinloop = ($limit ? min($num, $limit) : $num); while ($i < $imaxinloop) { diff --git a/htdocs/mrp/tpl/originproductline.tpl.php b/htdocs/mrp/tpl/originproductline.tpl.php index d65f625048b..e641bd142fc 100644 --- a/htdocs/mrp/tpl/originproductline.tpl.php +++ b/htdocs/mrp/tpl/originproductline.tpl.php @@ -24,7 +24,7 @@ if (empty($conf) || !is_object($conf)) { global $db; -if (!is_object($form)) { +if (!empty($form) && !is_object($form)) { $form = new Form($db); } diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 7df8e437272..9358eb9c60d 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -4896,14 +4896,14 @@ class Product extends CommonObject } if (!empty($conf->accounting->enabled)) { - if ($this->status) { + if ($this->status && isset($this->accountancy_code_sell)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; $label .= '
    '; $label .= '
    '.$langs->trans('ProductAccountancySellCode').': '.length_accountg($this->accountancy_code_sell); $label .= '
    '.$langs->trans('ProductAccountancySellIntraCode').': '.length_accountg($this->accountancy_code_sell_intra); $label .= '
    '.$langs->trans('ProductAccountancySellExportCode').': '.length_accountg($this->accountancy_code_sell_export); } - if ($this->status_buy) { + if ($this->status_buy && isset($this->accountancy_code_buy)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; if (empty($this->status)) { $label .= '
    '; diff --git a/htdocs/product/composition/card.php b/htdocs/product/composition/card.php index ec96bba20d6..69c872c51a4 100644 --- a/htdocs/product/composition/card.php +++ b/htdocs/product/composition/card.php @@ -28,7 +28,7 @@ */ require '../../main.inc.php'; - +require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; @@ -144,9 +144,10 @@ if ($action == 'add_prod' && ($user->rights->produit->creer || $user->rights->se * View */ +$form = new Form($db); +$formproduct = new FormProduct($db); $product_fourn = new ProductFournisseur($db); $productstatic = new Product($db); -$form = new Form($db); // action recherche des produits par mot-cle et/ou par categorie if ($action == 'search') { @@ -201,8 +202,10 @@ if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { llxHeader('', $title, $help_url); $head = product_prepare_head($object); + $titre = $langs->trans("CardProduct".$object->type); $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product'); + print dol_get_fiche_head($head, 'subproduct', $titre, -1, $picto); @@ -218,10 +221,11 @@ if ($id > 0 || !empty($ref)) { $shownav = 0; } - dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', '', '', '', 0, '', '', 0); + dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref', ''); if ($object->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES) || empty($conf->global->PRODUIT_MULTIPRICES)) { print '
    '; + print '
    '; print '
    '; print ''; @@ -229,23 +233,33 @@ if ($id > 0 || !empty($ref)) { // Type if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) { $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service"); - print ''; } + print '
    '; + print '
    '; print (empty($conf->global->PRODUCT_DENY_CHANGE_PRODUCT_TYPE)) ? $form->editfieldkey("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat) : $langs->trans('Type'); print ''; print $form->editfieldval("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat); print '
    '; + + print '
    '; + print '
    '; + + print ''; + // Nature if ($object->type != Product::TYPE_SERVICE) { - print ''; + if (empty($conf->global->PRODUCT_DISABLE_NATURE)) { + print ''; + } } if (empty($conf->global->PRODUIT_MULTIPRICES)) { // Price - print '
    '.$langs->trans("Nature").''; - print $object->getLibFinished(); - print '
    '.$form->textwithpicto($langs->trans("NatureOfProductShort"), $langs->trans("NatureOfProductDesc")).''; + print $object->getLibFinished(); + //print $formproduct->selectProductNature('finished', $object->finished); + print '
    '.$langs->trans("SellingPrice").''; + print '
    '.$langs->trans("SellingPrice").''; if ($object->price_base_type == 'TTC') { print price($object->price_ttc).' '.$langs->trans($object->price_base_type); } else { @@ -265,16 +279,13 @@ if ($id > 0 || !empty($ref)) { print '
    '; print '
    '; + print '
    '; } print dol_get_fiche_end(); - print '
    '; - print '
    '; - print '
    '; - - print '
    '; + print '

    '; $prodsfather = $object->getFather(); // Parent Products $object->get_sousproduits_arbo(); // Load $object->sousprods @@ -552,7 +563,7 @@ if ($id > 0 || !empty($ref)) { print ''."\n"; } else { - $colspan = 8; + $colspan = 10; if (!empty($conf->stock->enabled)) { $colspan++; } diff --git a/htdocs/product/popuprop.php b/htdocs/product/popuprop.php index b8118ba4884..b921f16d02e 100644 --- a/htdocs/product/popuprop.php +++ b/htdocs/product/popuprop.php @@ -68,6 +68,7 @@ restrictedArea($user, 'produit|service', 0, 'product&product', '', ''); */ $form = new Form($db); +$tmpproduct = new Product($db); $helpurl = ''; if ($type == '0') { @@ -124,7 +125,7 @@ $infoprod = array(); // Add lines for object -$sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type as type, SUM(pd.qty) as c"; +$sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type as type, p.tobuy, p.tosell, p.tobatch, p.barcode, SUM(pd.qty) as c"; $textforqty = 'Qty'; if ($mode == 'facture') { $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as pd"; @@ -141,7 +142,7 @@ $sql .= " AND p.rowid = pd.fk_product"; if ($type !== '') { $sql .= " AND fk_product_type = ".((int) $type); } -$sql .= " GROUP BY p.rowid, p.label, p.ref, p.fk_product_type"; +$sql .= " GROUP BY p.rowid, p.label, p.ref, p.fk_product_type, p.tobuy, p.tosell, p.tobatch, p.barcode"; $num = 0; $totalnboflines = 0; @@ -163,7 +164,7 @@ if (!empty($mode) && $mode != '-1') { while ($i < $num) { $objp = $db->fetch_object($resql); - $infoprod[$objp->rowid] = array('type'=>$objp->type, 'ref'=>$objp->ref, 'label'=>$objp->label); + $infoprod[$objp->rowid] = array('type'=>$objp->type, 'ref'=>$objp->ref, 'label'=>$objp->label, 'tobuy'=>$objp->tobuy, 'tosell'=>$objp->tobuy, 'tobatch'=>$objp->tobatch, 'barcode'=>$objp->barcode); $infoprod[$objp->rowid]['nbline'] = $objp->c; $i++; @@ -181,7 +182,7 @@ $arrayofmode = array( 'commande' => 'Orders', 'facture' => 'Facture' ); -$title .= ' '.$form->selectarray('mode', $arrayofmode, $mode, 1); +$title .= ' '.$form->selectarray('mode', $arrayofmode, $mode, 1, 0, 0, '', 1); $title .= ' '; @@ -228,23 +229,28 @@ if ($mode && $mode != '-1') { } } + $tmpproduct->ref = $vals['ref']; + $tmpproduct->label = $vals['label']; + $tmpproduct->type = $vals['type']; + $tmpproduct->status = $vals['tosell']; + $tmpproduct->status_buy = $vals['tobuy']; + $tmpproduct->status_batch = $vals['tobatch']; + $tmpproduct->barcode = $vals['barcode']; + print ""; - print ''; - if ($vals['type'] == 1) { - print img_object($langs->trans("ShowService"), "service"); - } else { - print img_object($langs->trans("ShowProduct"), "product"); - } - print " "; - print $vals['ref'].''; print ''; - if ($vals['type'] == 1) { - print $langs->trans("Service"); - } else { - print $langs->trans("Product"); - } + print $tmpproduct->getNomUrl(1); print ''; - print ''.$vals['label'].''; + print ''; + $s = ''; + if ($vals['type'] == 1) { + $s .= img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"'); + } else { + $s .= img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"'); + } + print $s; + print ''; + print ''.dol_escape_htmltag($vals['label']).''; print ''.$vals['nbline'].''; print "\n"; $i++; diff --git a/htdocs/product/reassortlot.php b/htdocs/product/reassortlot.php index c5463e3e4e2..690d3f3f261 100644 --- a/htdocs/product/reassortlot.php +++ b/htdocs/product/reassortlot.php @@ -33,11 +33,18 @@ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; // Load translation files required by the page $langs->loadLangs(array('products', 'stocks', 'productbatch')); -$action = GETPOST('action', 'aZ09'); +$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) +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectlist'; // 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') +$mode = GETPOST('mode', 'aZ'); + $sref = GETPOST("sref", 'alpha'); $snom = GETPOST("snom", 'alpha'); $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); @@ -52,25 +59,21 @@ $fourn_id = GETPOST("fourn_id", 'int'); $sbarcode = GETPOST("sbarcode", 'int'); $search_stock_physique = GETPOST('search_stock_physique', 'alpha'); +// 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) { +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; } -if (!$sortfield) { - $sortfield = "p.ref"; -} -if (!$sortorder) { - $sortorder = "ASC"; -} -$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -if (empty($page) || $page == -1) { - $page = 0; -} // If $page is not defined, or '' or -1 $offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; -// Load sale and categ filters +// Initialize array of search criterias +$object = new Product($db); $search_sale = GETPOST("search_sale"); if (GETPOSTISSET('catid')) { $search_categ = GETPOST('catid', 'int'); @@ -78,6 +81,40 @@ if (GETPOSTISSET('catid')) { $search_categ = GETPOST('search_categ', 'int'); } +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); +//$extrafields->fetch_name_optionals_label($object->table_element_line); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) { + reset($object->fields); // Reset is required to avoid key() to return null. + $sortfield = "p.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} + + +// Initialize array of search criterias +$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')); + } +} +$key = 'sellby'; +$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')); +$key = 'eatby'; +$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')); + // Get object canvas (By default, this is not defined, so standard usage of dolibarr) $canvas = GETPOST("canvas"); $objcanvas = null; @@ -98,21 +135,66 @@ $result = restrictedArea($user, 'produit|service', 0, 'product&product'); * Actions */ -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 - $sref = ""; - $snom = ""; - $sall = ""; - $tosell = ""; - $tobuy = ""; - $search_sale = ""; - $search_categ = ""; - $toolowstock = ''; - $search_batch = ''; - $search_warehouse = ''; - $fourn_id = ''; - $sbarcode = ''; - $search_stock_physique = ''; +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; } +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} + +$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'); +} + +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['sellby_dtstart'] = ''; + $search['eatby_dtstart'] = ''; + $search['sellby_dtend'] = ''; + $search['eatby_dtend'] = ''; + $sref = ""; + $snom = ""; + $sall = ""; + $tosell = ""; + $tobuy = ""; + $search_sale = ""; + $search_categ = ""; + $toolowstock = ''; + $search_batch = ''; + $search_warehouse = ''; + $fourn_id = ''; + $sbarcode = ''; + $search_stock_physique = ''; + $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 + } + + // Mass actions + /*$objectclass = 'MyObject'; + $objectlabel = 'MyObject'; + $uploaddir = $conf->mymodule->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + */ +} + /* @@ -122,8 +204,12 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $form = new Form($db); $htmlother = new FormOther($db); +$now = dol_now(); + $helpurl = 'EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks'; $title = $langs->trans("ProductsAndServices"); +$morejs = array(); +$morecss = array(); $sql = 'SELECT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; $sql .= ' p.fk_product_type, p.tms as datem,'; @@ -193,6 +279,37 @@ if ($search_warehouse) { if ($search_batch) { $sql .= natural_search("pb.batch", $search_batch); } + +foreach ($search as $key => $val) { + if (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.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search)); + } + } else { + if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') { + $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key); + if ($columnName == 'eatby' || $columnName == 'sellby') { + if (preg_match('/_dtstart$/', $key)) { + $sql .= " AND pl.".$db->escape($columnName)." >= '".$db->idate($search[$key])."'"; + } + if (preg_match('/_dtend$/', $key)) { + $sql .= " AND pl.".$db->escape($columnName)." <= '".$db->idate($search[$key])."'"; + } + } + } + } +} + $sql .= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,"; $sql .= " p.fk_product_type, p.tms,"; $sql .= " p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock, p.stock, p.tosell, p.tobuy, p.tobatch,"; @@ -217,317 +334,386 @@ if ($search_stock_physique != '') { if (!empty($sql_having)) { $sql .= $sql_having; } -$sql .= $db->order($sortfield, $sortorder); +//print $sql; + +// Count total nb of records $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 + $resql = $db->query($sql); + $nbtotalofrecords = $db->num_rows($resql); + + 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); } -$sql .= $db->plimit($limit + 1, $offset); +// 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) { - $num = $db->num_rows($resql); +if (!$resql) { + dol_print_error($db); + exit; +} - $i = 0; +$num = $db->num_rows($resql); - if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall or $snom or $sref)) { - $objp = $db->fetch_object($resql); - header("Location: card.php?id=$objp->rowid"); - exit; - } +$i = 0; - if (isset($type)) { - if ($type == 1) { - $texte = $langs->trans("Services"); - } else { - $texte = $langs->trans("Products"); - } +if ($num == 1 && GETPOST('autojumpifoneonly') && ($sall or $snom or $sref)) { + $objp = $db->fetch_object($resql); + header("Location: card.php?id=$objp->rowid"); + exit; +} + +if (isset($type)) { + if ($type == 1) { + $texte = $langs->trans("Services"); } else { - $texte = $langs->trans("ProductsAndServices"); + $texte = $langs->trans("Products"); } - $texte .= ' ('.$langs->trans("StocksByLotSerial").')'; +} else { + $texte = $langs->trans("ProductsAndServices"); +} +$texte .= ' ('.$langs->trans("StocksByLotSerial").')'; - $param = ''; - if ($limit > 0 && $limit != $conf->liste_limit) { - $param .= '&limit='.urlencode($limit); +$param = ''; +if (!empty($mode)) { + $param .= '&mode='.urlencode($mode); +} +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 ($sall) { - $param .= "&sall=".urlencode($sall); - } - if ($tosell) { - $param .= "&tosell=".urlencode($tosell); - } - if ($tobuy) { - $param .= "&tobuy=".urlencode($tobuy); - } - if ($type != '') { - $param .= "&type=".urlencode($type); - } - if ($fourn_id) { - $param .= "&fourn_id=".urlencode($fourn_id); - } - if ($snom) { - $param .= "&snom=".urlencode($snom); - } - if ($sref) { - $param .= "&sref=".urlencode($sref); - } - if ($search_batch) { - $param .= "&search_batch=".urlencode($search_batch); - } - if ($sbarcode) { - $param .= "&sbarcode=".urlencode($sbarcode); - } - if ($search_warehouse) { - $param .= "&search_warehouse=".urlencode($search_warehouse); - } - if ($toolowstock) { - $param .= "&toolowstock=".urlencode($toolowstock); - } - if ($search_sale) { - $param .= "&search_sale=".urlencode($search_sale); - } - if (!empty($search_categ) && $search_categ != '-1') { - $param .= "&search_categ=".urlencode($search_categ); - } - if ($search_stock_physique) { - $param .= '&search_stock_physique=' . urlencode($search_stock_physique); - } - /*if ($eatby) $param.="&eatby=".$eatby; - if ($sellby) $param.="&sellby=".$sellby;*/ +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if ($sall) { + $param .= "&sall=".urlencode($sall); +} +if ($tosell) { + $param .= "&tosell=".urlencode($tosell); +} +if ($tobuy) { + $param .= "&tobuy=".urlencode($tobuy); +} +if ($type != '') { + $param .= "&type=".urlencode($type); +} +if ($fourn_id) { + $param .= "&fourn_id=".urlencode($fourn_id); +} +if ($snom) { + $param .= "&snom=".urlencode($snom); +} +if ($sref) { + $param .= "&sref=".urlencode($sref); +} +if ($search_batch) { + $param .= "&search_batch=".urlencode($search_batch); +} +if ($sbarcode) { + $param .= "&sbarcode=".urlencode($sbarcode); +} +if ($search_warehouse) { + $param .= "&search_warehouse=".urlencode($search_warehouse); +} +if ($toolowstock) { + $param .= "&toolowstock=".urlencode($toolowstock); +} +if ($search_sale) { + $param .= "&search_sale=".urlencode($search_sale); +} +if (!empty($search_categ) && $search_categ != '-1') { + $param .= "&search_categ=".urlencode($search_categ); +} +if ($search_stock_physique) { + $param .= '&search_stock_physique=' . urlencode($search_stock_physique); +} +/*if ($eatby) $param.="&eatby=".$eatby; +if ($sellby) $param.="&sellby=".$sellby;*/ - llxHeader("", $title, $helpurl, $texte); +llxHeader("", $title, $helpurl, $texte); - print '
    '; - print ''; - print ''; - print ''; - print ''; +print ''."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; - print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit, 0, 0, 1); +print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'product', 0, '', '', $limit, 0, 0, 1); - if ($search_categ > 0) { - print "
    "; - $c = new Categorie($db); - $c->fetch($search_categ); - $ways = $c->print_all_ways(' > ', 'product/reassortlot.php'); - print " > ".$ways[0]."
    \n"; - print "

    "; - } +if ($search_categ > 0) { + print "
    "; + $c = new Categorie($db); + $c->fetch($search_categ); + $ways = $c->print_all_ways(' > ', 'product/reassortlot.php'); + print " > ".$ways[0]."
    \n"; + print "

    "; +} - // Filter on categories - $moreforfilter = ''; - if (!empty($conf->categorie->enabled)) { - $moreforfilter .= '
    '; - $moreforfilter .= img_picto($langs->trans('Categories'), 'category', 'class="pictofixedwidth"'); - $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1); - $moreforfilter .= '
    '; - } - //$moreforfilter.=$langs->trans("StockTooLow").' '; +// Filter on categories +$moreforfilter = ''; +if (!empty($conf->categorie->enabled)) { + $moreforfilter .= '
    '; + $moreforfilter .= img_picto($langs->trans('Categories'), 'category', 'class="pictofixedwidth"'); + $moreforfilter .= $htmlother->select_categories(Categorie::TYPE_PRODUCT, $search_categ, 'search_categ', 1); + $moreforfilter .= '
    '; +} +//$moreforfilter.=$langs->trans("StockTooLow").' '; - if (!empty($moreforfilter)) { - print '
    '; - print $moreforfilter; - $parameters = array(); - $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '
    '; - } +if (!empty($moreforfilter)) { + print '
    '; + print $moreforfilter; + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '
    '; +} - print '
    '; - print ''; +print '
    '; +print '
    '; - // Fields title search - print ''; +// Fields title search +// -------------------------------------------------------------------- +print ''; +print ''; +print ''; +if (!empty($conf->service->enabled) && $type == 1) { print ''; - print ''; +print ''; +if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print ''; - if (!empty($conf->service->enabled) && $type == 1) { - print ''; - } - print ''; - print ''; - if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { - print ''; - } - if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { - print ''; - } - // Physical stock - print ''; - print ''; - print ''; - print ''; +} +// Physical stock +print ''; +print ''; +print ''; +print ''; +// Action column +if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { print ''; - print ''; - - //Line for column titles - print ""; - print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", '', $param, "", $sortfield, $sortorder); - print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", '', $param, "", $sortfield, $sortorder); - if (!empty($conf->service->enabled) && $type == 1) { - print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", '', $param, "", $sortfield, $sortorder, 'center '); - } - print_liste_field_titre("Warehouse", $_SERVER["PHP_SELF"], "e.ref", '', $param, "", $sortfield, $sortorder); - //print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'',$sortfield,$sortorder, 'right ); - print_liste_field_titre("Batch", $_SERVER["PHP_SELF"], "pb.batch", '', $param, "", $sortfield, $sortorder, 'center '); - if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { - print_liste_field_titre("SellByDate", $_SERVER["PHP_SELF"], "pb.sellby", '', $param, "", $sortfield, $sortorder, 'center '); - } - if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { - print_liste_field_titre("EatByDate", $_SERVER["PHP_SELF"], "pb.eatby", '', $param, "", $sortfield, $sortorder, 'center '); - } - print_liste_field_titre("PhysicalStock", $_SERVER["PHP_SELF"], "stock_physique", '', $param, "", $sortfield, $sortorder, 'right '); - // TODO Add info of running suppliers/customers orders - //print_liste_field_titre("TheoreticalStock",$_SERVER["PHP_SELF"], "stock_theorique",$param,"",'',$sortfield,$sortorder, 'right '); - print_liste_field_titre(''); - print_liste_field_titre("ProductStatusOnSell", $_SERVER["PHP_SELF"], "p.tosell", "", $param, '', $sortfield, $sortorder, 'right '); - print_liste_field_titre("ProductStatusOnBuy", $_SERVER["PHP_SELF"], "p.tobuy", "", $param, '', $sortfield, $sortorder, 'right '); - print_liste_field_titre(''); - print "\n"; - - $product_static = new Product($db); - $product_lot_static = new Productlot($db); - $warehousetmp = new Entrepot($db); - - while ($i < min($num, $limit)) { - $objp = $db->fetch_object($resql); - - // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active - $sql = "SELECT label"; - $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; - $sql .= " WHERE fk_product = ".((int) $objp->rowid); - $sql .= " AND lang = '".$db->escape($langs->getDefaultLang())."'"; - $sql .= " LIMIT 1"; - - $result = $db->query($sql); - if ($result) { - $objtp = $db->fetch_object($result); - if (!empty($objtp->label)) { - $objp->label = $objtp->label; - } - } - } - - $product_static->ref = $objp->ref; - $product_static->id = $objp->rowid; - $product_static->label = $objp->label; - $product_static->type = $objp->fk_product_type; - $product_static->entity = $objp->entity; - $product_static->status = $objp->tosell; - $product_static->status_buy = $objp->tobuy; - $product_static->status_batch = $objp->tobatch; - - $product_lot_static->batch = $objp->batch; - $product_lot_static->product_id = $objp->rowid; - $product_lot_static->id = $objp->lotid; - $product_lot_static->eatby = $objp->eatby; - $product_lot_static->sellby = $objp->sellby; - - - $warehousetmp->id = $objp->fk_entrepot; - $warehousetmp->ref = $objp->warehouse_ref; - $warehousetmp->label = $objp->warehouse_ref; - $warehousetmp->fk_parent = $objp->warehouse_parent; - - print ''; - - // Ref - print ''; - - // Label - print ''; - - if (!empty($conf->service->enabled) && $type == 1) { - print ''; - } - //print ''; - //print ''; - //print ''; - - // Warehouse - print ''; - - // Lot - print ''; - - if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { - print ''; - } - - if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { - print ''; - } - - print ''; - - print ''; - - print ''; - - print ''; - - print ''; - - print "\n"; - $i++; - } - - print "
    '; +print ''; +print ''; +print ''; +print ''; - print ''; + print ' '; print ''; - print ''; +} +print ''; + $key = 'sellby'; + 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 '
    '; print '
    '; - print ' '; - print '  '; - print ''; +} +if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print ''; + $key = 'eatby'; + 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 '
    '; print '
       '; +print ''; +print '   '; - $searchpicto = $form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
    '; - print $product_static->getNomUrl(1, '', 16); - //if ($objp->stock_theorique < $objp->seuil_stock_alerte) print ' '.img_warning($langs->trans("StockTooLow")); - print ''.$objp->label.''; - if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) { - print $regs[1].' '.$langs->trans("DurationYear"); - } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) { - print $regs[1].' '.$langs->trans("DurationMonth"); - } elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) { - print $regs[1].' '.$langs->trans("DurationDay"); - } else { - print $objp->duration; - } - print ''.$objp->stock_theorique.''.$objp->seuil_stock_alerte.''.$objp->desiredstock.''; - if ($objp->fk_entrepot > 0) { - print $warehousetmp->getNomUrl(1); - } - print ''; - if ($product_lot_static->batch) { - print $product_lot_static->getNomUrl(1); - } - print ''.dol_print_date($db->jdate($objp->sellby), 'day').''.dol_print_date($db->jdate($objp->eatby), 'day').''; - //if ($objp->seuil_stock_alerte && ($objp->stock_physique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; - print $objp->stock_physique; - print ''; - print img_picto($langs->trans("StockMovement"), 'movement', 'class="pictofixedwidth"'); - print ''.$langs->trans("Movements").''; - print ''.$product_static->LibStatut($objp->statut, 5, 0).''.$product_static->LibStatut($objp->tobuy, 5, 1).'
    "; - print '
    '; - print '
    '; - - $db->free($resql); -} else { - dol_print_error($db); } +print ''."\n"; + +$totalarray = array(); +$totalarray['nbfield'] = 0; + +// Fields title label +// -------------------------------------------------------------------- +print ''; +print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", '', $param, "", $sortfield, $sortorder); +print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", '', $param, "", $sortfield, $sortorder); +if (!empty($conf->service->enabled) && $type == 1) { + print_liste_field_titre("Duration", $_SERVER["PHP_SELF"], "p.duration", '', $param, "", $sortfield, $sortorder, 'center '); +} +print_liste_field_titre("Warehouse", $_SERVER["PHP_SELF"], "e.ref", '', $param, "", $sortfield, $sortorder); +//print_liste_field_titre("DesiredStock", $_SERVER["PHP_SELF"], "p.desiredstock",$param,"",'',$sortfield,$sortorder, 'right ); +print_liste_field_titre("Batch", $_SERVER["PHP_SELF"], "pb.batch", '', $param, "", $sortfield, $sortorder, 'center '); +if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print_liste_field_titre("SellByDate", $_SERVER["PHP_SELF"], "pl.sellby", '', $param, "", $sortfield, $sortorder, 'center '); +} +if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print_liste_field_titre("EatByDate", $_SERVER["PHP_SELF"], "pl.eatby", '', $param, "", $sortfield, $sortorder, 'center '); +} +print_liste_field_titre("PhysicalStock", $_SERVER["PHP_SELF"], "stock_physique", '', $param, "", $sortfield, $sortorder, 'right '); +// TODO Add info of running suppliers/customers orders +//print_liste_field_titre("TheoreticalStock",$_SERVER["PHP_SELF"], "stock_theorique",$param,"",'',$sortfield,$sortorder, 'right '); +print_liste_field_titre(''); +print_liste_field_titre("ProductStatusOnSell", $_SERVER["PHP_SELF"], "p.tosell", "", $param, '', $sortfield, $sortorder, 'right '); +print_liste_field_titre("ProductStatusOnBuy", $_SERVER["PHP_SELF"], "p.tobuy", "", $param, '', $sortfield, $sortorder, 'right '); +print_liste_field_titre(''); +print "\n"; + +$product_static = new Product($db); +$product_lot_static = new Productlot($db); +$warehousetmp = new Entrepot($db); + +// Loop on record +// -------------------------------------------------------------------- +$i = 0; +$savnbfield = $totalarray['nbfield']; +$totalarray['nbfield'] = 0; +$imaxinloop = ($limit ? min($num, $limit) : $num); +while ($i < $imaxinloop) { + $objp = $db->fetch_object($resql); + + // Multilangs + if (!empty($conf->global->MAIN_MULTILANGS)) { // si l'option est active + // TODO Use a cache + $sql = "SELECT label"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql .= " WHERE fk_product = ".((int) $objp->rowid); + $sql .= " AND lang = '".$db->escape($langs->getDefaultLang())."'"; + $sql .= " LIMIT 1"; + + $result = $db->query($sql); + if ($result) { + $objtp = $db->fetch_object($result); + if (!empty($objtp->label)) { + $objp->label = $objtp->label; + } + } + } + + $product_static->ref = $objp->ref; + $product_static->id = $objp->rowid; + $product_static->label = $objp->label; + $product_static->type = $objp->fk_product_type; + $product_static->entity = $objp->entity; + $product_static->status = $objp->tosell; + $product_static->status_buy = $objp->tobuy; + $product_static->status_batch = $objp->tobatch; + + $product_lot_static->batch = $objp->batch; + $product_lot_static->product_id = $objp->rowid; + $product_lot_static->id = $objp->lotid; + $product_lot_static->eatby = $objp->eatby; + $product_lot_static->sellby = $objp->sellby; + + + $warehousetmp->id = $objp->fk_entrepot; + $warehousetmp->ref = $objp->warehouse_ref; + $warehousetmp->label = $objp->warehouse_ref; + $warehousetmp->fk_parent = $objp->warehouse_parent; + + print ''; + + // Ref + print ''; + print $product_static->getNomUrl(1, '', 16); + //if ($objp->stock_theorique < $objp->seuil_stock_alerte) print ' '.img_warning($langs->trans("StockTooLow")); + print ''; + + // Label + print ''.$objp->label.''; + + if (!empty($conf->service->enabled) && $type == 1) { + print ''; + if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationYear"); + } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationMonth"); + } elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) { + print $regs[1].' '.$langs->trans("DurationDay"); + } else { + print $objp->duration; + } + print ''; + } + //print ''.$objp->stock_theorique.''; + //print ''.$objp->seuil_stock_alerte.''; + //print ''.$objp->desiredstock.''; + + // Warehouse + print ''; + if ($objp->fk_entrepot > 0) { + print $warehousetmp->getNomUrl(1); + } + print ''; + + // Lot + print ''; + if ($product_lot_static->batch) { + print $product_lot_static->getNomUrl(1); + } + print ''; + + if (empty($conf->global->PRODUCT_DISABLE_SELLBY)) { + print ''.dol_print_date($db->jdate($objp->sellby), 'day').''; + } + + if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { + print ''.dol_print_date($db->jdate($objp->eatby), 'day').''; + } + + print ''; + //if ($objp->seuil_stock_alerte && ($objp->stock_physique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; + print $objp->stock_physique; + print ''; + + print ''; + print img_picto($langs->trans("StockMovement"), 'movement', 'class="pictofixedwidth"'); + print ''.$langs->trans("Movements").''; + print ''; + + print ''.$product_static->LibStatut($objp->statut, 5, 0).''; + + print ''.$product_static->LibStatut($objp->tobuy, 5, 1).''; + + print ''; + + print "\n"; + $i++; +} + +$db->free($resql); + +print ''."\n"; +print '
    '."\n"; + +print ''."\n"; + // End of page llxFooter(); diff --git a/htdocs/product/stats/bom.php b/htdocs/product/stats/bom.php index 1937b99b871..a8e76a178bf 100644 --- a/htdocs/product/stats/bom.php +++ b/htdocs/product/stats/bom.php @@ -199,7 +199,7 @@ if ($id > 0 || !empty($ref)) { $sql .= " INNER JOIN ".MAIN_DB_PREFIX."bom_bomline as bl ON bl.fk_bom=b.rowid"; $sql .= " WHERE b.entity IN (".getEntity('bom').")"; $sql .= " AND bl.fk_product = ".((int) $product->id); - $sql .= " GROUP BY b.rowid, b.ref, b.date_valid, b.status"; + $sql .= " GROUP BY b.rowid, b.ref, b.status, b.date_valid, b.fk_product"; $sql .= $db->order($sortfield, $sortorder); // Count total nb of records diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index 565b309b113..2743c4a5ea7 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -55,9 +55,10 @@ $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 == -1) { +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; -} // If $page is not defined, or '' or -1 +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -76,7 +77,7 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Default sort order (if not yet defined by previous GETPOST) if (!$sortfield) { - $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. + $sortfield = "t.fk_product,t.batch"; // Set here default search field. By default 1st field in definition. } if (!$sortorder) { $sortorder = "ASC"; @@ -89,6 +90,10 @@ 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')); + } } // List of fields to search into when doing a "search in all" @@ -104,12 +109,13 @@ $arrayfields = array(); foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field if (!empty($val['visible'])) { - $visible = dol_eval($val['visible'], 1, 1, '1'); + $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, 1, '1')), - 'position'=>$val['position'] + 'enabled'=>(abs($visible) != 3 && dol_eval($val['enabled'], 1)), + 'position'=>$val['position'], + 'help'=> isset($val['help']) ? $val['help'] : '' ); } } @@ -147,7 +153,8 @@ if (!$permissiontoread) accessforbidden(); */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; @@ -167,6 +174,10 @@ if (empty($reshook)) { 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'] = ''; + } } $toselect = array(); $search_array_options = array(); @@ -185,7 +196,7 @@ if (empty($reshook)) { /* - * VIEW + * View */ @@ -194,20 +205,19 @@ $form = new Form($db); $now = dol_now(); $help_url = 'EN:Module_Lot_/_Serial|FR:Module_Lot_/_Série'; - $title = $langs->trans('LotSerialList'); +$morejs = array(); +$morecss = array(); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) { - $sql .= "t.".$key.", "; -} +$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.', ' : ''); + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : ''); } } // Add fields from hooks @@ -216,9 +226,13 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if ( !empty($extrafields->attributes[$object->table_element]['label']) && ($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { +if (isset($extrafields->attributes[$object->table_element]['label']) && 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)"; } +// 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 { @@ -237,17 +251,17 @@ foreach ($search as $key => $val) { $mode_search = 2; } if ($search[$key] != '') { - $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + $sql .= natural_search("t.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search)); } } else { 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])."'"; + $sql .= " AND t.".$db->escape($columnName)." >= '".$db->idate($search[$key])."'"; } if (preg_match('/_dtend$/', $key)) { - $sql .= " AND t." . $columnName . " <= '" . $db->idate($search[$key]) . "'"; + $sql .= " AND t.".$db->escape($columnName)." <= '".$db->idate($search[$key])."'"; } } } @@ -265,21 +279,22 @@ $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $objec $sql .= $hookmanager->resPrint; /* If a group by is required - $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); // Note that $action and $object may have been modified by hook - $sql.=$hookmanager->resPrint; - $sql=preg_replace('/,\s*$/','', $sql); - */ +$sql.= " GROUP BY "; +foreach($object->fields as $key => $val) { + $sql .= "t.".$db->escape($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); +*/ // Count total nb of records $nbtotalofrecords = ''; @@ -290,14 +305,23 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { */ /* 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++; - }*/ + while ($db->fetch_object($resql)) { + if (empty($nbtotalofrecords)) { + $nbtotalofrecords = 1; // We can't make +1 because init value is '' + } else { + $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); + $sqlforcount = preg_replace('/^SELECT[a-zA-Z0-9\._\s\(\),=<>\:\-\']+\sFROM/', 'SELECT COUNT(*) as nbtotalofrecords FROM', $sql); $resql = $db->query($sqlforcount); - $objforcount = $db->fetch_object($resql); - $nbtotalofrecords = $objforcount->nbtotalofrecords; + if ($resql) { + $objforcount = $db->fetch_object($resql); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + } else { + dol_print_error($db); + } + if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0 $page = 0; $offset = 0; @@ -319,6 +343,7 @@ if (!$resql) { $num = $db->num_rows($resql); +$i = 0; // Direct jump if only one record found if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { @@ -332,11 +357,14 @@ if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $ // Output page // -------------------------------------------------------------------- -llxHeader('', $title, $help_url); +llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'bodyforlist'); $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; +if (!empty($mode)) { + $param .= '&mode='.urlencode($mode); +} if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { $param .= '&contextpage='.urlencode($contextpage); } @@ -346,9 +374,11 @@ if ($limit > 0 && $limit != $conf->liste_limit) { foreach ($search as $key => $val) { if (is_array($search[$key]) && count($search[$key])) { foreach ($search[$key] as $skey) { - $param .= '&search_'.$key.'[]='.urlencode($skey); + if ($skey != '') { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } } - } else { + } elseif ($search[$key] != '') { $param .= '&search_'.$key.'='.urlencode($search[$key]); } } @@ -357,6 +387,10 @@ if ($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( @@ -382,8 +416,9 @@ print ''; print ''; print ''; -//print ''; +print ''; print ''; +print ''; $newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/product/stock/productlot_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); @@ -397,12 +432,16 @@ $trackid = 'lot'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) { + $setupstring = ''; foreach ($fieldstosearchall as $key => $val) { $fieldstosearchall[$key] = $langs->trans($val); + $setupstring .= $key."=".$val.";"; } - print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; + print ''."\n"; + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '."\n"; } +// Filter on categories $moreforfilter = ''; /*$moreforfilter.='
    '; $moreforfilter.= $langs->trans('MyFilter') . ': '; @@ -419,21 +458,32 @@ if (empty($reshook)) { if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; print '
    '; } $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; -$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN', '')); // 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 '
    '; print ''."\n"; // Fields title search // -------------------------------------------------------------------- -print ''; +print ''; +// Action column +if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print ''; +} foreach ($object->fields as $key => $val) { + $searchkey = empty($search[$key]) ? '' : $search[$key]; $cssforfield = (empty($val['css']) ? '' : $val['css']); if ($key == 'status') { $cssforfield .= ($cssforfield ? ' ' : '').'center'; @@ -441,17 +491,28 @@ foreach ($object->fields as $key => $val) { $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') { + } 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 ''; } @@ -463,46 +524,61 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; +/*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; + }*/ // Action column -print ''; +if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print ''; +} print ''."\n"; +$totalarray = array(); +$totalarray['nbfield'] = 0; // Fields title label // -------------------------------------------------------------------- print ''; +if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +} foreach ($object->fields as $key => $val) { - $cssforfield = (empty($val['css']) ? '' : $val['css']); + $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') { + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { $cssforfield .= ($cssforfield ? ' ' : '').'right'; } + $cssforfield = preg_replace('/small\s*/', '', $cssforfield); // the 'small' css must not be used for the title label 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"; + $totalarray['nbfield']++; } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields -$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder, 'totalarray'=>&$totalarray); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column -print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +} +$totalarray['nbfield']++; print ''."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (!empty($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 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 @@ -514,9 +590,10 @@ if (!empty($extrafields->attributes[$object->table_element]['computed']) && is_a // Loop on record // -------------------------------------------------------------------- $i = 0; -$totalarray = array(); +$savnbfield = $totalarray['nbfield']; $totalarray['nbfield'] = 0; -while ($i < ($limit ? min($num, $limit) : $num)) { +$imaxinloop = ($limit ? min($num, $limit) : $num); +while ($i < $imaxinloop) { $obj = $db->fetch_object($resql); if (empty($obj)) { break; // Should not happen @@ -526,9 +603,22 @@ while ($i < ($limit ? min($num, $limit) : $num)) { $object->setVarsFromFetchObj($obj); // Show here line of result - print ''; + $j = 0; + print ''; + // Action column + if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print ''; + } foreach ($object->fields as $key => $val) { - $cssforfield = (empty($val['css']) ? '' : $val['css']); + $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') { @@ -541,17 +631,21 @@ while ($i < ($limit ? min($num, $limit) : $num)) { $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) { + 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 ''; + print ''; if ($key == 'status') { print $object->getLibStatut(5); } elseif ($key == 'rowid') { - print $object->id; + print $object->showOutputField($val, $key, $object->id, ''); } else { if ($key == 'batch') { print $object->getNomUrl(1); @@ -584,15 +678,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) { $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column - print ''; } - print ''; if (!$i) { $totalarray['nbfield']++; } @@ -613,14 +709,14 @@ if ($num == 0) { $colspan++; } } - print ''; + 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 +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; + $searchpicto = $form->showFilterButtons('left'); + print $searchpicto; + print ''; if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { - print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - } elseif (strpos($val['type'], 'integer:') === 0) { - print $object->showInputField($val, $key, !empty($search[$key])?$search[$key]:0, '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { - print ''; + 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_', $cssforfield.' maxwidth250', 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 '
    '; -$searchpicto = $form->showFilterButtons(); -print $searchpicto; -print ''; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + 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 ($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; + if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + 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 ''; + print '
    '.$langs->trans("NoRecordFound").'
    '.$langs->trans("NoRecordFound").'
    '."\n"; diff --git a/htdocs/product/stock/stocktransfer/class/stocktransfer.class.php b/htdocs/product/stock/stocktransfer/class/stocktransfer.class.php new file mode 100644 index 00000000000..a144895e836 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/class/stocktransfer.class.php @@ -0,0 +1,1067 @@ + + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 class/stocktransfer.class.php + * \ingroup stocktransfer + * \brief This file is a CRUD class file for StockTransfer (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php'; + +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for StockTransfer + */ +class StockTransfer extends CommonObject +{ + use CommonIncoterm; + /** + * @var string ID to identify managed object. + */ + public $element = 'stocktransfer'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'stocktransfer_stocktransfer'; + + /** + * @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 = 0; + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 1; + + /** + * @var string String with name of icon for stocktransfer. Must be the part after the 'object_' into object_stocktransfer.png + */ + public $picto = 'stock'; + + + const STATUS_DRAFT = 0; + const STATUS_VALIDATED = 1; + const STATUS_TRANSFERED = 2; + const STATUS_CLOSED = 3; + + + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', '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. + * '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' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * '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. + * 'arraykeyval' 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. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @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, 'comment'=>"Id"), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>'1', 'position'=>1, 'default'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'comment'=>"Id"), + 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of object"), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth200'/*, 'help'=>"Help text"*/, 'showoncombobox'=>'1',), + 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>31, 'notnull'=>0, 'visible'=>3,), + 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'enabled'=>'$conf->project->enabled', 'position'=>32, 'notnull'=>-1, 'visible'=>-1, 'index'=>1,), + 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1:status=1 AND entity IN (__SHARED_ENTITIES__)', 'label'=>'ThirdParty', 'enabled'=>'1', 'position'=>50, 'notnull'=>-1, 'visible'=>1, 'index'=>1/*, 'help'=>"LinkToThirparty"*/,), + 'fk_warehouse_source' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Entrepôt source', 'enabled'=>'1', 'position'=>50, 'notnull'=>0, 'visible'=>1, 'help'=>'HelpWarehouseStockTransferSource',), + 'fk_warehouse_destination' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Entrepôt de destination', 'enabled'=>'1', 'position'=>51, 'notnull'=>0, 'visible'=>1, 'help'=>'HelpWarehouseStockTransferDestination'), + 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0,), + 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,), + 'date_prevue_depart' => array('type'=>'date', 'label'=>'DatePrevueDepart', 'enabled'=>'1', 'position'=>100, 'notnull'=>0, 'visible'=>1,), + 'date_reelle_depart' => array('type'=>'date', 'label'=>'DateReelleDepart', 'enabled'=>'1', 'position'=>101, 'notnull'=>0, 'visible'=>5,), + 'date_prevue_arrivee' => array('type'=>'date', 'label'=>'DatePrevueArrivee', 'enabled'=>'1', 'position'=>102, 'notnull'=>0, 'visible'=>1,), + 'date_reelle_arrivee' => array('type'=>'date', 'label'=>'DateReelleArrivee', 'enabled'=>'1', 'position'=>103, 'notnull'=>0, 'visible'=>5,), + 'lead_time_for_warning' => array('type'=>'integer', 'label'=>'LeadTimeForWarning', 'enabled'=>'1', 'position'=>200, 'default'=>0, 'notnull'=>0, 'visible'=>1), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,), + 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',), + 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'ChangedBy', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,), + 'model_pdf' => array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>'1', 'position'=>1010, 'notnull'=>-1, 'visible'=>0,), + 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-2, 'position'=>220), + 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-2, 'position'=>225), + 'status' => array('type'=>'smallint', 'label'=>'Status', 'enabled'=>'1', 'position'=>1000, 'notnull'=>1, 'visible'=>5, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Draft', '1'=>'Validated', '2'=>'StockStransferDecremented', '3'=>'StockStransferIncremented'),), + ); + public $rowid; + public $ref; + public $label; + public $fk_soc; + public $fk_project; + public $description; + public $note_public; + public $note_private; + public $date_creation; + public $tms; + public $fk_user_creat; + public $fk_user_modif; + public $import_key; + public $model_pdf; + public $status; + // END MODULEBUILDER PROPERTIES + + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + public $table_element_line = 'stocktransfer_stocktransferline'; + + /** + * @var int Field with ID of parent key if this object has a parent + */ + public $fk_element = 'fk_stocktransfer'; + + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'StockTransferline'; + + /** + * @var array List of child tables. To test if we can delete object. + */ + //protected $childtables = array(); + + /** + * @var array List of child tables. To know object to delete on cascade. + * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will + * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object + */ + protected $childtablesoncascade = array('stocktransfer_stocktransferline'); + + /** + * @var StockTransferLine[] Array of subtable lines + */ + //public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; + + $this->db = $db; + $this->origin_type = 'StockTransfer@product/stock/stocktransfer'; + + 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; + + // Example to show how to set values of fields definition dynamically + /*if ($user->rights->stocktransfer->stocktransfer->read) { + $this->fields['myfield']['visible'] = 1; + $this->fields['myfield']['noteditable'] = 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 (is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + $model_pdf = GETPOST('model'); + if (!empty($model_pdf)) $this->model_pdf = $model_pdf; + $this->status = (int) $this->status; + if ($this->fk_warehouse_source <= 0) $this->fk_warehouse_source = 0; + if ($this->fk_warehouse_destination <= 0) $this->fk_warehouse_destination = 0; + return $this->createCommon($user, $notrigger); + } + + /** + * Clone an object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $langs, $extrafields; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $result = $object->fetchCommon($fromid); + if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + + // get lines so they will be clone + //foreach($this->lines as $line) + // $line->fetch_optionals(); + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + unset($object->date_prevue_depart); + unset($object->date_prevue_arrivee); + unset($object->date_reelle_depart); + unset($object->date_reelle_arrivee); + + + // Clear fields + $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default']; + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + $object->status = self::STATUS_DRAFT; + // ... + // Clear extrafields that are unique + if (is_array($object->array_options) && count($object->array_options) > 0) { + $extrafields->fetch_name_optionals_label($this->table_element); + foreach ($object->array_options as $key => $option) { + $shortkey = preg_replace('/options_/', '', $key); + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { + //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; + unset($object->array_options[$key]); + } + } + } + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + if (!$error) { + // copy internal contacts + if ($this->copy_linked_contact($object, 'internal') < 0) { + $error++; + } + } + + if (!$error) { + // copy external contacts if same company + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) + $error++; + } + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + require_once DOL_DOCUMENT_ROOT . '/product/stock/stocktransfer/class/stocktransferline.class.php'; + $this->lines = array(); + + $result = $this->fetchLinesCommon(); + usort($this->lines, array('stocktransfer', 'cmp')); + return $result; + } + + /** + * Used to sort lines by rank + * + * @param $a 1st element to test + * @param $b 1st element to test + * @return int + */ + public function cmp($a, $b) + { + if ($a->rang == $b->rang) { + return 0; + } + return ($a->rang < $b->rang) ? -1 : 1; + } + + /** + * Used to get total PMP amount of all quantities of products of Stock Transfer + * + * @return float total amount of Stock Transfer + */ + public function getValorisationTotale() + { + + $total_pmp = 0; + + if (empty($this->lines)) $this->fetchLines(); + if (!empty($this->lines)) { + foreach ($this->lines as $l) $total_pmp+= ($l->pmp * $l->qty); + } + + return $total_pmp; + } + + /** + * Load list of objects in memory from the database. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int $limit limit + * @param int $offset Offset + * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...) + * @param string $filtermode Filter mode (AND or OR) + * @return array|int int <0 if KO, array of pages if OK + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $records = array(); + + $sql = 'SELECT '; + $sql .= $this->getFieldList(); + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + else $sql .= ' WHERE 1 = 1'; + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key == 't.rowid') { + $sqlwhere[] = $key.'='.$value; + } elseif (strpos($key, 'date') !== false) { + $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; + } elseif ($key == 'customsql') { + $sqlwhere[] = $value; + } else { + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } + if (count($sqlwhere) > 0) { + $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")"; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new self($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); + + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + $this->tms = ''; // Will be done automatically because tms field is on update cascade + $res = $this->updateCommon($user, $notrigger); + if ($this->socid > 0 || $this->fk_soc > 0 && empty($this->thirdparty)) $this->fetch_thirdparty(); + if (empty($this->socid) && empty($this->fk_soc)) unset($this->thirdparty); + return $res; + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + if ($this->status > self::STATUS_VALIDATED) { + return 0; + } else { + return $this->deleteCommon($user, $notrigger); + } + } + + /** + * Delete a line of object in database + * + * @param User $user User that delete + * @param int $idline Id of line to delete + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int >0 if OK, <0 if KO + */ + public function deleteLine(User $user, $idline, $notrigger = false) + { + if ($this->status < 0) { + $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; + return -2; + } + + $res = $this->deleteLineCommon($user, $idline, $notrigger); + $this->line_order(true); + return $res; + } + + + /** + * Validate object + * + * @param User $user User making status change + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <=0 if OK, 0=Nothing done, >0 if KO + */ + public function validate($user, $notrigger = 0) + { + global $conf, $langs; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $error = 0; + + // Protection + if ($this->status == self::STATUS_VALIDATED) { + dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer->stocktransfer_advance->validate)))) + { + $this->error='NotEnoughPermissions'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + }*/ + + $now = dol_now(); + + $this->db->begin(); + + // Define new ref + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life + $num = $this->getNextNumRef(); + } else { + $num = $this->ref; + } + $this->newref = $num; + + if (!empty($num)) { + // Validate + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " status = ".self::STATUS_VALIDATED; + if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."',"; + if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".((int) $user->id); + $sql .= " WHERE rowid = ".((int) $this->id); + + dol_syslog(get_class($this)."::validate()", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + dol_print_error($this->db); + $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('STOCKTRANSFER_VALIDATE', $user); + if ($result < 0) $error++; + // End call triggers + } + } + + if (!$error) { + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) { + // Now we rename also files into index + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'stocktransfer/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'stocktransfer/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity); + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->stocktransfer->dir_output.'/stocktransfer/'.$oldref; + $dirdest = $conf->stocktransfer->dir_output.'/stocktransfer/'.$newref; + if (!$error && file_exists($dirsource)) { + dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); + + if (@rename($dirsource, $dirdest)) { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->stocktransfer->dir_output.'/stocktransfer/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + } + + // Set new ref and current status + if (!$error) { + $this->ref = $num; + $this->status = self::STATUS_VALIDATED; + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, >0 if OK + */ + public function setDraft($user, $notrigger = 0) + { + // Protection + if ($this->status <= self::STATUS_DRAFT) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'STOCKTRANSFER_UNVALIDATE'); + } + + /** + * Set cancel status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function cancel($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_VALIDATED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_CLOSED, $notrigger, 'STOCKTRANSFER_CLOSE'); + } + + /** + * Set back to validated status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function reopen($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_CLOSED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'STOCKTRANSFER_REOPEN'); + } + + /** + * 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 = ''.$langs->trans("StockTransfer").''; + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; + if (isset($this->status)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } + + $url = dol_buildpath('/product/stock/stocktransfer/stocktransfer_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 ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + } + + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowStockTransfer"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + + $linkstart = ''; + $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('stocktransferdao')); + $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 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 getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the 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 of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; + //$langs->load("stocktransfer@stocktransfer"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Validated'); + $this->labelStatus[self::STATUS_TRANSFERED] = $langs->trans('StockStransferDecremented'); + $this->labelStatus[self::STATUS_CLOSED] = $langs->trans('StockStransferIncremented'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Validated'); + $this->labelStatusShort[self::STATUS_TRANSFERED] = $langs->trans('StockStransferDecremented'); + $this->labelStatusShort[self::STATUS_CLOSED] = $langs->trans('StockStransferIncremented'); + } + + $statusType = 'status'.$status; + //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; + if ($status == self::STATUS_CLOSED) $statusType = 'status6'; + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } + + /** + * Load the info information in the object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql .= ' fk_user_creat, fk_user_modif'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql .= ' WHERE t.rowid = '.((int) $id); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + + /** + * Create an array of lines + * + * @return array|int array of lines if OK, <0 if KO + */ + public function getLinesArray() + { + $this->lines = array(); + + $objectline = new StockTransferLine($this->db); + $result = $objectline->fetchAll('ASC', 'rang', 0, 0, array('customsql'=>'fk_stocktransfer = '.$this->id)); + + if (is_numeric($result)) { + $this->error = $this->error; + $this->errors = $this->errors; + return $result; + } else { + $this->lines = $result; + return $this->lines; + } + } + + /** + * Returns the reference to the following non used object depending on the active numbering module. + * + * @return string Object free reference + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("stocks"); + + if (empty($conf->global->STOCKTRANSFER_STOCKTRANSFER_ADDON)) { + $conf->global->STOCKTRANSFER_STOCKTRANSFER_ADDON = 'mod_stocktransfer_standard'; + } + + if (!empty($conf->global->STOCKTRANSFER_STOCKTRANSFER_ADDON)) { + $mybool = false; + + $file = $conf->global->STOCKTRANSFER_STOCKTRANSFER_ADDON.".php"; + $classname = $conf->global->STOCKTRANSFER_STOCKTRANSFER_ADDON; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/stocktransfer/"); + + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } + + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } + + if (class_exists($classname)) { + $obj = new $classname(); + $numref = $obj->getNextValue($this); + + if ($numref != '' && $numref != '-1') { + return $numref; + } else { + $this->error = $obj->error; + //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); + return ""; + } + } else { + print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname; + return ""; + } + } else { + print $langs->trans("ErrorNumberingModuleNotSetup", $this->element); + return ""; + } + } + + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; + + $result = 0; + $includedocgeneration = 1; + + $langs->load("stocks"); + + if (!dol_strlen($modele)) { + $modele = 'eagle'; + + if ($this->modelpdf) { + $modele = $this->modelpdf; + } elseif (!empty($conf->global->STOCKTRANSFER_ADDON_PDF)) { + $modele = $conf->global->STOCKTRANSFER_ADDON_PDF; + } + } + + $modelpath = "core/modules/stocktransfer/doc/"; + + if ($includedocgeneration) { + $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } + + return $result; + } + + /** + * Action executed by scheduler + * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters' + * Use public function doScheduledJob($param1, $param2, ...) to get parameters + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + global $conf, $langs; + + //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log'; + + $error = 0; + $this->output = ''; + $this->error = ''; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $now = dol_now(); + + $this->db->begin(); + + // ... + + $this->db->commit(); + + return $error; + } +} + +/** + * Class StockTransferLine. You can also remove this and generate a CRUD class for lines objects. + */ +//class StockTransferLine +//{ +// // To complete with content of an object StockTransferLine +// // We should have a field rowid, fk_stocktransfer and position +// +// /** +// * @var int Does object support extrafields ? 0=No, 1=Yes +// */ +// public $isextrafieldmanaged = 0; +// +// /** +// * Constructor +// * +// * @param DoliDb $db Database handler +// */ +// public function __construct(DoliDB $db) +// { +// $this->db = $db; +// } +//} diff --git a/htdocs/product/stock/stocktransfer/class/stocktransferline.class.php b/htdocs/product/stock/stocktransfer/class/stocktransferline.class.php new file mode 100644 index 00000000000..31549e04832 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/class/stocktransferline.class.php @@ -0,0 +1,1091 @@ + + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 class/stocktransferline.class.php + * \ingroup stocktransfer + * \brief This file is a CRUD class file for StockTransferLine (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for StockTransferLine + */ +class StockTransferLine extends CommonObjectLine +{ + /** + * @var string ID to identify managed object. + */ + public $element = 'stocktransferline'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'stocktransfer_stocktransferline'; + + /** + * @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 = 0; + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 1; + + /** + * @var string String with name of icon for stocktransferline. Must be the part after the 'object_' into object_stocktransferline.png + */ + public $picto = 'stocktransferline@stocktransfer'; + + + const STATUS_DRAFT = 0; + const STATUS_VALIDATED = 1; + const STATUS_CANCELED = 9; + + + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', '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. + * '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' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * '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. + * 'arraykeyval' 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. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @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, 'comment'=>"Id"), + 'amount' => array('type'=>'price', 'label'=>'Amount', 'enabled'=>'1', 'position'=>40, 'notnull'=>0, 'visible'=>1, 'default'=>'null', 'isameasure'=>'1', 'help'=>"Help text for amount",), + 'qty' => array('type'=>'real', 'label'=>'Qty', 'enabled'=>'1', 'position'=>45, 'notnull'=>0, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'css'=>'maxwidth75imp', 'help'=>"Help text for quantity",), + 'fk_warehouse_destination' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Entrepôt de destination', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1,), + 'fk_warehouse_source' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Entrepôt source', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1,), + 'fk_stocktransfer' => array('type'=>'integer:StockTransfer:stocktransfer/stock/class/stocktransfer.class.php', 'label'=>'StockTransfer', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>0,), + 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>1,), + 'batch' => array('type'=>'varchar(128)', 'label'=>'Batch', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>1,), + 'pmp' => array('type'=>'double'/*, 'help'=>'THMEstimatedHelp'*/, 'label'=>'PMP', 'enabled'=>'1', 'position'=>50, 'notnull'=>0, 'visible'=>1,), + 'rang' => array('type'=>'integer', 'label'=>'Qty', 'enabled'=>'1', 'position'=>45, 'notnull'=>0, 'visible'=>0, 'default'=>'0', 'isameasure'=>'1', 'css'=>'maxwidth75imp', 'help'=>"Help text for quantity",), + ); + public $rowid; + public $amount; + public $qty; + public $fk_warehouse_destination; + public $fk_warehouse_source; + public $fk_stocktransfer; + public $fk_product; + public $batch; + // END MODULEBUILDER PROPERTIES + + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + //public $table_element_line = 'stocktransfer_stocktransferlineline'; + + /** + * @var int Field with ID of parent key if this object has a parent + */ + //public $fk_element = 'fk_stocktransferline'; + + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'StockTransferLineline'; + + /** + * @var array List of child tables. To test if we can delete object. + */ + //protected $childtables = array(); + + /** + * @var array List of child tables. To know object to delete on cascade. + * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will + * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object + */ + //protected $childtablesoncascade = array('stocktransfer_stocktransferlinedet'); + + /** + * @var StockTransferLineLine[] Array of subtable lines + */ + //public $lines = array(); + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; + + $this->db = $db; + + 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; + + // Example to show how to set values of fields definition dynamically + /*if ($user->rights->stocktransfer->stocktransferline->read) { + $this->fields['myfield']['visible'] = 1; + $this->fields['myfield']['noteditable'] = 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 (is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone an object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $langs, $extrafields; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $result = $object->fetchCommon($fromid); + if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + + // get lines so they will be clone + //foreach($this->lines as $line) + // $line->fetch_optionals(); + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + + // Clear fields + $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default']; + $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; + $object->status = self::STATUS_DRAFT; + // ... + // Clear extrafields that are unique + if (is_array($object->array_options) && count($object->array_options) > 0) { + $extrafields->fetch_name_optionals_label($this->table_element); + foreach ($object->array_options as $key => $option) { + $shortkey = preg_replace('/options_/', '', $key); + if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) { + //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; + unset($object->array_options[$key]); + } + } + } + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + if (!$error) { + // copy internal contacts + if ($this->copy_linked_contact($object, 'internal') < 0) { + $error++; + } + } + + if (!$error) { + // copy external contacts if same company + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) + $error++; + } + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetchLines() + { + $this->lines = array(); + + $result = $this->fetchLinesCommon(); + return $result; + } + + + /** + * Load list of objects in memory from the database. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int $limit limit + * @param int $offset Offset + * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...) + * @param string $filtermode Filter mode (AND or OR) + * @return array|int int <0 if KO, array of pages if OK + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $records = array(); + + $sql = 'SELECT '; + $sql .= $this->getFieldList(); + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + else $sql .= ' WHERE 1 = 1'; + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key == 't.rowid') { + $sqlwhere[] = $key.'='.$value; + } elseif (strpos($key, 'date') !== false) { + $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\''; + } elseif ($key == 'customsql') { + $sqlwhere[] = $value; + } else { + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } + if (count($sqlwhere) > 0) { + $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")"; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= ' '.$this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new self($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); + + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + //return $this->deleteCommon($user, $notrigger, 1); + } + + /** + * Delete a line of object in database + * + * @param User $user User that delete + * @param int $idline Id of line to delete + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int >0 if OK, <0 if KO + */ + public function deleteLine(User $user, $idline, $notrigger = false) + { + if ($this->status < 0) { + $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; + return -2; + } + + return $this->deleteLineCommon($user, $idline, $notrigger); + } + + /** + * Makes all stock movements (add quantity, remove quantity or cancel all actions) + * + * @param string $label label of stock movement + * @param string $code_inv label of stock movement + * @param int $fk_entrepot Warehouse concerned by stock movement + * @param int $direction add or remove qty + * @return int 1 if ok, <= 0 if ko + */ + public function doStockMovement($label, $code_inv, $fk_entrepot, $direction = 1) + { + + global $conf, $user, $langs; + + require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + include_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php'; + include_once DOL_DOCUMENT_ROOT . '/product/stock/stocktransfer/class/stocktransfer.class.php'; + + $p = new Product($this->db); + $p->fetch($this->fk_product); + + $op[0] = "+".trim($this->qty); + $op[1] = "-".trim($this->qty); + $movementstock = new MouvementStock($this->db); + $st = new StockTransfer($this->db); + $movementstock->origin_type = $st->origin_type; + $movementstock->origin_id = $this->fk_stocktransfer; + + if (empty($this->batch)) { // no batch for line + /*$result = $p->correct_stock( + $user, + $fk_entrepot, + $this->qty, + $direction, // 1=décrémentation + $label, + empty($direction) ? $this->pmp : 0, + GETPOST('inventorycode', 'alphanohtml'), + 'stocktransfer', + $this->fk_stocktransfer + );*/ + + $result = $movementstock->_create($user, + $p->id, + $fk_entrepot, + $op[$direction], + $direction, + empty($direction) ? $this->pmp : 0, + $label, + $code_inv); + + if ($result < 0) { + setEventMessages($p->errors, $p->errorss, 'errors'); + return 0; + } + } else { + if ($p->hasbatch()) { + $arraybatchinfo = $p->loadBatchInfo($this->batch); + if (count($arraybatchinfo) > 0) { + $firstrecord = array_shift($arraybatchinfo); + $dlc = $firstrecord['eatby']; + $dluo = $firstrecord['sellby']; + //var_dump($batch); var_dump($arraybatchinfo); var_dump($firstrecord); var_dump($dlc); var_dump($dluo); exit; + } else { + $dlc = ''; + $dluo = ''; + } + + /*$result = $p->correct_stock_batch( + $user, + $fk_entrepot, + $this->qty, + $direction, + $label, + empty($direction) ? $this->pmp : 0, + $dlc, + $dluo, + $this->batch, + GETPOST("codemove") + );*/ + + $result = $movementstock->_create($user, + $p->id, + $fk_entrepot, + $op[$direction], + $direction, + empty($direction) ? $this->pmp : 0, + $label, + $code_inv, + '', + $dlc, + $dluo, + $this->batch); + + if ($result < 0) { + setEventMessages($p->errors, $p->errorss, 'errors'); + return 0; + } + } else { + setEventMessages($langs->trans('StockTransferNoBatchForProduct', $p->getNomUrl()), '', 'errors'); + return -1; + } + } + + return 1; + } + + /** + * Validate object + * + * @param User $user User making status change + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <=0 if OK, 0=Nothing done, >0 if KO + */ + public function validate($user, $notrigger = 0) + { + global $conf, $langs; + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + $error = 0; + + // Protection + if ($this->status == self::STATUS_VALIDATED) { + dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransferline->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransferline->stocktransferline_advance->validate)))) + { + $this->error='NotEnoughPermissions'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + }*/ + + $now = dol_now(); + + $this->db->begin(); + + // Define new ref + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life + $num = $this->getNextNumRef(); + } else { + $num = $this->ref; + } + $this->newref = $num; + + if (!empty($num)) { + // Validate + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql .= " SET ref = '".$this->db->escape($num)."',"; + $sql .= " status = ".self::STATUS_VALIDATED; + if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."',"; + if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".((int) $user->id); + $sql .= " WHERE rowid = ".((int) $this->id); + + dol_syslog(get_class($this)."::validate()", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + dol_print_error($this->db); + $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('STOCKTRANSFERLINE_VALIDATE', $user); + if ($result < 0) $error++; + // End call triggers + } + } + + if (!$error) { + $this->oldref = $this->ref; + + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) { + // Now we rename also files into index + $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'stocktransferline/".$this->db->escape($this->newref)."'"; + $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'stocktransferline/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity); + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + + // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->stocktransfer->dir_output.'/stocktransferline/'.$oldref; + $dirdest = $conf->stocktransfer->dir_output.'/stocktransferline/'.$newref; + if (!$error && file_exists($dirsource)) { + dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); + + if (@rename($dirsource, $dirdest)) { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles = dol_dir_list($conf->stocktransfer->dir_output.'/stocktransferline/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); + foreach ($listoffiles as $fileentry) { + $dirsource = $fileentry['name']; + $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); + $dirsource = $fileentry['path'].'/'.$dirsource; + $dirdest = $fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } + } + + // Set new ref and current status + if (!$error) { + $this->ref = $num; + $this->status = self::STATUS_VALIDATED; + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Set draft status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, >0 if OK + */ + public function setDraft($user, $notrigger = 0) + { + // Protection + if ($this->status <= self::STATUS_DRAFT) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'STOCKTRANSFERLINE_UNVALIDATE'); + } + + /** + * Set cancel status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function cancel($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_VALIDATED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'STOCKTRANSFERLINE_CLOSE'); + } + + /** + * Set back to validated status + * + * @param User $user Object user that modify + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, 0=Nothing done, >0 if OK + */ + public function reopen($user, $notrigger = 0) + { + // Protection + if ($this->status != self::STATUS_CANCELED) { + return 0; + } + + /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->write)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->stocktransfer->stocktransfer_advance->validate)))) + { + $this->error='Permission denied'; + return -1; + }*/ + + return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'STOCKTRANSFERLINE_REOPEN'); + } + + /** + * 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 = ''.$langs->trans("StockTransferLine").''; + $label .= '
    '; + $label .= ''.$langs->trans('Ref').': '.$this->ref; + if (isset($this->status)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } + + $url = dol_buildpath('/stocktransfer/stocktransferline_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 ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + } + + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowStockTransferLine"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + + $linkstart = ''; + $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('stocktransferlinedao')); + $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 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 getLibStatut($mode = 0) + { + return $this->LibStatut($this->status, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return the 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 of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; + //$langs->load("stocktransfer@stocktransfer"); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Enabled'); + $this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Disabled'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Enabled'); + $this->labelStatusShort[self::STATUS_CANCELED] = $langs->trans('Disabled'); + } + + $statusType = 'status'.$status; + //if ($status == self::STATUS_VALIDATED) $statusType = 'status1'; + if ($status == self::STATUS_CANCELED) $statusType = 'status6'; + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } + + /** + * Load the info information in the object + * + * @param int $id Id of object + * @return void + */ + public function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql .= ' fk_user_creat, fk_user_modif'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql .= ' WHERE t.rowid = '.((int) $id); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + + /** + * Create an array of lines + * + * @return array|int array of lines if OK, <0 if KO + */ + public function getLinesArray() + { + $this->lines = array(); + + $objectline = new StockTransferLineLine($this->db); + $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_stocktransferline = '.((int) $this->id))); + + if (is_numeric($result)) { + $this->error = $this->error; + $this->errors = $this->errors; + return $result; + } else { + $this->lines = $result; + return $this->lines; + } + } + + /** + * Returns the reference to the following non used object depending on the active numbering module. + * + * @return string Object free reference + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("stocks"); + + if (empty($conf->global->STOCKTRANSFER_STOCKTRANSFERLINE_ADDON)) { + $conf->global->STOCKTRANSFER_STOCKTRANSFERLINE_ADDON = 'mod_stocktransferline_standard'; + } + + if (!empty($conf->global->STOCKTRANSFER_STOCKTRANSFERLINE_ADDON)) { + $mybool = false; + + $file = $conf->global->STOCKTRANSFER_STOCKTRANSFERLINE_ADDON.".php"; + $classname = $conf->global->STOCKTRANSFER_STOCKTRANSFERLINE_ADDON; + + // Include file with class + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { + $dir = dol_buildpath($reldir."core/modules/stocktransfer/"); + + // Load file with numbering class (if found) + $mybool |= @include_once $dir.$file; + } + + if ($mybool === false) { + dol_print_error('', "Failed to include file ".$file); + return ''; + } + + if (class_exists($classname)) { + $obj = new $classname(); + $numref = $obj->getNextValue($this); + + if ($numref != '' && $numref != '-1') { + return $numref; + } else { + $this->error = $obj->error; + //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error); + return ""; + } + } else { + print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname; + return ""; + } + } else { + print $langs->trans("ErrorNumberingModuleNotSetup", $this->element); + return ""; + } + } + + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null) + { + global $conf, $langs; + + $result = 0; + $includedocgeneration = 0; + + $langs->load("stocks"); + + if (!dol_strlen($modele)) { + $modele = 'standard_stocktransferline'; + + if ($this->modelpdf) { + $modele = $this->modelpdf; + } elseif (!empty($conf->global->STOCKTRANSFERLINE_ADDON_PDF)) { + $modele = $conf->global->STOCKTRANSFERLINE_ADDON_PDF; + } + } + + $modelpath = "core/modules/stocktransfer/doc/"; + + if ($includedocgeneration) { + $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } + + return $result; + } + + /** + * Action executed by scheduler + * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters' + * Use public function doScheduledJob($param1, $param2, ...) to get parameters + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + global $conf, $langs; + + //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log'; + + $error = 0; + $this->output = ''; + $this->error = ''; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $now = dol_now(); + + $this->db->begin(); + + // ... + + $this->db->commit(); + + return $error; + } +} + +/** + * Class StockTransferLineLine. You can also remove this and generate a CRUD class for lines objects. + */ +class StockTransferLineLine +{ + // To complete with content of an object StockTransferLineLine + // We should have a field rowid, fk_stocktransferline and position + + /** + * @var int Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + } +} diff --git a/htdocs/product/stock/stocktransfer/lib/stocktransfer.lib.php b/htdocs/product/stock/stocktransfer/lib/stocktransfer.lib.php new file mode 100644 index 00000000000..8460a6405bc --- /dev/null +++ b/htdocs/product/stock/stocktransfer/lib/stocktransfer.lib.php @@ -0,0 +1,67 @@ + + * + * 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 stocktransfer/lib/stocktransfer.lib.php + * \ingroup stocktransfer + * \brief Library files with common functions for StockTransfer + */ + +/** + * Prepare admin pages header + * + * @return array + */ +function stocktransferAdminPrepareHead() +{ + global $langs, $conf; + + $langs->load("stocks"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/admin/stocktransfer.php", 1); + $head[$h][1] = $langs->trans("Settings"); + $head[$h][2] = 'settings'; + $h++; + + /* + $head[$h][0] = dol_buildpath("/stocktransfer/admin/myobject_extrafields.php", 1); + $head[$h][1] = $langs->trans("ExtraFields"); + $head[$h][2] = 'myobject_extrafields'; + $h++; + */ + + /*$head[$h][0] = dol_buildpath("/product/stock/stocktransfer/admin/about.php", 1); + $head[$h][1] = $langs->trans("About"); + $head[$h][2] = 'about'; + $h++;*/ + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@stocktransfer:/stocktransfer/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@stocktransfer:/stocktransfer/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, null, $head, $h, 'stocktransfer'); + + return $head; +} diff --git a/htdocs/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php b/htdocs/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php new file mode 100644 index 00000000000..232229a014d --- /dev/null +++ b/htdocs/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php @@ -0,0 +1,94 @@ + + * + * 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 lib/stocktransfer_stocktransfer.lib.php + * \ingroup stocktransfer + * \brief Library files with common functions for StockTransfer + */ + +/** + * Prepare array of tabs for StockTransfer + * + * @param StockTransfer $object StockTransfer + * @return array Array of tabs + */ +function stocktransferPrepareHead($object) +{ + global $db, $langs, $conf; + + $langs->load("stocks"); + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/product/stock/stocktransfer/stocktransfer_card.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'card'; + $h++; + + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = dol_buildpath('/product/stock/stocktransfer/stocktransfer_contact.php', 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('ContactsAddresses'); + if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + $head[$h][2] = 'contact'; + $h++; + } + + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; + if (!empty($object->note_public)) $nbNote++; + $head[$h][0] = dol_buildpath('/product/stock/stocktransfer/stocktransfer_note.php', 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Notes'); + if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbNote.'' : ''); + $head[$h][2] = 'note'; + $h++; + } + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->stocktransfer->dir_output."/stocktransfer/".dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$h][0] = dol_buildpath("/product/stock/stocktransfer/stocktransfer_document.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + $head[$h][2] = 'document'; + $h++; + + $head[$h][0] = dol_buildpath("/product/stock/stocktransfer/stocktransfer_agenda.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Events"); + $head[$h][2] = 'agenda'; + $h++; + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@stocktransfer:/stocktransfer/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@stocktransfer:/stocktransfer/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'stocktransfer@stocktransfer'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'stocktransfer@stocktransfer', 'remove'); + + return $head; +} diff --git a/htdocs/product/stock/stocktransfer/stocktransfer_agenda.php b/htdocs/product/stock/stocktransfer/stocktransfer_agenda.php new file mode 100644 index 00000000000..ccbdf12e712 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/stocktransfer_agenda.php @@ -0,0 +1,247 @@ + + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 stocktransfer_agenda.php + * \ingroup stocktransfer + * \brief Page of StockTransfer events + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; +if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); + +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/class/stocktransfer.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php'; + + +// Load translation files required by the page +$langs->loadLangs(array("stocks", "other")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +if (GETPOST('actioncode', 'array')) { + $actioncode = GETPOST('actioncode', 'array', 3); + if (!count($actioncode)) $actioncode = '0'; +} else { + $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); +} +$search_agenda_label = GETPOST('search_agenda_label'); + +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortfield) $sortfield = 'a.datep,a.id'; +if (!$sortorder) $sortorder = 'DESC,DESC'; + +// Initialize technical objects +$object = new StockTransfer($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->stocktransfer->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('stocktransferagenda', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || !empty($ref)) $upload_dir = $conf->stocktransfer->multidir_output[$object->entity]."/".$object->id; + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +$result = restrictedArea($user, 'stocktransfer', $object->id, '', 'stocktransfer'); + +$permissiontoadd = $user->rights->stocktransfer->stocktransfer->write; // Used by the include of actions_addupdatedelete.inc.php + + +/* + * Actions + */ + +$parameters = array('id'=>$id); +$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'); + +if (empty($reshook)) { + // Cancel + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { + header("Location: ".$backtopage); + exit; + } + + // 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 + $actioncode = ''; + $search_agenda_label = ''; + } +} + + + +/* + * View + */ + +$form = new Form($db); + +if ($object->id > 0) { + $title = $langs->trans("Agenda"); + //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; + $help_url = ''; + llxHeader('', $title, $help_url); + + if (!empty($conf->notification->enabled)) $langs->load("mails"); + $head = stocktransferPrepareHead($object); + + + dol_fiche_head($head, 'agenda', $langs->trans("StockTransfer"), -1, $object->picto); + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + + $object->info($object->id); + dol_print_object_info($object, 1); + + print '
    '; + + dol_fiche_end(); + + + + // Actions buttons + + $objthirdparty = $object; + $objcon = new stdClass(); + + $out = '&origin='.$object->element.'&originid='.$object->id; + $permok = $user->rights->agenda->myactions->create; + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { + //$out.='trans("AddAnAction"),'filenew'); + //$out.=""; + } + + + print '
    '; + + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { + print ''.$langs->trans("AddAction").''; + } else { + print ''.$langs->trans("AddAction").''; + } + } + + print '
    '; + + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { + $param = '&id='.$object->id.'&socid='.$socid; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + + + //print load_fiche_titre($langs->trans("ActionsOnStockTransfer"), '', ''); + + // List of all actions + $filters = array(); + $filters['search_agenda_label'] = $search_agenda_label; + + // TODO Replace this with same code than into list.php + + show_actions_done($conf, $langs, $db, $object, null, 0, $actioncode, '', $filters, $sortfield, $sortorder, ''); + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/product/stock/stocktransfer/stocktransfer_card.php b/htdocs/product/stock/stocktransfer/stocktransfer_card.php new file mode 100644 index 00000000000..84e87dd32f1 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/stocktransfer_card.php @@ -0,0 +1,1098 @@ + + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 stocktransfer_card.php + * \ingroup stocktransfer + * \brief Page to create/edit/view stocktransfer + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies + + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; +if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/class/stocktransfer.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/class/stocktransferline.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/stocktransfer/modules_stocktransfer.php'; + +// Load translation files required by the page +$langs->loadLangs(array("stocks", "other", "productbatch", "companies")); + if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'stocktransfercard'; // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); +$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); +$qty = GETPOST('qty', 'int'); +$fk_product = GETPOST('fk_product', 'int'); +$fk_warehouse_source = GETPOST('fk_warehouse_source', 'int'); +$fk_warehouse_destination = GETPOST('fk_warehouse_destination', 'int'); +$lineid = GETPOST('lineid', 'int'); +$label = GETPOST('label', 'alpha'); +$batch = GETPOST('batch', 'alpha'); +$code_inv = GETPOST('inventorycode', 'alphanohtml'); + +// Initialize technical objects +$object = new StockTransfer($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->stocktransfer->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('stocktransfercard', 'globalcard')); // 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_'); + +// Initialize array of search criterias +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +} + +if (empty($action) && empty($id) && empty($ref)) $action = 'view'; + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. + + +$permissiontoread = $user->rights->stocktransfer->stocktransfer->read; +$permissiontoadd = $user->rights->stocktransfer->stocktransfer->write; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissionnote = $user->rights->stocktransfer->stocktransfer->write; // Used by the include of actions_setnotes.inc.php +$permissiontodelete = $user->rights->stocktransfer->stocktransfer->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); +$permissiondellink = $user->rights->stocktransfer->stocktransfer->write; // Used by the include of actions_dellink.inc.php +$upload_dir = $conf->stocktransfer->multidir_output[isset($object->entity) ? $object->entity : 1]; + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->statut == $object::STATUS_DRAFT) ? 1 : 0); +//$result = restrictedArea($user, 'stocktransfer', $object->id, '', '', 'fk_soc', 'rowid', $isdraft); + +if (!$permissiontoread || ($action === 'create' && !$permissiontoadd)) accessforbidden(); + + +/* + * Actions + */ + +$form = new Form($db); +$formfile = new FormFile($db); +$formproject = new FormProjets($db); + +$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'); + +if (empty($reshook)) { + $error = 0; + + $backurlforlist = dol_buildpath('/product/stock/stocktransfer/stocktransfer_list.php', 1); + + 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('/product/stock/stocktransfer/stocktransfer_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } + } + $triggermodname = 'STOCKTRANSFER_STOCKTRANSFER_MODIFY'; // Name of trigger action code to execute when we modify record + + // 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'; + + // On remet cette lecture de permission ici car nécessaire d'avoir le nouveau statut de l'objet après toute action exécutée dessus (après incrémentation par exemple, le bouton supprimer doit disparaître) + $permissiontodelete = $user->rights->stocktransfer->stocktransfer->delete || ($permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); + + // Actions when linking object each other + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; + + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + + // Action to move up and down lines of object + include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; + + // Action to build doc + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + if ($action == 'set_thirdparty' && $permissiontoadd) { + $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'STOCKTRANSFER_MODIFY'); + } + if ($action == 'classin' && $permissiontoadd) { + $object->setProject(GETPOST('projectid', 'int')); + } + + if ($action == 'addline' && $permissiontoadd) { + if ($qty <= 0) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); + $action = 'view'; + } + + if ($fk_warehouse_source <= 0) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors'); + $action = 'view'; + } + + if ($fk_warehouse_destination <= 0) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors'); + $action = 'view'; + } + + $prod = new Product($db); + $prod->fetch($fk_product); + if ($prod->hasbatch()) { + if (empty($batch)) { + $error++; + $langs->load("errors"); + setEventMessages($langs->transnoentities("ErrorTryToMakeMoveOnProductRequiringBatchData", $prod->ref), null, 'errors'); + } + } else { + if (!empty($batch)) { + $error++; + setEventMessages($langs->transnoentities('StockTransferNoBatchForProduct', $prod->getNomUrl()), '', 'errors'); + } + } + + if (empty($error)) { + $line = new StockTransferLine($db); + $records = $line->fetchAll('', '', 0, 0, array('customsql'=>' fk_stocktransfer = '.((int) $id).' AND fk_product = '.((int) $fk_product).' AND fk_warehouse_source = '.((int) $fk_warehouse_source).' AND fk_warehouse_destination = '.((int) $fk_warehouse_destination).' AND ('.(empty($batch) ? 'batch = "" or batch IS NULL' : "batch = '".$db->escape($batch)."'" ).')')); + if (!empty($records[key($records)])) $line = $records[key($records)]; + $line->fk_stocktransfer = $id; + $line->qty += $qty; + $line->fk_warehouse_source = $fk_warehouse_source; + $line->fk_warehouse_destination = $fk_warehouse_destination; + $line->fk_product = $fk_product; + $line->batch = $batch; + + $line->pmp = $prod->pmp; + if ($line->id > 0) $line->update($user); + else { + $line->rang = count($object->lines) + 1; + $line->create($user); + } + $object->fetchLines(); + } + } elseif ($action === 'updateline' && $permissiontoadd) { + if ($qty <= 0) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); + $action = 'editline'; + } + + if ($fk_warehouse_source <= 0) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseSource")), null, 'errors'); + $action = 'editline'; + } + + if ($fk_warehouse_destination <= 0) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WarehouseTarget")), null, 'errors'); + $action = 'editline'; + } + + $prod = new Product($db); + $prod->fetch($fk_product); + if ($prod->hasbatch()) { + if (empty($batch)) { + $error++; + $langs->load("errors"); + setEventMessages($langs->transnoentities("ErrorTryToMakeMoveOnProductRequiringBatchData", $prod->getNomUrl()), null, 'errors'); + $action = 'editline'; + } + } else { + if (!empty($batch)) { + $error++; + setEventMessages($langs->transnoentities('StockTransferNoBatchForProduct', $prod->getNomUrl()), '', 'errors'); + $action = 'editline'; + } + } + + if (empty($error)) { + $line = new StockTransferLine($db); + $line->fetch($lineid); + $line->qty = $qty; + $line->fk_warehouse_source = $fk_warehouse_source; + $line->fk_warehouse_destination = $fk_warehouse_destination; + $line->fk_product = $fk_product; + $line->batch = $batch; + $line->pmp = $prod->pmp; + $line->update($user); + } + } + + if ($permissiontoadd) { + // Décrémentation + if ($action == 'confirm_destock' && $confirm == 'yes' && $object->status == $object::STATUS_VALIDATED) { + $lines = $object->getLinesArray(); + if (!empty($lines)) { + $db->begin(); + foreach ($lines as $line) { + $res = $line->doStockMovement($label, $code_inv, $line->fk_warehouse_source); + if ($res <= 0) $error++; + } + if (empty($error)) $db->commit(); + else $db->rollback(); + } + if (empty($error)) { + $object->setStatut($object::STATUS_TRANSFERED, $id); + $object->status = $object::STATUS_TRANSFERED; + $object->date_reelle_depart = date('Y-m-d'); + $object->update($user); + setEventMessage('StockStransferDecremented'); + } + } + + // Annulation décrémentation + if ($action == 'confirm_destockcancel' && $confirm == 'yes' && $object->status == $object::STATUS_TRANSFERED) { + $lines = $object->getLinesArray(); + if (!empty($lines)) { + $db->begin(); + foreach ($lines as $line) { + $res = $line->doStockMovement($label, $code_inv, $line->fk_warehouse_source, 0); + if ($res <= 0) $error++; + } + if (empty($error)) $db->commit(); + else $db->rollback(); + } + if (empty($error)) { + $object->setStatut($object::STATUS_VALIDATED, $id); + $object->status = $object::STATUS_VALIDATED; + $object->date_reelle_depart = null; + $object->update($user); + setEventMessage('StockStransferDecrementedCancel', 'warnings'); + } + } + + // Incrémentation + if ($action == 'confirm_addstock' && $confirm == 'yes' && $object->status == $object::STATUS_TRANSFERED) { + $lines = $object->getLinesArray(); + if (!empty($lines)) { + $db->begin(); + foreach ($lines as $line) { + $res = $line->doStockMovement($label, $code_inv, $line->fk_warehouse_destination, 0); + if ($res <= 0) $error++; + } + if (empty($error)) $db->commit(); + else $db->rollback(); + } + if (empty($error)) { + $object->setStatut($object::STATUS_CLOSED, $id); + $object->status = $object::STATUS_CLOSED; + $object->date_reelle_arrivee = date('Y-m-d'); + $object->update($user); + setEventMessage('StockStransferIncrementedShort'); + } + } + + // Annulation incrémentation + if ($action == 'confirm_addstockcancel' && $confirm == 'yes' && $object->status == $object::STATUS_CLOSED) { + $lines = $object->getLinesArray(); + if (!empty($lines)) { + $db->begin(); + foreach ($lines as $line) { + $res = $line->doStockMovement($label, $code_inv, $line->fk_warehouse_destination); + if ($res <= 0) $error++; + } + if (empty($error)) $db->commit(); + else $db->rollback(); + } + if (empty($error)) { + $object->setStatut($object::STATUS_TRANSFERED, $id); + $object->status = $object::STATUS_TRANSFERED; + $object->date_reelle_arrivee = null; + $object->update($user); + setEventMessage('StockStransferIncrementedShortCancel', 'warnings'); + } + } + } + + // Set incoterm + if ($action == 'set_incoterms' && !empty($conf->incoterm->enabled) && $permissiontoadd) { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + } + // Actions to send emails + $triggersendname = 'STOCKTRANSFER_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_STOCKTRANSFER_TO'; + $trackid = 'stocktransfer'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; +} + + + + +/* + * View + * + * Put here all code to build page + */ + +$title = $langs->trans("StockTransfer"); +$help_url = ''; +llxHeader('', $title, $help_url); + + + +// Example : Adding jquery code +print ''; + + +// Part to create +if ($action == 'create') { + print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("StockTransfer")), '', 'object_'.$object->picto); + + print '
    '; + print ''; + print ''; + if ($backtopage) print ''; + if ($backtopageforcancel) print ''; + + dol_fiche_head(array(), ''); + + // Set some default values + //if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue'; + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; + + if (!empty($conf->incoterm->enabled)) { + print ''; + print ''; + print ''; + } + // Template to use by default + print ''; + print '"; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; + + print '
    '; + print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms) ? $soc->location_incoterms : ''), '', 'fk_incoterms'); + print '
    '.$langs->trans('DefaultModel').''; + print img_picto('', 'pdf', 'class="pictofixedwidth"'); + include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; + $liste = ModelePDFStockTransfer::liste_modeles($db); + $preselected = $conf->global->STOCKTRANSFER_ADDON_PDF; + print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1); + print "
    '."\n"; + + dol_fiche_end(); + + 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="ref"]'); +} + +// Part to edit record +if (($id || $ref) && $action == 'edit') { + //if($object->status < 3) { + print load_fiche_titre($langs->trans("StockTransfer"), '', 'object_' . $object->picto); + + print '
    '; + print ''; + print ''; + print ''; + if ($backtopage) print ''; + if ($backtopageforcancel) print ''; + + dol_fiche_head(); + + print '' . "\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + + print '
    '; + + dol_fiche_end(); + + print '
    '; + print '   '; + print '
    '; + + print '
    '; + //} else $action = 'view'; +} + +// Part to show record +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + $res = $object->fetch_optionals(); + + $head = stocktransferPrepareHead($object); + dol_fiche_head($head, 'card', $langs->trans("StockTransfer"), -1, $object->picto); + + $formconfirm = ''; + + // Confirmation to delete + if ($action == 'delete') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Delete'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); + } + // Confirmation to delete line + if ($action == 'deleteline') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); + } + // Clone confirmation + if ($action == 'clone') { + // Create an array for form + $formquestion = array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + } elseif ($action == 'destock') { // Destock confirmation + // Create an array for form + $formquestion = array( 'text' => '', + array('type' => 'text', 'name' => 'label', 'label' => $langs->trans("Label"), 'value' => $langs->trans('ConfirmDestock', $object->ref), 'size'=>40), + array('type' => 'text', 'name' => 'inventorycode', 'label' => $langs->trans("InventoryCode"), 'value' => dol_print_date(dol_now(), '%y%m%d%H%M%S'), 'size'=>25) + ); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DestockAllProduct'), '', 'confirm_destock', $formquestion, 'yes', 1); + } elseif ($action == 'destockcancel') { // Destock confirmation cancel + // Create an array for form + $formquestion = array( 'text' => '', + array('type' => 'text', 'name' => 'label', 'label' => $langs->trans("Label"), 'value' => $langs->trans('ConfirmDestockCancel', $object->ref), 'size'=>40), + array('type' => 'text', 'name' => 'inventorycode', 'label' => $langs->trans("InventoryCode"), 'value' => dol_print_date(dol_now(), '%y%m%d%H%M%S'), 'size'=>25) + ); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DestockAllProductCancel'), '', 'confirm_destockcancel', $formquestion, 'yes', 1); + } elseif ($action == 'addstock') { // Addstock confirmation + // Create an array for form + $formquestion = array( 'text' => '', + array('type' => 'text', 'name' => 'label', 'label' => $langs->trans("Label").' :', 'value' => $langs->trans('ConfirmAddStock', $object->ref), 'size'=>40), + array('type' => 'text', 'name' => 'inventorycode', 'label' => $langs->trans("InventoryCode"), 'value' => dol_print_date(dol_now(), '%y%m%d%H%M%S'), 'size'=>25) + ); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('AddStockAllProduct'), '', 'confirm_addstock', $formquestion, 'yes', 1); + } elseif ($action == 'addstockcancel') { // Addstock confirmation cancel + // Create an array for form + $formquestion = array( 'text' => '', + array('type' => 'text', 'name' => 'label', 'label' => $langs->trans("Label").' :', 'value' => $langs->trans('ConfirmAddStockCancel', $object->ref), 'size'=>40), + array('type' => 'text', 'name' => 'inventorycode', 'label' => $langs->trans("InventoryCode"), 'value' => dol_print_date(dol_now(), '%y%m%d%H%M%S'), 'size'=>25) + ); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('AddStockAllProductCancel'), '', 'confirm_addstockcancel', $formquestion, 'yes', 1); + } + + // Confirmation of action xxxx + if ($action == 'xxx') { + $formquestion = array(); + /* + $forcecombo=0; + if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + $formquestion = array( + // 'text' => $langs->trans("ConfirmClone"), + // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), + // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + ); + */ + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + } + + + if ($action == 'valid' && $permissiontoadd) { + $nextref=$object->getNextNumRef(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Validate'), $langs->transnoentities('ConfirmValidateStockTransfer', $nextref), 'confirm_validate', $formquestion, 0, 2); + } + + // 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 + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + + // Thirdparty + if ($conf->societe->enabled) { + $morehtmlref .= $langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : '').'
    '; + } + // Project + if (! empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref.=$langs->trans('Project') . ' '; + if ($permissiontoadd) { + //if ($action != 'classify') $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + } + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + print ''."\n"; + + // Common attributes + //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field + //unset($object->fields['fk_project']); // Hide field already shown in banner + //unset($object->fields['fk_soc']); // Hide field already shown in banner + + $object->fields['fk_soc']['visible']=0; // Already available in banner + $object->fields['fk_project']['visible']=0; // Already available in banner + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; + + // Incoterms + if (!empty($conf->incoterm->enabled)) { + print ''; + print ''; + } + + echo ''; + echo ''; + echo ''; + // Other attributes. Fields from hook formObjectOptions and Extrafields. + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + + print '
    '; + print '
    '; + print $langs->trans('IncotermLabel'); + print ''; + if ($permissiontoadd && $action != 'editincoterm') print ''.img_edit().''; + else print ' '; + print '
    '; + print '
    '; + if ($action != 'editincoterm') { + print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); + } else { + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); + } + print '
    '.$langs->trans('EnhancedValue').' '.strtolower($langs->trans('TotalWoman')); + echo ''.price($object->getValorisationTotale(), 0, '', 1, -1, -1, $conf->currency).'
    '; + print '
    '; + print '
    '; + + print '
    '; + + dol_fiche_end(); + + + /* + * Lines + */ + + if (!empty($object->table_element_line)) { + // Show object lines + /*$result = $object->getLinesArray(); + + print '
    + + + + + ';*/ + + if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; + } + + /*print '
    '; + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) + { + print ''; + } + + if (!empty($object->lines)) + { + $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1); + } + + // Form to add new line + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') + { + if ($action != 'editline') + { + // Add products/services form + $object->formAddObjectLine(1, $mysoc, $soc); + + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + } + } + + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) + { + print '
    '; + } + print '
    '; + + print "
    \n";*/ + } + + + $formproduct = new FormProduct($db); + print '
    '; + print '
    + + + + + '; + if ($lineid > 0) print ''; + print ''; + //print '
    '; + + $param = ''; + + $conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE=true; // Full display needed to see all column title details + + print '
    '; + print getTitleFieldOfList($langs->trans('ProductRef'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); + if ($conf->productbatch->enabled) { + print getTitleFieldOfList($langs->trans('Batch'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); + } + print getTitleFieldOfList($langs->trans('WarehouseSource'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); + print getTitleFieldOfList($langs->trans('WarehouseTarget'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); + print getTitleFieldOfList($langs->trans('Qty'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'center tagtd maxwidthonsmartphone '); + if ($conf->global->PRODUCT_USE_UNITS) { + print getTitleFieldOfList($langs->trans('Unit'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'tagtd maxwidthonsmartphone '); + } + print getTitleFieldOfList($langs->trans('AverageUnitPricePMPShort'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'center tagtd maxwidthonsmartphone '); + print getTitleFieldOfList($langs->trans('EstimatedStockValueShort'), 0, $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'center tagtd maxwidthonsmartphone '); + if (empty($object->status) && $permissiontoadd) { + print getTitleFieldOfList('', 0); + print getTitleFieldOfList('', 0); + print getTitleFieldOfList('', 0); + } + + print ''; + + $listofdata = $object->getLinesArray(); + $productstatic = new Product($db); + $warehousestatics = new Entrepot($db); + $warehousestatict = new Entrepot($db); + + foreach ($listofdata as $key => $line) { + $productstatic->fetch($line->fk_product); + $warehousestatics->fetch($line->fk_warehouse_source); + $warehousestatict->fetch($line->fk_warehouse_destination); + + // add html5 elements + $domData = ' data-element="'.$line->element.'"'; + $domData .= ' data-id="'.$line->id.'"'; + $domData .= ' data-qty="'.$line->qty.'"'; + //$domData .= ' data-product_type="'.$line->product_type.'"'; + + print ''; + print ''; + if ($conf->productbatch->enabled) { + print ''; + } + + print ''; + print ''; + if ($action === 'editline' && $line->id == $lineid) print ''; + else print ''; + + if ($conf->global->PRODUCT_USE_UNITS) { + print ''; + } + + print ''; + print ''; + if (empty($object->status) && $permissiontoadd) { + if ($action === 'editline' && $line->id == $lineid) { + //print ''; + print ''; + } else { + print ''; + print ''; + } + + $num = count($object->lines); + + if ($num > 1 && $conf->browser->layout != 'phone' && empty($disablemove)) { + print ''; + $coldisplay++; + } + } + + print ''; + } + + if (empty($object->status) && $action !== 'editline' && $permissiontoadd) { + print ''; + // Product + print ''; + // Batch number + if ($conf->productbatch->enabled) { + print ''; + } + + $formproduct->loadWarehouses(); // Pour charger la totalité des entrepôts + + // On stock ceux qui ne doivent pas être proposés dans la liste + $TExcludedWarehouseSource=array(); + if (!empty($object->fk_warehouse_source)) { + $source_ent = new Entrepot($db); + $source_ent->fetch($object->fk_warehouse_source); + foreach ($formproduct->cache_warehouses as $TDataCacheWarehouse) { + if (strpos($TDataCacheWarehouse['full_label'], $source_ent->label) === false) $TExcludedWarehouseSource[] = $TDataCacheWarehouse['id']; + } + } + + // On stock ceux qui ne doivent pas être proposés dans la liste + $TExcludedWarehouseDestination=array(); + if (!empty($object->fk_warehouse_destination)) { + $dest_ent = new Entrepot($db); + $dest_ent->fetch($object->fk_warehouse_destination); + foreach ($formproduct->cache_warehouses as $TDataCacheWarehouse) { + if (strpos($TDataCacheWarehouse['full_label'], $dest_ent->label) === false) $TExcludedWarehouseDestination[] = $TDataCacheWarehouse['id']; + } + } + + // On vide le tableau pour qu'il se charge tout seul lors de l'appel à la fonction select_warehouses + $formproduct->cache_warehouses=array(); + // In warehouse + print ''; + + // On vide le tableau pour qu'il se charge tout seul lors de l'appel à la fonction select_warehouses + $formproduct->cache_warehouses=array(); + // Out warehouse + print ''; + + // Qty + print ''; + // PMP + print ''; + if ($conf->global->PRODUCT_USE_UNITS) { + // Unité + print ''; + } + // PMP * Qty + print ''; + // Button to add line + print ''; + // Grad and drop lines + print ''; + print ''; + } + + print '
    '; + if ($action === 'editline' && $line->id == $lineid) $form->select_produits($line->fk_product, 'fk_product', $filtertype, $limit, 0, -1, 2, '', 0, array(), 0, 0, 0, 'minwidth200imp maxwidth300', 1); + else print $productstatic->getNomUrl(1).' - '.$productstatic->label; + print ''; + if ($action === 'editline' && $line->id == $lineid) print ''; + else { + $productlot = new Productlot($db); + if ($productlot->fetch(0, $line->fk_product, $line->batch) > 0) { + print $productlot->getNomUrl(1); + } elseif (!empty($line->batch)) print $line->batch.' '.img_warning($langs->trans('BatchNotFound'));; + } + print ''; + + if ($action === 'editline' && $line->id == $lineid) print $formproduct->selectWarehouses($line->fk_warehouse_source, 'fk_warehouse_source', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, array(), 'minwidth200imp maxwidth200', $TExcludedWarehouseSource); + else print $warehousestatics->getNomUrl(1); + print ''; + if ($action === 'editline' && $line->id == $lineid) print $formproduct->selectWarehouses($line->fk_warehouse_destination, 'fk_warehouse_destination', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, array(), 'minwidth200imp maxwidth200', $TExcludedWarehouseDestination); + else print $warehousestatict->getNomUrl(1); + print ''.$line->qty.''; + $label = $productstatic->getLabelOfUnit('short'); + if ($label !== '') { + print $langs->trans($label); + } + print ''; + print price($line->pmp, 0, '', 1, -1, -1, $conf->currency); + print ''; + print price($line->pmp * $line->qty, 0, '', 1, -1, -1, $conf->currency); + print '
    '; + print '
    '; + print 'id . '#line_' . $line->id . '">'; + print img_edit() . ''; + print ''; + print 'id . '">' . img_delete($langs->trans("Remove")) . ''; + print ''; + $coldisplay++; + if ($i > 0) { ?> + id; ?>"> + + + + id; ?>"> + + + '; + } else { + print 'browser->layout != 'phone' && empty($disablemove)) ? ' class="linecolmove tdlineupdown center"' : ' class="linecolmove center"').'>
    '; + $filtertype = 0; + if (!empty($conf->global->STOCK_SUPPORTS_SERVICES)) $filtertype = ''; + if ($conf->global->PRODUIT_LIMIT_SIZE <= 0) { + $limit = ''; + } else { + $limit = $conf->global->PRODUIT_LIMIT_SIZE; + } + + $form->select_produits($fk_product, 'fk_product', $filtertype, $limit, 0, -1, 2, '', 0, array(), 0, 0, 0, 'minwidth200imp maxwidth300', 1); + print ''; + print ''; + print ''; + print $formproduct->selectWarehouses(empty($fk_warehouse_source) ? $object->fk_warehouse_source : $fk_warehouse_source, 'fk_warehouse_source', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, array(), 'minwidth200imp maxwidth200', $TExcludedWarehouseSource); + print ''; + print $formproduct->selectWarehouses(empty($fk_warehouse_destination) ? $object->fk_warehouse_destination : $fk_warehouse_destination, 'fk_warehouse_destination', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, array(), 'minwidth200imp maxwidth200', $TExcludedWarehouseDestination); + print '
    '; + print '
    '; + print '
    '; + + // Buttons for actions + + if ($action != 'presend' && $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)) { + // Send + if (empty($user->socid)) { + print ''.$langs->trans('SendMail').''."\n"; + } + + // Back to draft + if ($object->status == $object::STATUS_VALIDATED) { + if ($permissiontoadd) { + print ''.$langs->trans("SetToDraft").''; + } + } + + // Modify + if ($permissiontoadd) { + print ''.$langs->trans("Modify").''."\n"; + } + /*else + { + print ''.$langs->trans('Modify').''."\n"; + }*/ + + // Validate + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { + print ''.$langs->trans("Validate").''; + } else { + $langs->load("errors"); + print ''.$langs->trans("Validate").''; + } + } + } elseif ($object->status == $object::STATUS_VALIDATED && $permissiontoadd) { + print ''.$langs->trans("StockTransferDecrementation").''; + } elseif ($object->status == $object::STATUS_TRANSFERED && $permissiontoadd) { + print ''.$langs->trans("StockTransferDecrementationCancel").''; + print ''.$langs->trans("StockTransferIncrementation").''; + } elseif ($object->status == $object::STATUS_CLOSED && $permissiontoadd) { + print ''.$langs->trans("StockTransferIncrementationCancel").''; + } + + // Clone + if ($permissiontoadd) { + print ''.$langs->trans("ToClone").''."\n"; + } + + /* + if ($permissiontoadd) + { + if ($object->status == $object::STATUS_ENABLED) + { + print ''.$langs->trans("Disable").''."\n"; + } + else + { + print ''.$langs->trans("Enable").''."\n"; + } + } + if ($permissiontoadd) + { + if ($object->status == $object::STATUS_VALIDATED) + { + print ''.$langs->trans("Cancel").''."\n"; + } + else + { + print ''.$langs->trans("Re-Open").''."\n"; + } + } + */ + + // Delete (need delete permission, or if draft, just need create/modify permission) + if ($object->status < $object::STATUS_TRANSFERED && $permissiontodelete) { + print ''.$langs->trans('Delete').''."\n"; + } + /*else + { + print ''.$langs->trans('Delete').''."\n"; + }*/ + } + print '
    '."\n"; + } + + + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + if ($action != 'presend') { + print '
    '; + print ''; // ancre + + $includedocgeneration = 1; + + // Documents + if ($includedocgeneration) { + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref . '/' . $objref . '.pdf'; + $filedir = $conf->stocktransfer->dir_output.'/'.$object->element.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->stocktransfer->stocktransfer->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->stocktransfer->stocktransfer->write; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('stocktransfer:StockTransfer', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang); + } + + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('stocktransfer')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + + + print '
    '; + + $MAXEVENT = 10; + + $morehtmlright = ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; + + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'stocktransfer', 0, 1, '', $MAXEVENT, '', $morehtmlright); + + print '
    '; + } + + //Select mail models is same action as presend + if (GETPOST('modelselected')) $action = 'presend'; + + // Presend form + $modelmail = 'stocktransfer'; + $defaulttopic = 'InformationMessage'; + $diroutput = $conf->stocktransfer->dir_output; + $trackid = 'stocktransfer'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/product/stock/stocktransfer/stocktransfer_contact.php b/htdocs/product/stock/stocktransfer/stocktransfer_contact.php new file mode 100644 index 00000000000..97ac4c28a73 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/stocktransfer_contact.php @@ -0,0 +1,194 @@ + + * Copyright (C) 2005-2016 Destailleur Laurent + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2011-2015 Philippe Grand + * Copyright (C) 2021 Gauthier VERDOL + * + * 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 htdocs/comm/propal/contact.php + * \ingroup propal + * \brief Tab to manage contacts/adresses of proposal + */ + +if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; +if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/class/stocktransfer.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array('facture', 'orders', 'sendings', 'companies', 'stocks')); + +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$lineid = GETPOST('lineid', 'int'); +$action = GETPOST('action', 'alpha'); + +// Security check +if ($user->socid) $socid = $user->socid; + +$result = restrictedArea($user, 'stocktransfer', $id, '', 'stocktransfer'); + +$object = new StockTransfer($db); + +// Load object +if ($id > 0 || !empty($ref)) { + $ret = $object->fetch($id, $ref); + if ($ret == 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorRecordNotFound'), null, 'errors'); + $error++; + } elseif ($ret < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } +} +if (!$error) { + $object->fetch_thirdparty(); +} else { + header('Location: '.dol_buildpath('/stocktransfer/stocktransfer_list.php', 1)); + exit; +} + + +/* + * Add a new contact + */ + +if ($action == 'addcontact' && $user->rights->stocktransfer->stocktransfer->write) { + if ($object->id > 0) { + $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); + $result = $object->add_contact($contactid, !empty($_POST["typecontact"]) ? $_POST["typecontact"] : $_POST["type"], $_POST["source"]); + } + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } +} elseif ($action == 'swapstatut' && $user->rights->stocktransfer->stocktransfer->write) { // Toggle the status of a contact + if ($object->id > 0) { + $result = $object->swapContactStatus(GETPOST('ligne')); + } +} elseif ($action == 'deletecontact' && $user->rights->stocktransfer->stocktransfer->write) { // Deletes a contact + $result = $object->delete_contact($lineid); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + dol_print_error($db); + } +} +/* +elseif ($action == 'setaddress' && $user->rights->stocktransfer->stocktransfer->write) +{ + $result=$object->setDeliveryAddress($_POST['fk_address']); + if ($result < 0) dol_print_error($db,$object->error); +}*/ + + +/* + * View + */ + +llxHeader('', $langs->trans('ModuleStockTransferName'), 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos'); + +$form = new Form($db); +$formcompany = new FormCompany($db); +$formother = new FormOther($db); + +if ($object->id > 0) { + $head = stocktransferPrepareHead($object); + dol_fiche_head($head, 'contact', $langs->trans("StockTransfer"), -1, 'stock'); + + + // Proposal card + + $linkback = ''.$langs->trans("BackToList").''; + + + $morehtmlref = '
    '; + // Ref customer + $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + if (!empty($object->thirdparty)) { + $morehtmlref .= '
    ' . $langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'customer'); + } + // Project + if (!empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '
    '.$langs->trans('Project').' '; + if ($user->rights->stocktransfer->stocktransfer->write) { + if ($action != 'classify') { + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; + $morehtmlref .= ' : '; + } + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
    '; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
    '; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } + } + $morehtmlref .= '
    '; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + + dol_fiche_end(); + + $user->rights->stocktransfer->write = $user->rights->stocktransfer->stocktransfer->write; + // Contacts lines (modules that overwrite templates must declare this into descriptor) + $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); + foreach ($dirtpls as $reldir) { + $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); + if ($res) break; + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/product/stock/stocktransfer/stocktransfer_document.php b/htdocs/product/stock/stocktransfer/stocktransfer_document.php new file mode 100644 index 00000000000..4fba0c3fea5 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/stocktransfer_document.php @@ -0,0 +1,207 @@ + + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 stocktransfer_document.php + * \ingroup stocktransfer + * \brief Tab for documents linked to StockTransfer + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; +if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); + +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/class/stocktransfer.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array("stocks", "companies", "other", "mails")); + + +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +$id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); +$ref = GETPOST('ref', 'alpha'); + +// Get parameters +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "name"; +//if (! $sortfield) $sortfield="position_name"; + +// Initialize technical objects +$object = new StockTransfer($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->stocktransfer->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('stocktransferdocument', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals + +//if ($id > 0 || ! empty($ref)) $upload_dir = $conf->stocktransfer->multidir_output[$object->entity?$object->entity:$conf->entity] . "/stocktransfer/" . dol_sanitizeFileName($object->id); +if ($id > 0 || !empty($ref)) $upload_dir = $conf->stocktransfer->multidir_output[$object->entity ? $object->entity : $conf->entity]."/stocktransfer/".dol_sanitizeFileName($object->ref); + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$result = restrictedArea($user, 'stocktransfer', $object->id); + +$permissiontoadd = $user->rights->stocktransfer->stocktransfer->write; // Used by the include of actions_addupdatedelete.inc.php + + + +/* + * Actions + */ + +include_once DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; + + +/* + * View + */ + +$form = new Form($db); + +$title = $langs->trans("ModuleStockTransferName").' - '.$langs->trans("Files"); +$help_url = ''; +//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +llxHeader('', $title, $help_url); + +if ($object->id) { + /* + * Show tabs + */ + $head = stocktransferPrepareHead($object); + + dol_fiche_head($head, 'document', $langs->trans("StockTransfer"), -1, $object->picto); + + + // Build file list + $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); + $totalsize = 0; + foreach ($filearray as $key => $file) { + $totalsize += $file['size']; + } + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + + print '
    '; + print ''; + + // Number of files + print ''; + + // Total size + print ''; + + print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '; + + print '
    '; + + dol_fiche_end(); + + $modulepart = 'stocktransfer'; + //$permission = $user->rights->stocktransfer->stocktransfer->write; + $permission = 1; + //$permtoedit = $user->rights->stocktransfer->stocktransfer->write; + $permtoedit = 1; + $param = '&id='.$object->id; + + //$relativepathwithnofile='stocktransfer/' . dol_sanitizeFileName($object->id).'/'; + $relativepathwithnofile = 'stocktransfer/'.dol_sanitizeFileName($object->ref).'/'; + + include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; +} else { + accessforbidden('', 0, 1); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/product/stock/stocktransfer/stocktransfer_list.php b/htdocs/product/stock/stocktransfer/stocktransfer_list.php new file mode 100644 index 00000000000..3ef27f37557 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/stocktransfer_list.php @@ -0,0 +1,572 @@ + + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 stocktransfer_list.php + * \ingroup stocktransfer + * \brief List page for stocktransfer + */ + +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value +//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', '1'); // The main.inc.php does not make a redirect if not logged, instead show simple error message +//if (! defined("XFRAMEOPTIONS_ALLOWALL")) define('XFRAMEOPTIONS_ALLOWALL', '1'); // Do not add the HTTP header 'X-Frame-Options: SAMEORIGIN' but 'X-Frame-Options: ALLOWALL' + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; +if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; + +// load stocktransfer libraries +require_once __DIR__.'/class/stocktransfer.class.php'; + +// for other modules +//dol_include_once('/othermodule/class/otherobject.class.php'); + +// Load translation files required by the page +$langs->loadLangs(array("stocks", "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') : 'stocktransferlist'; // 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', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object = new StockTransfer($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->stocktransfer->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('stocktransferlist')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); +//$extrafields->fetch_name_optionals_label($object->table_element_line); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) $sortfield = "t.".key($object->fields); // 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') ? trim(GETPOST('search_all', 'alphanohtml')) : trim(GETPOST('sall', 'alphanohtml')); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach ($object->fields as $key => $val) { + if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +} + +// Definition of fields for list +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>(verifCond($val['enabled']) && ($val['visible'] != 3)), 'position'=>$val['position']); +} +//var_dump($object->fields); +// Extra fields +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { + $arrayfields["ef.".$key] = array( + 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], + 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), + 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], + 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]), + 'langfile'=>$extrafields->attributes[$object->table_element]['langfile'][$key] + ); + } + } +} +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +$permissiontoread = $user->rights->stocktransfer->stocktransfer->read; +$permissiontoadd = $user->rights->stocktransfer->stocktransfer->write; +$permissiontodelete = $user->rights->stocktransfer->stocktransfer->delete; + +// Security check +if (empty($conf->stocktransfer->enabled)) accessforbidden('Module not enabled'); +$socid = 0; +if ($user->socid > 0) { // Protection if external user + //$socid = $user->socid; + accessforbidden(); +} +//$result = restrictedArea($user, 'stocktransfer', $id, ''); +if (!$permissiontoread) accessforbidden(); + + + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } + +$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'); + +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] = ''; + } + $toselect = ''; + $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 + } + + // Mass actions + $objectclass = 'StockTransfer'; + $objectlabel = 'StockTransfer'; + $uploaddir = $conf->stocktransfer->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + + +/* + * View + */ + +$form = new Form($db); + +$now = dol_now(); + +//$help_url="EN:Module_StockTransfer|FR:Module_StockTransfer_FR|ES:Módulo_StockTransfer"; +$help_url = ''; +$title = $langs->trans('StockTransferList'); + + +// Build and execute select +// -------------------------------------------------------------------- +$sql = 'SELECT '; +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." 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)"; +if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +else $sql .= " WHERE 1 = 1"; +foreach ($search as $key => $val) { + 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) { + if ($search[$key] == '-1') $search[$key] = ''; + $mode_search = 2; + } + if ($search[$key] != '') $sql .= natural_search($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; + +/* If a group by is required +$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); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql=preg_replace('/,\s*$/','', $sql); +*/ + +$sql .= $db->order($sortfield, $sortorder); + +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + $resql = $db->query($sql); + $nbtotalofrecords = $db->num_rows($resql); + if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0 + $page = 0; + $offset = 0; + } +} +// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { + $num = $nbtotalofrecords; +} else { + 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('/product/stock/stocktransfer/stocktransfer_card.php', 1).'?id='.$id); + exit; +} + + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $title, $help_url); + +// Example : Adding jquery code +print ''; + +$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) $param .= '&search_'.$key.'[]='.urlencode($skey); + else $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'; + +// List of mass actions available +$arrayofmassactions = array( + //'validate'=>$langs->trans("Validate"), + //'generate_doc'=>$langs->trans("ReGeneratePDF"), + //'builddoc'=>$langs->trans("PDFMerge"), + //'presend'=>$langs->trans("SendByMail"), +); +if ($permissiontodelete) $arrayofmassactions['predelete'] = ''.$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_buildpath('/product/stock/stocktransfer/stocktransfer_card.php', 1).'?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 = "SendStockTransferRef"; +$modelmail = "stocktransfer"; +$objecttmp = new StockTransfer($db); +$trackid = 'xxxx'.$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['css']) ? '' : $val['css']); + 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') $cssforfield .= ($cssforfield ? ' ' : '').'right'; + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// 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 ''."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['css']) ? '' : $val['css']); + 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') $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'; +// 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($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +print ''."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine = 0; +if (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(); +while ($i < ($limit ? min($num, $limit) : $num)) { + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen + + // Store properties in $object + $object->setVarsFromFetchObj($obj); + + // Show here line of result + print ''; + foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['css']) ? '' : $val['css']); + 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')) && $key != 'status') $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); + else { + print $object->showOutputField($val, $key, $object->$key, ''); + if ($key === 'date_prevue_depart' && $object->lead_time_for_warning > 0 && $object->$key > 0) { + $date_prevue_depart = $object->$key; + $date_prevue_depart_plus_delai = $date_prevue_depart; + if ($object->lead_time_for_warning > 0) $date_prevue_depart_plus_delai = strtotime(date('Y-m-d', $date_prevue_depart) . ' + '.$object->lead_time_for_warning.' day'); + if ($date_prevue_depart_plus_delai < strtotime(date('Y-m-d'))) print img_warning($langs->trans('Alert').' - '.$langs->trans('Late')); + } + } + print ''; + if (!$i) $totalarray['nbfield']++; + if (!empty($val['isameasure'])) { + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + $totalarray['val']['t.'.$key] += $object->$key; + } + } + } + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // 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 ''."\n"; + + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +// If no record found +if ($num == 0) { + $colspan = 1; + 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 (is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + elseif (strpos($val['type'], 'integer:') === 0) { + print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; + print ''; +$searchpicto = $form->showFilterButtons(); +print $searchpicto; +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 '
    '.$langs->trans("NoRecordFound").'
    '."\n"; +print '
    '."\n"; + +print '
    '."\n"; + +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_stocktransfer', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/product/stock/stocktransfer/stocktransfer_note.php b/htdocs/product/stock/stocktransfer/stocktransfer_note.php new file mode 100644 index 00000000000..51ad1c32df3 --- /dev/null +++ b/htdocs/product/stock/stocktransfer/stocktransfer_note.php @@ -0,0 +1,162 @@ + + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) ---Put here your own copyright and developer email--- + * + * 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 stocktransfer_note.php + * \ingroup stocktransfer + * \brief Car with notes on StockTransfer + */ + +// Load Dolibarr environment +$res = 0; +// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) +if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"; +// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME +$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; +while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } +if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1))."/main.inc.php"; +if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php"; +// Try main.inc.php using relative path +if (!$res && file_exists("../main.inc.php")) $res = @include "../main.inc.php"; +if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; +if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; +if (!$res) die("Include of main fails"); + +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/class/stocktransfer.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/stocktransfer/lib/stocktransfer_stocktransfer.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array("stocks", "companies")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object = new StockTransfer($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->stocktransfer->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('stocktransfernote', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Security check - Protection if external user +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$result = restrictedArea($user, 'stocktransfer', $id); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || !empty($ref)) $upload_dir = $conf->stocktransfer->multidir_output[$object->entity]."/".$object->id; + +$permissionnote = $user->rights->stocktransfer->stocktransfer->write; // Used by the include of actions_setnotes.inc.php +$permissiontoadd = $user->rights->stocktransfer->stocktransfer->write; // Used by the include of actions_addupdatedelete.inc.php + + + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + + +/* + * View + */ + +$form = new Form($db); + +//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; +$help_url = ''; +llxHeader('', $langs->trans('ModuleStockTransferName'), $help_url); + +if ($id > 0 || !empty($ref)) { + $object->fetch_thirdparty(); + + $head = stocktransferPrepareHead($object); + + dol_fiche_head($head, 'note', $langs->trans("StockTransfer"), -1, $object->picto); + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
    '; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
    '; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + + + $cssclass = "titlefield"; + include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; + + print '
    '; + + dol_fiche_end(); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php index c9cecd8dc6e..79152c6cfb9 100644 --- a/htdocs/projet/class/task.class.php +++ b/htdocs/projet/class/task.class.php @@ -481,7 +481,7 @@ class Task extends CommonObjectLine $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref); if (file_exists($olddir)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $res = dol_move($olddir, $newdir); + $res = dol_move_dir($olddir, $newdir); if (!$res) { $langs->load("errors"); $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir); diff --git a/htdocs/projet/tasks/task.php b/htdocs/projet/tasks/task.php index 0c323d5e058..9fce4072183 100644 --- a/htdocs/projet/tasks/task.php +++ b/htdocs/projet/tasks/task.php @@ -120,6 +120,8 @@ if ($action == 'update' && !GETPOST("cancel") && $user->rights->projet->creer) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'edit'; } + } else { + $action = 'edit'; } } else { $action = 'edit'; diff --git a/htdocs/recruitment/class/recruitmentcandidature.class.php b/htdocs/recruitment/class/recruitmentcandidature.class.php index 835cfe0b7cd..1b4074a6798 100644 --- a/htdocs/recruitment/class/recruitmentcandidature.class.php +++ b/htdocs/recruitment/class/recruitmentcandidature.class.php @@ -120,7 +120,7 @@ class RecruitmentCandidature extends CommonObject 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,), 'lastname' => array('type'=>'varchar(128)', 'label'=>'Lastname', 'enabled'=>'1', 'position'=>20, 'notnull'=>0, 'visible'=>1,), 'firstname' => array('type'=>'varchar(128)', 'label'=>'Firstname', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>1,), - 'email' => array('type'=>'varchar(255)', 'label'=>'EMail', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'picto'=>'email'), + 'email' => array('type'=>'email', 'label'=>'EMail', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'picto'=>'email', 'csslist'=>'tdoverflowmax200'), 'phone' => array('type'=>'phone', 'label'=>'Phone', 'enabled'=>'1', 'position'=>31, 'notnull'=>0, 'visible'=>1, 'picto'=>'phone'), 'date_birth' => array('type'=>'date', 'label'=>'DateOfBirth', 'enabled'=>'1', 'position'=>70, 'visible'=>-1,), 'email_msgid' => array('type'=>'varchar(255)', 'label'=>'EmailMsgID', 'visible'=>-2, 'enabled'=>1, 'position'=>540, 'notnull'=>-1, 'help'=>'EmailMsgIDDesc'), diff --git a/htdocs/recruitment/recruitmentcandidature_list.php b/htdocs/recruitment/recruitmentcandidature_list.php index 4ce262c8c92..9a0a21484b1 100644 --- a/htdocs/recruitment/recruitmentcandidature_list.php +++ b/htdocs/recruitment/recruitmentcandidature_list.php @@ -30,11 +30,11 @@ //if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on). //if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) //if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data -//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip //if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu //if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php //if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library //if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip //if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value //if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler //if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', '1'); // The main.inc.php does not make a redirect if not logged, instead show simple error message @@ -129,11 +129,11 @@ $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, 1, '1'); + $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, 1, '1')), + 'enabled'=>(abs($visible) != 3 && dol_eval($val['enabled'], 1)), 'position'=>$val['position'], 'help'=> isset($val['help']) ? $val['help'] : '' ); @@ -318,7 +318,7 @@ if (! empty($extrafields->attributes[$object->table_element]['label'])) { } // Add where from hooks $parameters=array(); -$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters); // Note that $action and $object may have been modified by hook +$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); */ @@ -326,8 +326,15 @@ $sql = preg_replace('/,\s*$/', '', $sql); // Count total nb of records $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $resql = $db->query($sql); - $nbtotalofrecords = $db->num_rows($resql); + /* The fast and low memory method to get and count full list converts the sql into a sql count */ + $sqlforcount = preg_replace('/^SELECT[a-zA-Z0-9\._\s\(\),=<>\:\-\']+\sFROM/', 'SELECT COUNT(*) as nbtotalofrecords FROM', $sql); + $resql = $db->query($sqlforcount); + if ($resql) { + $objforcount = $db->fetch_object($resql); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + } else { + dol_print_error($db); + } if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0 $page = 0; @@ -543,7 +550,7 @@ $arrayofmassactions = array( //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"), //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"), ); -if ($permissiontodelete) { +if (!empty($permissiontodelete)) { $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); } if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { @@ -560,12 +567,17 @@ print ''; print ''; print ''; -//print ''; +print ''; print ''; print ''; print ''; -$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.((int) $id)), '', $permissiontoadd); + +$newcardbutton = ''; +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); +$newcardbutton .= dolGetButtonTitleSeparator(); +$newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/recruitment/recruitmentcandidature_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.((int) $id)), '', $permissiontoadd); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -577,10 +589,13 @@ $trackid = 'recruitmentapplication'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($search_all) { + $setupstring = ''; foreach ($fieldstosearchall as $key => $val) { $fieldstosearchall[$key] = $langs->trans($val); + $setupstring .= $key."=".$val.";"; } - print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; + print ''."\n"; + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '."\n"; } $moreforfilter = ''; @@ -603,7 +618,7 @@ if (!empty($moreforfilter)) { } $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; -$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN', '')); // 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 @@ -613,8 +628,16 @@ print ''; +// Action column +if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print ''; +} foreach ($object->fields as $key => $val) { - $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + $searchkey = empty($search[$key]) ? '' : $search[$key]; + $cssforfield = (empty($val['css']) ? '' : $val['css']); if ($key == 'status') { $cssforfield .= ($cssforfield ? ' ' : '').'center'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { @@ -655,10 +678,12 @@ $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 ''; +if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print ''; +} print ''."\n"; $totalarray = array(); @@ -667,6 +692,9 @@ $totalarray['nbfield'] = 0; // Fields title label // -------------------------------------------------------------------- print ''; +if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +} foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); if ($key == 'status') { @@ -675,21 +703,25 @@ foreach ($object->fields as $key => $val) { $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') { + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { $cssforfield .= ($cssforfield ? ' ' : '').'right'; } + $cssforfield = preg_replace('/small\s*/', '', $cssforfield); // the 'small' css must not be used for the title label 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"; + $totalarray['nbfield']++; } } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields -$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder, 'totalarray'=>&$totalarray); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column -print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + print getTitleFieldOfList(($mode != 'kanban' ? $selectedfields : ''), 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; +} $totalarray['nbfield']++; print ''."\n"; @@ -735,7 +767,19 @@ while ($i < $imaxinloop) { } else { // Show here line of result $j = 0; - print ''; + print ''; + // Action column + if (!empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + 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'))) { @@ -756,7 +800,11 @@ while ($i < $imaxinloop) { //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; if (!empty($arrayfields['t.'.$key]['checked'])) { - print ''; + print ''; if ($key == 'status') { print $object->getLibStatut(5); } elseif ($key == 'rowid') { @@ -789,15 +837,17 @@ while ($i < $imaxinloop) { $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action column - print ''; } - print ''; if (!$i) { $totalarray['nbfield']++; } @@ -826,7 +876,7 @@ if ($num == 0) { $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 +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print '
    '; + $searchpicto = $form->showFilterButtons('left'); + print $searchpicto; + print ''; -$searchpicto = $form->showFilterButtons(); -print $searchpicto; -print ''; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + 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 ($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; + if (empty($conf->global->MAIN_CHECKBOX_LEFT_COLUMN)) { + 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 ''; + print '
    '."\n"; diff --git a/htdocs/recruitment/recruitmentjobposition_list.php b/htdocs/recruitment/recruitmentjobposition_list.php index cf4bdddb63d..4f63434f9cf 100644 --- a/htdocs/recruitment/recruitmentjobposition_list.php +++ b/htdocs/recruitment/recruitmentjobposition_list.php @@ -427,8 +427,8 @@ print ''; print ''; $newcardbutton = ''; -$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/^&mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); $newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/^&mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/^&mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); $newcardbutton .= dolGetButtonTitleSeparator(); $newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/recruitment/recruitmentjobposition_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index e546986ba98..d76b090d839 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -2741,13 +2741,6 @@ class Societe extends CommonObject if (in_array($target, $target_value)) { $linkclose .= ' target="'.dol_escape_htmltag($target).'"'; } - - /* - $hookmanager->initHooks(array('thirdpartydao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } $linkstart .= $linkclose.'>'; $linkend = ''; diff --git a/htdocs/societe/index.php b/htdocs/societe/index.php index 8cae5ef49f8..597fc4b80ea 100644 --- a/htdocs/societe/index.php +++ b/htdocs/societe/index.php @@ -177,7 +177,8 @@ if (!empty($conf->use_javascript_ajax) && ((round($third['prospect']) ? 1 : 0) + $statstring .= ''.$langs->trans("Customers").''.round($third['customer']).''; $statstring .= ""; } - if ((($conf->fournisseur->enabled && $user->rights->fournisseur->facture->lire && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || (!empty($conf->supplier_order->enabled) && $user->rights->supplier_order->lire) || (!empty($conf->supplier_invoice->enabled) && $user->rights->supplier_invoice->lire)) && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS)) { + $statstring2 = ''; + if (((!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || (!empty($conf->supplier_order->enabled) && $user->rights->supplier_order->lire) || (!empty($conf->supplier_invoice->enabled) && $user->rights->supplier_invoice->lire)) && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS)) { $statstring2 = ""; $statstring2 .= ''.$langs->trans("Suppliers").''.round($third['supplier']).''; $statstring2 .= ""; diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index df54da4132c..5f11b6e3c02 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -321,8 +321,20 @@ if (empty($reshook)) { if (!$error) { if ($origin && $originid) { - $element = 'supplier_proposal'; - $subelement = 'supplier_proposal'; + $element = $subelement = $origin; + if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { + $element = $regs[1]; + $subelement = $regs[2]; + } + + // For compatibility + if ($element == 'order') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; + $subelement = 'propal'; + } $object->origin = $origin; $object->origin_id = $originid; @@ -1138,8 +1150,20 @@ if ($action == 'create') { // Load objectsrc if (!empty($origin) && !empty($originid)) { - $element = 'supplier_proposal'; - $subelement = 'supplier_proposal'; + $element = $subelement = GETPOST('origin'); + if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) { + $element = $regs[1]; + $subelement = $regs[2]; + } + + // For compatibility + if ($element == 'order' || $element == 'commande') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; + $subelement = 'propal'; + } dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); diff --git a/htdocs/takepos/invoice.php b/htdocs/takepos/invoice.php index 9f22cc20b40..586cdcfcd56 100644 --- a/htdocs/takepos/invoice.php +++ b/htdocs/takepos/invoice.php @@ -913,7 +913,7 @@ if (empty($reshook)) { $sectionwithinvoicelink .= ' '; } - if ($remaintopay <= 0 && getDolGlobalString('TAKEPOS_AUTO_PRINT_TICKETS')) { + if ($remaintopay <= 0 && getDolGlobalString('TAKEPOS_AUTO_PRINT_TICKETS') && $action != "history") { $sectionwithinvoicelink .= ''; } } diff --git a/htdocs/theme/eldy/global.inc.php b/htdocs/theme/eldy/global.inc.php index 9eb615d2355..34a7f8f87f3 100644 --- a/htdocs/theme/eldy/global.inc.php +++ b/htdocs/theme/eldy/global.inc.php @@ -7631,6 +7631,11 @@ if (!empty($conf->global->THEME_CUSTOM_CSS)) { ?> + div.extra_inline_chkbxlst, + div.extra_inline_checkbox { + min-width:150px; + } + /* Must be at end */ div.flot-text .flot-tick-label .tickLabel, .fa-color-unset { color: unset; diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php index 73337ba0284..298b8b5c46a 100644 --- a/htdocs/theme/md/style.css.php +++ b/htdocs/theme/md/style.css.php @@ -488,7 +488,7 @@ section.setupsection { border-radius: 5px; } -.field-error-icon { color: #ea1212; !important; } +.field-error-icon { color: #ea1212 !important; } textarea { border-radius: 0; @@ -3570,7 +3570,7 @@ td.border, div.tagtable div div.border { left: 0; top: 0; max-width: 150px !important; - //background-color: inherit; + /*background-color: inherit;*/ background-color: gainsboro; z-index: 2; } @@ -3583,7 +3583,7 @@ td.border, div.tagtable div div.border { right: 0; top: 0; max-width: 150px !important; - //background-color: inherit; + /*background-color: inherit;*/ background-color: gainsboro; z-index: 2; } @@ -4164,7 +4164,7 @@ tr.liste_sub_total, tr.liste_sub_total td { } .paymenttable tr td:first-child, .margintable tr td:first-child { - //padding-left: 2px; + /*padding-left: 2px;*/ } .paymenttable, .margintable tr td { height: 22px; @@ -7320,3 +7320,4 @@ if (is_object($db)) { div.flot-text .flot-tick-label .tickLabel, .fa-color-unset { color: unset; } + diff --git a/htdocs/user/card.php b/htdocs/user/card.php index 821d6748eb6..f0b362b383e 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -333,18 +333,26 @@ if (empty($reshook)) { $id = $object->create($user); if ($id > 0) { + $resPass = 0; if (GETPOST('password', 'none')) { - $object->setPassword($user, GETPOST('password', 'none')); + $resPass = $object->setPassword($user, GETPOST('password', 'none')); } - if (!empty($conf->categorie->enabled)) { - // Categories association - $usercats = GETPOST('usercats', 'array'); - $object->setCategories($usercats); - } - $db->commit(); + if ($resPass < 0) { + $langs->load("errors"); + $db->rollback(); + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; // Go back to create page + } else { + if (! empty($conf->categorie->enabled)) { + // Categories association + $usercats = GETPOST('usercats', 'array'); + $object->setCategories($usercats); + } + $db->commit(); - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); - exit; + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); + exit; + } } else { $langs->load("errors"); $db->rollback(); diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index cb76b25cc5a..45610d7b8dc 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -2805,13 +2805,6 @@ class User extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('userdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } $linkstart .= $linkclose.'>'; diff --git a/htdocs/user/class/usergroup.class.php b/htdocs/user/class/usergroup.class.php index 5c83e8ce94c..41ac859f558 100644 --- a/htdocs/user/class/usergroup.class.php +++ b/htdocs/user/class/usergroup.class.php @@ -761,13 +761,6 @@ class UserGroup extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('groupdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } $linkstart = 'rights->user->user->lire && !$user->admin) { - accessforbidden(); -} - // Load translation files required by page $langs->loadLangs(array('users', 'companies')); @@ -51,7 +47,6 @@ $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("pa // Load mode employee $mode = GETPOST("mode", 'alpha'); -$userstatic = new User($db); $search_statut = GETPOST('search_statut', 'int'); if ($search_statut == '' || $search_statut == '0') { @@ -62,9 +57,16 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', $search_statut = ""; } +$userstatic = new User($db); + // Define value to know what current user can do on users $canadduser = (!empty($user->admin) || $user->rights->user->user->creer); +if (!$user->rights->user->user->lire && !$user->admin) { + accessforbidden(); +} + +$childids = $user->getAllChildIds(1); /* @@ -73,19 +75,25 @@ $canadduser = (!empty($user->admin) || $user->rights->user->user->creer); $form = new Form($db); -$title = $langs->trans("Users").' - '.$langs->trans("HierarchicView"); +$help_url = 'EN:Module_Users|FR:Module_Utilisateurs|ES:Módulo_Usuarios|DE:Modul_Benutzer'; +$title = $langs->trans("Users"); $arrayofjs = array( '/includes/jquery/plugins/jquerytreeview/jquery.treeview.js', '/includes/jquery/plugins/jquerytreeview/lib/jquery.cookie.js', ); $arrayofcss = array('/includes/jquery/plugins/jquerytreeview/jquery.treeview.css'); -llxHeader('', $title, '', '', 0, 0, $arrayofjs, $arrayofcss, '', 'bodyforlist'); +llxHeader('', $title, $help_url, '', 0, 0, $arrayofjs, $arrayofcss, '', 'bodyforlist'); // Load hierarchy of users $user_arbo = $userstatic->get_full_tree(0, ($search_statut != '' && $search_statut >= 0) ? "statut = ".$search_statut : ''); + +// Count total nb of records +$nbtotalofrecords = count($user_arbo); + + if (!is_array($user_arbo) && $user_arbo < 0) { setEventMessages($userstatic->error, $userstatic->errors, 'warnings'); } else { @@ -142,12 +150,12 @@ if (!is_array($user_arbo) && $user_arbo < 0) { //var_dump($data); - $param = "search_statut=".urlencode($search_statut); + $param = "&search_statut=".urlencode($search_statut); $newcardbutton = ''; - $newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', DOL_URL_ROOT.'/user/list.php?mode=kanban'.(($search_statut != '' && $search_statut >= 0) ? '&search_statut='.$search_statut : '').preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); - $newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars paddingleft imgforviewmode', DOL_URL_ROOT.'/user/list.php?mode=common'.(($search_statut != '' && $search_statut >= 0) ? '&search_statut='.$search_statut : '').preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); - $newcardbutton .= dolGetButtonTitle($langs->trans('HierarchicView'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/user/hierarchy.php?mode=hierarchy'.(($search_statut != '' && $search_statut >= 0) ? '&search_statut='.$search_statut : '').preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', (($mode == 'hierarchy') ? 2 : 1), array('morecss'=>'reposition')); + $newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars paddingleft imgforviewmode', DOL_URL_ROOT.'/user/list.php?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); + $newcardbutton .= dolGetButtonTitle($langs->trans('HierarchicView'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/user/hierarchy.php?mode=hierarchy'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', (($mode == 'hierarchy') ? 2 : 1), array('morecss'=>'reposition')); + $newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', DOL_URL_ROOT.'/user/list.php?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); $newcardbutton .= dolGetButtonTitleSeparator(); $newcardbutton .= dolGetButtonTitle($langs->trans('NewUser'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/user/card.php?action=create'.($mode == 'employee' ? '&employee=1' : '').'&leftmenu=', '', $canadduser); @@ -155,18 +163,19 @@ if (!is_array($user_arbo) && $user_arbo < 0) { $num = 0; $limit = 0; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, '', 'user', 0, $newcardbutton, '', $limit, 0, 0, 1); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'user', 0, $newcardbutton, '', $limit, 0, 0, 1); print '
    '."\n"; if ($optioncss != '') { print ''; } print ''; + print ''; print ''; print ''; print ''; - print ''; print ''; + print ''; print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; diff --git a/htdocs/user/list.php b/htdocs/user/list.php index 0dc3317b1ef..3c97a7f7298 100644 --- a/htdocs/user/list.php +++ b/htdocs/user/list.php @@ -562,7 +562,7 @@ if ($search_api_key != '') { if ($search_supervisor > 0) { $param .= "&search_supervisor=".urlencode($search_supervisor); } -if ($search_statut != '' && $search_statut >= 0) { +if ($search_statut != '') { $param .= "&search_statut=".urlencode($search_statut); } if ($optioncss != '') { @@ -613,9 +613,9 @@ if (!empty($socid)) { } $newcardbutton = ''; +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars paddingleft imgforviewmode', DOL_URL_ROOT.'/user/list.php?mode=common'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); +$newcardbutton .= dolGetButtonTitle($langs->trans('HierarchicView'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/user/hierarchy.php?mode=hierarchy'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', (($mode == 'hierarchy') ? 2 : 1), array('morecss'=>'reposition')); $newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss'=>'reposition')); -$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars paddingleft imgforviewmode', DOL_URL_ROOT.'/user/list.php?mode=common'.(($search_statut != '' && $search_statut >= 0) ? '&search_statut='.$search_statut : '').preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss'=>'reposition')); -$newcardbutton .= dolGetButtonTitle($langs->trans('HierarchicView'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/user/hierarchy.php?mode=hierarchy'.(($search_statut != '' && $search_statut >= 0) ? '&search_statut='.$search_statut : '').preg_replace('/(&|\?)*mode=[^&]+/', '', $param), '', (($mode == 'hierarchy') ? 2 : 1), array('morecss'=>'reposition')); $newcardbutton .= dolGetButtonTitleSeparator(); $newcardbutton .= dolGetButtonTitle($langs->trans('NewUser'), '', 'fa fa-plus-circle', $url, '', $permissiontoadd); diff --git a/htdocs/zapier/class/hook.class.php b/htdocs/zapier/class/hook.class.php index e27658838bd..d2e656d15f1 100644 --- a/htdocs/zapier/class/hook.class.php +++ b/htdocs/zapier/class/hook.class.php @@ -537,13 +537,6 @@ class Hook extends CommonObject } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - - /* - $hookmanager->initHooks(array('hookdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ } else { $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } diff --git a/test/phpunit/FunctionsLibTest.php b/test/phpunit/FunctionsLibTest.php index 1bf3b6378fb..82205369c86 100644 --- a/test/phpunit/FunctionsLibTest.php +++ b/test/phpunit/FunctionsLibTest.php @@ -166,6 +166,26 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase print __METHOD__."\n"; } + /** + * testNum2Alpha + * + * @return void + */ + public function testNum2Alpha() + { + $result = num2Alpha(0); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($result, 'A', 'Check num2Alpha 0'); + + $result = num2Alpha(5); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($result, 'F', 'Check num2Alpha 5'); + + $result = num2Alpha(26); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($result, 'AA', 'Check num2Alpha 26'); + } + /** * testIsValidEmail *