diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 0d2c67e..0000000 --- a/.gitattributes +++ /dev/null @@ -1,23 +0,0 @@ -# Set default behaviour, in case users don't have core.autocrlf set. -* text=auto - - -# Explicitly declare text files we want to always be normalized and converted -# to native line endings on checkout. -*.php text eol=lf -*.sql text eol=lf -*.htm text eol=lf -*.html text eol=lf -*.js text eol=lf -*.css text eol=lf -*.lang text eol=lf -*.txt text eol=lf -*.md text eol=lf -*.bat text eol=lf - -# Denote all files that are truly binary and should not be modified. -*.ico binary -*.png binary -*.jpg binary -*.odt binary -*.odf binary diff --git a/.gitignore b/.gitignore index 0798bd0..7558968 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,23 @@ +# Generated binaries +/build/*.zip +/bin/*.zip +# Doxygen generated documentation +/build/doxygen/doxygen_warnings.log +/doc/code/doxygen +# Composer managed dependencies +/vendor +/dev/bin +# PHPdocumentor generated files +/build/phpdoc +/doc/code/phpdoc +# Sphinx generated files +/doc/user/build +/.settings/ +/.buildpath +/.project +# Other +*.back +/.editorconfig +/.gitattributes node_modules -npm-debug.log -.idea -vendor -.editorconfig -.gitattributes package-lock.json diff --git a/.tx/config b/.tx/config deleted file mode 100644 index 1743c5d..0000000 --- a/.tx/config +++ /dev/null @@ -1,9 +0,0 @@ -[main] -host = https://www.transifex.com -lang_map = uz: uz_UZ - -[mymodule.mymodule] -file_filter = langs//mymodule.lang -source_file = langs/en_US/mymodule.lang -source_lang = en_US -type = MOZILLAPROPERTIES diff --git a/.tx/index.php b/.tx/index.php deleted file mode 100644 index cd6990e..0000000 --- a/.tx/index.php +++ /dev/null @@ -1,2 +0,0 @@ - - * Copyright (C) 2022 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 dolicar/admin/about.php - * \ingroup dolicar - * \brief About page of module DoliCar. - */ - -// Load DoliCar environment -if (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; -} elseif (file_exists('../../dolicar.main.inc.php')) { - require_once __DIR__ . '/../../dolicar.main.inc.php'; -} else { - die('Include of dolicar main fails'); -} - -// Libraries -require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -require_once '../lib/dolicar.lib.php'; - -// Global variables definitions -global $conf, $db, $langs, $user; - -// Translations -saturne_load_langs(['admin', 'categories']); - -// Access control -$permissiontoread = $user->rights->dolicar->adminpage->read; -saturne_check_access($permissiontoread); - -// Parameters -$action = GETPOST('action', 'aZ09'); -$backtopage = GETPOST('backtopage', 'alpha'); - - -/* - * Actions - */ - -// None - - -/* - * View - */ - -$form = new Form($db); - -$help_url = ''; -$page_name = $langs->transnoentities('DolicarSetup'); - -saturne_header(0, '', $langs->trans($page_name), $help_url); - -// Subheader -$linkback = ''.$langs->trans("BackToModuleList").''; - -print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); - -// Configuration header -$head = dolicar_admin_prepare_head(); -print dol_get_fiche_head($head, 'about', $langs->trans($page_name), 0, 'dolicar_color@dolicar'); - -require_once __DIR__ . '/../core/modules/modDoliCar.class.php'; -$tmpmodule = new modDoliCar($db); -print $tmpmodule->getDescLong(); - -// Page end -print dol_get_fiche_end(); -llxFooter(); -$db->close(); diff --git a/admin/quickcreation.php b/admin/quickcreation.php index b5c4137..c8ef0ba 100644 --- a/admin/quickcreation.php +++ b/admin/quickcreation.php @@ -1,6 +1,5 @@ - * Copyright (C) 2022 SuperAdmin +/* Copyright (C) 2023-2024 EVARISK * * 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 @@ -17,82 +16,57 @@ */ /** - * \file dolicar/admin/setup.php + * \file dolicar/admin/quickcreation.php * \ingroup dolicar - * \brief DoliCar setup page. + * \brief DoliCar quickcreation config page */ // Load DoliCar environment if (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; + require_once __DIR__ . '/../dolicar.main.inc.php'; } elseif (file_exists('../../dolicar.main.inc.php')) { - require_once __DIR__ . '/../../dolicar.main.inc.php'; + require_once __DIR__ . '/../../dolicar.main.inc.php'; } else { - die('Include of dolicar main fails'); + die('Include of dolicar main fails'); } -// Global variables definitions -global $conf, $db, $langs, $user; - -// Libraries -require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; - +// Load DoliCar libraries require_once __DIR__ . '/../lib/dolicar.lib.php'; -require_once __DIR__ . '/../lib/dolicar_functions.lib.php'; -require_once __DIR__ . '/../lib/dolicar_registrationcertificatefr.lib.php'; -//require_once "../class/myclass.class.php"; - -// Translations -saturne_load_langs(['admin', 'categories']); - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('dolicarsetup', 'globalsetup')); - -// Access control -$permissiontoread = $user->rights->dolicar->adminpage->read; -saturne_check_access($permissiontoread); -// Parameters -$action = GETPOST('action', 'aZ09'); -$backtopage = GETPOST('backtopage', 'alpha'); -$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php +// Global variables definitions +global $conf, $db, $langs, $user; -/* - * Actions - */ +// Load translation files required by the page +saturne_load_langs(); -include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; +// Security check - Protection if external user +$permissionToRead = $user->rights->dolicar->adminpage->read && isModEnabled('easycrm'); +saturne_check_access($permissionToRead); /* * View */ -$form = new Form($db); - -$help_url = ''; -$page_name = $langs->transnoentities('DolicarSetup'); +$title = $langs->trans('ModuleSetup', 'DoliCar'); +$helpUrl = 'FR:Module_DoliCar'; -saturne_header(0, '', $langs->trans($page_name), $help_url); +saturne_header(0, '', $title, $helpUrl); // Subheader -$linkback = ''.$langs->trans("BackToModuleList").''; +$linkBack = '' . $langs->trans('BackToModuleList') . ''; -print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); +print load_fiche_titre($title, $linkBack, 'title_setup'); // Configuration header $head = dolicar_admin_prepare_head(); -print dol_get_fiche_head($head, 'quickcreation', $langs->trans($page_name), -1, "dolicar_color@dolicar"); +print dol_get_fiche_head($head, 'quickcreation', $title, -1, 'dolicar_color@dolicar'); -print load_fiche_titre($langs->transnoentities("QuickCreationConfiguration"), '', ''); +print load_fiche_titre($langs->transnoentities('Config'), '', ''); -print '
'; -print '
'; -print ''; -print ''; print ''; print ''; -print ''; -print ''; +print ''; +print ''; print ''; print ''; @@ -124,11 +98,8 @@ print ''; print '
' . $langs->transnoentities("Parameters") . '' . $langs->transnoentities("Value") . '' . $langs->transnoentities('Parameters') . '' . $langs->transnoentities('Status') . '
'; -print '
'; -print '
'; // Page end print dol_get_fiche_end(); - llxFooter(); $db->close(); diff --git a/admin/registrationcertificate.php b/admin/registrationcertificate.php index 6496564..1d8e508 100644 --- a/admin/registrationcertificate.php +++ b/admin/registrationcertificate.php @@ -1,6 +1,5 @@ - * Copyright (C) 2022 SuperAdmin +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ -19,135 +18,119 @@ /** * \file dolicar/admin/setup.php * \ingroup dolicar - * \brief DoliCar setup page. + * \brief DoliCar registration certificate config page */ // Load DoliCar environment if (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; + require_once __DIR__ . '/../dolicar.main.inc.php'; } elseif (file_exists('../../dolicar.main.inc.php')) { - require_once __DIR__ . '/../../dolicar.main.inc.php'; + require_once __DIR__ . '/../../dolicar.main.inc.php'; } else { - die('Include of dolicar main fails'); + die('Include of dolicar main fails'); } -// Global variables definitions -global $conf, $db, $langs, $user; - -// Libraries -require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; - +// Load DoliCar libraries require_once __DIR__ . '/../lib/dolicar.lib.php'; -require_once __DIR__ . '/../lib/dolicar_functions.lib.php'; require_once __DIR__ . '/../lib/dolicar_registrationcertificatefr.lib.php'; -//require_once "../class/myclass.class.php"; +require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; -// Translations -saturne_load_langs(['admin', 'categories']); +// Global variables definitions +global $conf, $db, $langs, $user; -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('dolicarsetup', 'globalsetup')); +// Load translation files required by the page +saturne_load_langs(); -// Access control -$permissiontoread = $user->rights->dolicar->adminpage->read; -saturne_check_access($permissiontoread); +// Initialize technical objects +$object = new RegistrationCertificateFr($db); -// Parameters -$action = GETPOST('action', 'aZ09'); -$backtopage = GETPOST('backtopage', 'alpha'); +// Initialize view objects +$form = new Form($db); +// Security check - Protection if external user +$permissionToRead = $user->rights->dolicar->adminpage->read; +saturne_check_access($permissionToRead); /* * View */ -$form = new Form($db); - -$help_url = ''; -$page_name = $langs->transnoentities('DolicarSetup'); +$title = $langs->trans('ModuleSetup', 'DoliCar'); +$helpUrl = 'FR:Module_DoliCar'; -saturne_header(0, '', $langs->trans($page_name), $help_url); +saturne_header(0, '', $title, $helpUrl); // Subheader -$linkback = ''.$langs->trans("BackToModuleList").''; +$linkBack = '' . $langs->trans('BackToModuleList') . ''; -print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); +print load_fiche_titre($title, $linkBack, 'title_setup'); // Configuration header $head = dolicar_admin_prepare_head(); -print dol_get_fiche_head($head, 'registrationcertificate', $langs->trans($page_name), -1, "dolicar_color@dolicar"); +print dol_get_fiche_head($head, 'registrationcertificate', $title, -1, 'dolicar_color@dolicar'); -print load_fiche_titre($langs->transnoentities("ImmatriculationAPIConfig"), '', ''); +print load_fiche_titre($langs->transnoentities('ImmatriculationAPIConfig'), '', ''); print ''; print ''; -print ''; -print ''; +print ''; +print ''; print ''; print ''; print ''; print ''; print ''; print '
' . $langs->transnoentities("Parameters") . '' . $langs->transnoentities("Value") . '' . $langs->transnoentities('Parameters') . '' . $langs->transnoentities('Value') . '
' . $langs->transnoentities('RemainingRequests') . ''; -print '' . ($conf->global->DOLICAR_API_REMAINING_REQUESTS_COUNTER ?? 0) . ''; +print '' . (getDolGlobalInt('DOLICAR_API_REMAINING_REQUESTS_COUNTER') ?? 0) . ''; print '
'; -print load_fiche_titre($langs->transnoentities("RegistrationCertificateFieldsConfig"), '', ''); +print load_fiche_titre($langs->transnoentities('RegistrationCertificateFieldsConfig'), '', ''); -print '
'; print ''; print ''; -print ''; -print ''; -print ''; +print ''; +print ''; +print ''; print ''; -$registrationCertificateFields = get_registration_certificate_fields(); - -if (is_array($registrationCertificateFields) && !empty($registrationCertificateFields)) { - foreach ($registrationCertificateFields as $registrationCertificateCode => $registrationCertificateField) { - print ''; - print ''; - print ''; - print ''; - } +foreach ($object->fields as $registrationCertificateCode => $registrationCertificateField) { + if ($registrationCertificateField['config'] == 1) { + print ''; + print ''; + print ''; + print ''; + } } print '
' . $langs->transnoentities("Parameters") . '' . $langs->transnoentities("Visible") . '' . $langs->transnoentities("ShortInfo") . '' . $langs->transnoentities('Parameters') . '' . $langs->transnoentities('Status') . '' . $langs->transnoentities('ShortInfo') . '
' . $langs->transnoentities('Display') . ' ' . $langs->transnoentities($registrationCertificateField) . ''; - print ajax_constantonoff('DOLICAR_' . $registrationCertificateCode . '_VISIBLE'); - print ''; - print $form->textwithpicto('', $langs->transnoentities('ShowRegistrationCertificateFieldHelp')); - print '
' . $langs->transnoentities('Display') . ' ' . $langs->transnoentities($registrationCertificateField['label']) . ''; + print ajax_constantonoff('DOLICAR_' . dol_strtoupper($registrationCertificateCode) . '_VISIBLE'); + print ''; + print $form->textwithpicto('', $langs->transnoentities('ShowRegistrationCertificateFieldHelp')); + print '
'; -print '
'; -print load_fiche_titre($langs->trans("ProductBatch"), '', ''); +print load_fiche_titre($langs->trans('Config'), '', ''); -print '
'; print ''; print ''; -print ''; -print ''; -print ''; +print ''; +print ''; +print ''; print ''; -// Show logo for company -print ''; -print ''; +print ''; print ''; print ''; -print ''; print '
' . $langs->trans("Parameters") . '' . $langs->trans("ShortInfo") . '' . $langs->trans("Status") . '' . $langs->trans('Parameters') . '' . $langs->trans('Description') . '' . $langs->trans('Status') . '
' . $langs->trans("HideObjectDetsDolicarDetails") . ''; -print $langs->trans("HideObjectDetsDolicarDetailsDescription"); +print '
' . $langs->trans('HideObjectDetsDolicarDetails') . ''; +print $langs->trans('HideObjectDetsDolicarDetailsDescription'); print ''; print ajax_constantonoff('DOLICAR_HIDE_OBJECT_DET_DOLICAR_DETAILS'); print '
'; -print '
'; // Page end print dol_get_fiche_end(); - llxFooter(); $db->close(); diff --git a/admin/setup.php b/admin/setup.php index a241361..5df13a8 100644 --- a/admin/setup.php +++ b/admin/setup.php @@ -1,6 +1,5 @@ - * Copyright (C) 2022 SuperAdmin +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ -19,174 +18,56 @@ /** * \file dolicar/admin/setup.php * \ingroup dolicar - * \brief DoliCar setup page. + * \brief DoliCar setup page */ // Load DoliCar environment if (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; + require_once __DIR__ . '/../dolicar.main.inc.php'; } elseif (file_exists('../../dolicar.main.inc.php')) { - require_once __DIR__ . '/../../dolicar.main.inc.php'; + require_once __DIR__ . '/../../dolicar.main.inc.php'; } else { - die('Include of dolicar main fails'); + die('Include of dolicar main fails'); } -// Libraries -require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php"; -require_once '../lib/dolicar.lib.php'; +// Load DoliCar libraries +require_once __DIR__ . '/../lib/dolicar.lib.php'; // Global variables definitions global $conf, $db, $langs, $user; -// Translations -saturne_load_langs(['admin', 'categories']); - -// Access control -$permissiontoread = $user->rights->dolicar->adminpage->read; -saturne_check_access($permissiontoread); - -// Parameters -$action = GETPOST('action', 'aZ09'); -$backtopage = GETPOST('backtopage', 'alpha'); -$modulepart = GETPOST('modulepart', 'aZ09'); // Used by actions_setmoduleoptions.inc.php - -$value = GETPOST('value', 'alpha'); -$label = GETPOST('label', 'alpha'); -$scandir = GETPOST('scan_dir', 'alpha'); - -/* - * Actions - */ - -include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; - -if ($action == 'updateMask') { - $maskconst = GETPOST('maskconst', 'alpha'); - $maskvalue = GETPOST('maskvalue', 'alpha'); - - if ($maskconst) { - $res = dolibarr_set_const($db, $maskconst, $maskvalue, '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 = GETPOST('object'); - - $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/dolicar/doc/pdf_".$modele."_".strtolower($tmpobjectkey).".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 == 'setmod') { - // TODO Check if numbering module chosen can be activated by calling method canBeActivated - $tmpobjectkey = GETPOST('object'); - if (!empty($tmpobjectkey)) { - $constforval = 'DOLICAR_'.strtoupper($tmpobjectkey)."_ADDON"; - dolibarr_set_const($db, $constforval, $value, 'chaine', 0, '', $conf->entity); - } -} elseif ($action == 'set') { - // Activate a model - $ret = addDocumentModel($value, $type, $label, $scandir); -} elseif ($action == 'del') { - $ret = delDocumentModel($value, $type); - if ($ret > 0) { - $tmpobjectkey = GETPOST('object'); - if (!empty($tmpobjectkey)) { - $constforval = 'DOLICAR_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { - dolibarr_del_const($db, $constforval, $conf->entity); - } - } - } -} elseif ($action == 'setdoc') { - // Set or unset default model - $tmpobjectkey = GETPOST('object'); - if (!empty($tmpobjectkey)) { - $constforval = 'DOLICAR_'.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; - } - - // We disable/enable the document template (into llx_document_model table) - $ret = delDocumentModel($value, $type); - if ($ret > 0) { - $ret = addDocumentModel($value, $type, $label, $scandir); - } - } -} elseif ($action == 'unsetdoc') { - $tmpobjectkey = GETPOST('object'); - if (!empty($tmpobjectkey)) { - $constforval = 'DOLICAR_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - dolibarr_del_const($db, $constforval, $conf->entity); - } -} - +// Load translation files required by the page +saturne_load_langs(); +// Security check - Protection if external user +$permissionToRead = $user->rights->dolicar->adminpage->read; +saturne_check_access($permissionToRead); /* * View */ -$form = new Form($db); +$title = $langs->trans('ModuleSetup', 'DoliCar'); +$helpUrl = 'FR:Module_DoliCar'; -$help_url = ''; -$page_name = $langs->transnoentities('DolicarSetup'); - -saturne_header(0,'', $langs->trans($page_name), $help_url); +saturne_header(0,'', $title, $helpUrl); // Subheader -$linkback = ''.$langs->trans("BackToModuleList").''; +$linkBack = '' . $langs->trans('BackToModuleList') . ''; -print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); +print load_fiche_titre($title, $linkBack, 'title_setup'); // Configuration header $head = dolicar_admin_prepare_head(); -print dol_get_fiche_head($head, 'settings', $langs->trans($page_name), -1, "dolicar_color@dolicar"); +print dol_get_fiche_head($head, 'settings', $title, -1, 'dolicar_color@dolicar'); // Configuration header -print '

' . ' ' . $langs->trans("AgendaModuleRequired") . '
'; -print '

' . ' ' . $langs->trans("HowToSetupOtherModules") . ' ' . '' . $langs->trans('ConfigMyModules') . '' . '
'; -print '

' . ' ' . $langs->trans("AvoidLogoProblems") . ' ' . '' . $langs->trans('LogoHelpLink') . '' . '
'; -print '

' . ' ' . $langs->trans("HowToSetupIHM") . ' ' . '' . $langs->trans('ConfigIHM') . '' . '
'; +print '
' . $langs->trans('AgendaModuleRequired') . '
'; +print '
' . $langs->trans('HowToSetupOtherModules') . '' . $langs->trans('ConfigMyModules') . '
'; +print '
' . $langs->trans('AvoidLogoProblems') . '' . $langs->trans('LogoHelpLink') . '
'; +print '
' . $langs->trans('HowToSetupIHM') . '' . $langs->trans('ConfigIHM') . '
'; // Page end print dol_get_fiche_end(); - llxFooter(); $db->close(); diff --git a/build/index.php b/build/index.php deleted file mode 100644 index cd6990e..0000000 --- a/build/index.php +++ /dev/null @@ -1,2 +0,0 @@ - -# Author: Copyright - -# License: GPLv3 -# Install: Just unpack content of module package in Dolibarr directory. -# Setup: Go on Dolibarr setup - modules to enable module. -# -# Files in module -mymodule/ \ No newline at end of file diff --git a/class/actions_dolicar.class.php b/class/actions_dolicar.class.php index d015883..903b3f4 100644 --- a/class/actions_dolicar.class.php +++ b/class/actions_dolicar.class.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2022-2024 EVARISK * * 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,822 +18,295 @@ /** * \file dolicar/class/actions_dolicar.class.php * \ingroup dolicar - * \brief Example hook overload. - * - * Put detailed description here. + * \brief DoliCar hook overload */ +// Load DoliCar libraries +require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; + /** * Class ActionsDoliCar */ class ActionsDoliCar { - /** - * @var DoliDB Database handler. - */ - public $db; - - /** - * @var string Error code (or message) - */ - public $error = ''; - - /** - * @var array Errors - */ - public $errors = array(); - - - /** - * @var array Hook results. Propagated to $hookmanager->resArray for later reuse - */ - public $results = array(); - - /** - * @var string String displayed by executeHook() immediately after return - */ - public $resprints; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - - /** - * Execute action - * - * @param array $parameters Array of parameters - * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) - * @param string $action 'add', 'update', 'view' - * @return int <0 if KO, - * =0 if OK but we want to process standard actions too, - * >0 if OK and we want to replace standard actions. - */ - public function getNomUrl($parameters, &$object, &$action) - { - global $db, $langs, $conf, $user; - $this->resprints = ''; - return 0; - } + /** + * @var DoliDB Database handler + */ + public DoliDB $db; + + /** + * @var string Error code (or message) + */ + public string $error = ''; + + /** + * @var array Errors + */ + public array $errors = []; + + /** + * @var array Hook results. Propagated to $hookmanager->resArray for later reuse + */ + public array $results = []; /** - * Overloading the addHtmlHeader function : replacing the parent's function with the one below + * @var string|null String displayed by executeHook() immediately after return + */ + public ?string $resprints; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + } + + /** + * Overloading the printCommonFooter function : replacing the parent's function with the one below * - * @param array $parameters Hook metadata (context, etc...) + * @param array $parameters Hook metadatas (context, etc...) * @return int 0 < on error, 0 on success, 1 to replace standard code + * @throws Exception */ - public function addHtmlHeader(array $parameters): int + public function printCommonFooter(array $parameters): int { - if (strpos($_SERVER['PHP_SELF'], 'dolicar') !== false) { - ?> - - resprints = ''; - } + global $db, $object, $langs; // // $db/$langs mandatory for TPL - return 0; // or return 1 to replace standard code - } + $picto = img_picto('', 'dolicar_color@dolicar', 'class="pictofixedwidth paddingright"'); + $action = GETPOST('action', 'aZ09'); - /** - * Overloading the printCommonFooter function : replacing the parent's function with the one below - * - * @param array $parameters Hook metadatas (context, etc...) - * @return int < 0 on error, 0 on success, 1 to replace standard code - */ - public function printCommonFooter($parameters) - { - global $db, $conf, $langs; - - /* print_r($parameters); print_r($object); echo "action: " . $action; */ - $picto = img_picto('', 'dolicar_color@dolicar', 'class="pictofixedwidth"') . ' '; - - if (in_array($parameters['currentcontext'], ['invoicecard', 'propalcard', 'ordercard'])) { - $registrationCertificate = new RegistrationCertificateFr($db); - - $outputline = $registrationCertificate->selectRegistrationCertificateList(GETPOST('options_registrationcertificatefr'), 'options_registrationcertificatefr', GETPOST('socid') > 0 ? ['customsql' => 'fk_soc = ' . GETPOST('socid')] : []); - $addButton = ' '; - $addButton .= ''; - - ?> - - element . '_extras_' . $extrafieldsName; ?> - if ($parameters['currentcontext'] == 'invoicecard') { - - if ((GETPOST('action') == '' || empty(GETPOST('action')) || GETPOST('action') == 'addline' || GETPOST('action') == 'update_extras' || GETPOST('action') != 'create') && (GETPOST('facid') > 0 || GETPOST('id') > 0)) { - - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - require_once __DIR__ . '/../../../product/stock/class/productlot.class.php'; - require_once __DIR__ . '/../../../product/class/product.class.php'; - require_once __DIR__ . '/../../../compta/facture/class/facture.class.php'; - - $facture = new Facture($db); - $facture->fetch(GETPOST('facid') ?: GETPOST('id')); - $facture->fetch_optionals(); - $registrationCertificate_id = $facture->array_options['options_registrationcertificatefr']; - $registrationCertificate = new RegistrationCertificateFr($db); - $registrationCertificate->fetch($registrationCertificate_id); - - $outputline = $registrationCertificate->selectRegistrationCertificateList($registrationCertificate_id); - - $product = new Product($db); - $productlot = new Productlot($db); - - if ($facture->array_options['options_linked_product'] > 0) { - $product->fetch($facture->array_options['options_linked_product']); - } - if ($facture->array_options['options_linked_lot'] > 0) { - $productlot->fetch($facture->array_options['options_linked_lot']); - } - - $mileageWithSeparator = price($facture->array_options['options_mileage'], 0,"",1, 0); - $firstRegistrationDateFormatted = dol_print_date($facture->array_options['options_first_registration_date'], 'day'); - - ?> - - - - - - global->DOLICAR_HIDE_OBJECT_DET_DOLICAR_DETAILS) : - ?> - - - - 0 || GETPOST('id') > 0)) { - - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - require_once __DIR__ . '/../../../product/stock/class/productlot.class.php'; - require_once __DIR__ . '/../../../product/class/product.class.php'; - require_once __DIR__ . '/../../../comm/propal/class/propal.class.php'; - - $propal = new Propal($db); - $propal->fetch(GETPOST('facid') ?: GETPOST('id')); - $propal->fetch_optionals(); - $registrationCertificate_id = $propal->array_options['options_registrationcertificatefr']; - $registrationCertificate = new RegistrationCertificateFr($db); - $registrationCertificate->fetch($registrationCertificate_id); - - $outputline = $registrationCertificate->selectRegistrationCertificateList($registrationCertificate_id); - - $product = new Product($db); - $productlot = new Productlot($db); - - if ($propal->array_options['options_linked_product'] > 0) { - $product->fetch($propal->array_options['options_linked_product']); - } - - if ($propal->array_options['options_linked_lot'] > 0) { - $productlot->fetch($propal->array_options['options_linked_lot']); - } - - $mileageWithSeparator = price($propal->array_options['options_mileage'], 0,"",1, 0); - $firstRegistrationDateFormatted = dol_print_date($propal->array_options['options_first_registration_date'], 'day'); - - ?> - - - - global->DOLICAR_HIDE_OBJECT_DET_DOLICAR_DETAILS) : - ?> - - - - 0 || GETPOST('id') > 0)) { - - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - require_once __DIR__ . '/../../../product/stock/class/productlot.class.php'; - require_once __DIR__ . '/../../../product/class/product.class.php'; - require_once __DIR__ . '/../../../commande/class/commande.class.php'; - - $commande = new Commande($db); - $commande->fetch(GETPOST('facid') ?: GETPOST('id')); - $commande->fetch_optionals(); - $registrationCertificate_id = $commande->array_options['options_registrationcertificatefr']; - $registrationCertificate = new RegistrationCertificateFr($db); - $registrationCertificate->fetch($registrationCertificate_id); - - $outputline = $registrationCertificate->selectRegistrationCertificateList($registrationCertificate_id); - - $product = new Product($db); - $productlot = new Productlot($db); - - if ($commande->array_options['options_linked_product'] > 0) { - $product->fetch($commande->array_options['options_linked_product']); - } - - if ($commande->array_options['options_linked_lot'] > 0) { - $productlot->fetch($commande->array_options['options_linked_lot']); - } - - $mileageWithSeparator = price($commande->array_options['options_mileage'], 0,"",1, 0); - $firstRegistrationDateFormatted = dol_print_date($commande->array_options['options_first_registration_date'], 'day'); - - ?> - + - - - global->DOLICAR_HIDE_OBJECT_DET_DOLICAR_DETAILS) : - ?> - - - - 0 ? $registrationCertificate->fetch(GETPOST('id')) : ''; - - $category->fetch($conf->global->DOLICAR_VEHICLE_TAG); - $objects_in_categ = $category->getObjectsInCateg('product'); - $product_ids = array(); - if (!empty($objects_in_categ)) { - foreach ($objects_in_categ as $object_in_categ) { - $product_ids[$object_in_categ->id] = $object_in_categ->id; - } - } - - $brand_name = get_vehicle_brand(GETPOST('fk_product')?:$registrationCertificate->fk_product); - - ?> - - call_trigger('DOLICAR_PRODUCTLOT_MILEAGE_MODIFY', $user); - } - - if (!$error) { - $this->results = array('myreturn' => 999); - $this->resprints = 'A text to show'; - return 0; // or return 1 to replace standard code - } else { - $this->errors[] = 'Error message'; - return -1; - } - } else if ($parameters['currentcontext'] == 'invoicecard' || $parameters['currentcontext'] == 'propalcard' || $parameters['currentcontext'] == 'commandecard') { - - if ( GETPOST('action') == 'add') { - - require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; - require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - - $product = new Product($this->db); - $registrationcertificatefr = new RegistrationCertificateFr($this->db); - $registrationcertificatefr->fetch(GETPOST('options_registrationcertificatefr')); - - $product->fetch($registrationcertificatefr->fk_product); - - $_POST['options_registration_number'] = $registrationcertificatefr->a_registration_number; - $_POST['options_vehicle_model'] = $product->label; - $_POST['options_linked_product'] = $registrationcertificatefr->fk_product; - $_POST['options_linked_lot'] = $registrationcertificatefr->fk_lot; - $_POST['options_first_registration_date'] = $registrationcertificatefr->b_first_registration_date; - $_POST['options_VIN_number'] = $registrationcertificatefr->e_vehicle_serial_number; - } - - if (GETPOST('action') == 'addline') { - - require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - - $registrationcertificatefr = new RegistrationCertificateFr($this->db); - $registrationcertificatefr->fetch($object->array_options['options_registrationcertificatefr']); - - $product = new Product($this->db); - $product->fetch($registrationcertificatefr->fk_product); - - $productlot = new ProductLot($this->db); - $productlot->fetch($registrationcertificatefr->fk_lot); - - $_POST['options_registrationcertificatefr'] = $object->array_options['options_registrationcertificatefr']; - $_POST['options_registration_number'] = $object->array_options['options_registration_number']; - $_POST['options_vehicle_model'] = $object->array_options['options_vehicle_model']; - $_POST['options_mileage'] = $object->array_options['options_mileage']; - $_POST['options_linked_lot'] = $object->array_options['options_linked_lot']; - $_POST['options_first_registration_date'] = $object->array_options['options_first_registration_date']; - $_POST['options_VIN_number'] = $object->array_options['options_VIN_number']; - } - - if (GETPOST('action') == 'update_extras') { - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - - $registrationcertificatefr = new RegistrationCertificateFr($this->db); - - if (GETPOST('attribute') == 'registrationcertificatefr') { - - $registrationcertificatefr_id = GETPOST('options_registrationcertificatefr'); - $registrationcertificatefr->fetch($registrationcertificatefr_id); - $object->array_options['options_registration_number'] = $registrationcertificatefr->a_registration_number; - $object->array_options['options_vehicle_model'] = $registrationcertificatefr->d3_vehicle_model; - $object->array_options['options_linked_product'] = $registrationcertificatefr->fk_product; - $object->array_options['options_linked_lot'] = $registrationcertificatefr->fk_lot; - $object->update($user); - - } - if (GETPOST('attribute') == 'mileage') { - $mileage = GETPOST('options_mileage'); - foreach ($object->lines as $line) { - if ($object->array_options['options_registrationcertificatefr'] == $line->array_options['options_registrationcertificatefr']) { - $line->array_options['options_mileage'] = $mileage; - $line->update($user); - } - } - } - } - } - } - - /** - * Overloading the doMassActions function : replacing the parent's function with the one below - * - * @param array $parameters Hook metadatas (context, etc...) - * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) - * @param string $action Current action (if set). Generally create or edit or null - * @param HookManager $hookmanager Hook manager propagated to allow calling another hook - * @return int < 0 on error, 0 on success, 1 to replace standard code - */ - public function doMassActions($parameters, &$object, &$action, $hookmanager) - { - global $conf, $user, $langs; - - $error = 0; // Error counter - - /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' - foreach ($parameters['toselect'] as $objectid) { - // Do action on each object id - } - } - - if (!$error) { - $this->results = array('myreturn' => 999); - $this->resprints = 'A text to show'; - return 0; // or return 1 to replace standard code - } else { - $this->errors[] = 'Error message'; - return -1; - } - } - - /** - * Overloading the addMoreMassActions function : replacing the parent's function with the one below - * - * @param array $parameters Hook metadatas (context, etc...) - * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) - * @param string $action Current action (if set). Generally create or edit or null - * @param HookManager $hookmanager Hook manager propagated to allow calling another hook - * @return int < 0 on error, 0 on success, 1 to replace standard code - */ - public function addMoreMassActions($parameters, &$object, &$action, $hookmanager) - { - global $conf, $user, $langs; - - $error = 0; // Error counter - $disabled = 1; - - /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) { // do something only for the context 'somecontext1' or 'somecontext2' - $this->resprints = ''; - } - - if (!$error) { - return 0; // or return 1 to replace standard code - } else { - $this->errors[] = 'Error message'; - return -1; - } - } - - /** - * Execute action - * - * @param array $parameters Array of parameters - * @param Object $object Object output on PDF - * @param string $action 'add', 'update', 'view' - * @return int <0 if KO, - * =0 if OK but we want to process standard actions too, - * >0 if OK and we want to replace standard actions. - */ - public function beforePDFCreation($parameters, &$object, &$action) - { - global $conf, $db, $langs, $user; - - $ret = 0; - dol_syslog(get_class($this).'::executeHooks action='.$action); - if ( - (in_array('ordercard', explode(':', $parameters['context'])) && empty($conf->global->DOLICAR_HIDE_ADDRESS_ON_ORDERCARD)) - || (in_array('propalcard', explode(':', $parameters['context'])) && empty($conf->global->DOLICAR_HIDE_ADDRESS_ON_PROPALCARD)) - || (in_array('invoicecard', explode(':', $parameters['context'])) && empty($conf->global->DOLICAR_HIDE_ADDRESS_ON_INVOICECARD)) - || (in_array('paiementcard', explode(':', $parameters['context']))) + db); + + if ($action == 'add') { + if (GETPOSTISSET('options_registrationcertificatefr')) { + require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + + $product = new Product($this->db); + + $registrationCertificateFr->fetch(GETPOST('options_registrationcertificatefr')); + $product->fetch($registrationCertificateFr->fk_product); + + $_POST['options_registration_number'] = $registrationCertificateFr->a_registration_number; + $_POST['options_vehicle_model'] = $product->label; + $_POST['options_linked_product'] = $registrationCertificateFr->fk_product; + $_POST['options_linked_lot'] = $registrationCertificateFr->fk_lot; + $_POST['options_first_registration_date'] = $registrationCertificateFr->b_first_registration_date; + $_POST['options_VIN_number'] = $registrationCertificateFr->e_vehicle_serial_number; + } + } + + if ($action == 'update_extras') { + if (GETPOST('attribute') == 'registrationcertificatefr') { + $registrationCertificateFr->fetch(GETPOST('options_registrationcertificatefr')); + $object->array_options['options_registration_number'] = $registrationCertificateFr->a_registration_number; + $object->array_options['options_vehicle_model'] = $registrationCertificateFr->d3_vehicle_model; + $object->array_options['options_linked_product'] = $registrationCertificateFr->fk_product; + $object->array_options['options_linked_lot'] = $registrationCertificateFr->fk_lot; + $object->array_options['options_first_registration_date'] = $registrationCertificateFr->b_first_registration_date; + $object->array_options['options_VIN_number'] = $registrationCertificateFr->e_vehicle_serial_number; + $object->update($user); + } + + if (GETPOST('attribute') == 'mileage') { + $mileage = GETPOST('options_mileage'); + foreach ($object->lines as $line) { + if ($object->array_options['options_registrationcertificatefr'] == $line->array_options['options_registrationcertificatefr']) { + $line->array_options['options_mileage'] = $mileage; + $line->update($user); + } + } + } + } + } + + return 0; // or return 1 to replace standard code + } + + /** + * Overloading the beforePDFCreation function : replacing the parent's function with the one below + * + * @param array $parameters Hook metadatas (context, etc...) + * @param CommonObject $object Current object + * @param string $action Current action + * @return int 0 < on error, 0 on success, 1 to replace standard code + * @throws Exception + */ + public function beforePDFCreation($parameters, &$object, &$action): int + { + global $conf, $langs; + + if ( + (in_array('ordercard', explode(':', $parameters['context'])) && empty($conf->global->DOLICAR_HIDE_ADDRESS_ON_ORDERCARD)) + || (in_array('propalcard', explode(':', $parameters['context'])) && empty($conf->global->DOLICAR_HIDE_ADDRESS_ON_PROPALCARD)) + || (in_array('invoicecard', explode(':', $parameters['context'])) && empty($conf->global->DOLICAR_HIDE_ADDRESS_ON_INVOICECARD)) + || (in_array('paiementcard', explode(':', $parameters['context']))) ) { if ($object->array_options['options_registrationcertificatefr'] > 0) { - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; - $registrationcertificatefr = new RegistrationCertificateFr($this->db); - $productlot = new ProductLot($this->db); - $registrationcertificatefr->fetch($object->array_options['options_registrationcertificatefr']); - $productlot->fetch($registrationcertificatefr->fk_lot); + $registrationCertificateFr = new RegistrationCertificateFr($this->db); - $mileageWithSeparator = price($object->array_options['options_mileage'], 0,"",1, 0); + $registrationCertificateFr->fetch($object->array_options['options_registrationcertificatefr']); $object->fetch_optionals(); - $object->note_public = $langs->transnoentities('RegistrationNumber') . ' : ' . $object->array_options['options_registration_number'] . '
'; + $object->note_public = $langs->transnoentities('RegistrationNumber') . ' : ' . $object->array_options['options_registration_number'] . '
'; $object->note_public .= $langs->transnoentities('VehicleModel') . ' : ' . $object->array_options['options_vehicle_model'] . '
'; - $object->note_public .= $langs->transnoentities('VINNumber') . ' : ' . $productlot->batch . '
'; - $object->note_public .= $langs->transnoentities('FirstRegistrationDate') . ' : ' . dol_print_date($registrationcertificatefr->b_first_registration_date, 'day') . '
'; - $object->note_public .= $langs->transnoentities('Mileage') . ' : ' . $mileageWithSeparator . ' ' . $langs->trans('km') . '
'; + $object->note_public .= $langs->transnoentities('VINNumber') . ' : ' . $object->array_options['options_VIN_number'] . '
'; + $object->note_public .= $langs->transnoentities('FirstRegistrationDate') . ' : ' . dol_print_date($object->array_options['options_first_registration_date'], 'day') . '
'; + $object->note_public .= $langs->transnoentities('Mileage') . ' : ' . price($object->array_options['options_mileage'], 0,'',1, 0) . ' ' . $langs->trans('km') . '
'; + } + + } + + return 0; // or return 1 to replace standard code + } + + /** + * Overloading the extendSheetLinkableObjectsList function : replacing the parent's function with the one below + * + * @param array $linkableObjectTypes Array of linkable objects + * @return int 0 < on error, 0 on success, 1 to replace standard code + */ + public function extendSheetLinkableObjectsList(array $linkableObjectTypes): int { + require_once __DIR__ . '/../lib/dolicar_registrationcertificatefr.lib.php'; + + $registrationCertificate = new RegistrationCertificateFr($this->db); + $linkableObjectTypes['dolicar_regcertfr'] = [ + 'langs' => 'RegistrationCertificateFr', + 'langfile' => 'dolicar@dolicar', + 'picto' => $registrationCertificate->picto, + 'className' => 'registrationCertificateFr', + 'name_field' => 'ref', + 'post_name' => 'fk_registrationcertificatefr', + 'link_name' => 'dolicar_regcertfr', + 'tab_type' => 'registrationcertificatefr', + 'hook_name_list' => 'registrationcertificatefrcard', + 'hook_name_card' => 'registrationcertificatefrlist', + 'create_url' => 'custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php?action=create', + 'class_path' => 'custom/dolicar/class/registrationcertificatefr.class.php', + ]; + $this->results = $linkableObjectTypes; + + return 0; // or return 1 to replace standard code + } + + /** + * Overloading the quickCreationAction function : replacing the parent's function with the one below + * + * @param array $parameters Hook metadatas (context, etc...) + * @param CommonObject $object Current object + * @param string $action Current action + * @return int 0 < on error, 0 on success, 1 to replace standard code + * @throws Exception + */ + public function quickCreationAction(array $parameters, CommonObject $object, string $action) + { + global $conf, $langs, $user; // $langs mandatory for TPL + + if (strpos($parameters['context'], 'dolicar_quickcreation') !== false) { + if (isModEnabled('productbatch')) { + require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; + } + if (isModEnabled('categorie')) { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + } + + require_once __DIR__ . '/../lib/dolicar_registrationcertificatefr.lib.php'; + + if (isModEnabled('product')) { + $product = new Product($this->db); + } + if (isModEnabled('productbatch')) { + $productLot = new Productlot($this->db); + } + if (isModEnabled('categorie')) { + $category = new Categorie($this->db); } + $object = new RegistrationCertificateFr($this->db); - } - - return $ret; - } - - /** - * Overloading the restrictedArea function : check permission on an object - * - * @param array $parameters Hook metadatas (context, etc...) - * @param string $action Current action (if set). Generally create or edit or null - * @param HookManager $hookmanager Hook manager propagated to allow calling another hook - * @return int <0 if KO, - * =0 if OK but we want to process standard actions too, - * >0 if OK and we want to replace standard actions. - */ - public function restrictedArea($parameters, &$action, $hookmanager) - { - global $user; - - if ($parameters['features'] == 'myobject') { - if ($user->rights->dolicar->myobject->read) { - $this->results['result'] = 1; - return 1; - } else { - $this->results['result'] = 0; - return 1; - } - } - - return 0; - } - - /** - * Execute action completeTabsHead - * - * @param array $parameters Array of parameters - * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) - * @param string $action 'add', 'update', 'view' - * @param Hookmanager $hookmanager hookmanager - * @return int <0 if KO, - * =0 if OK but we want to process standard actions too, - * >0 if OK and we want to replace standard actions. - */ - public function completeTabsHead(&$parameters, &$object, &$action, $hookmanager) - { - global $langs, $conf, $user; - - if (!isset($parameters['object']->element)) { - return 0; - } - if ($parameters['mode'] == 'remove') { - // utilisé si on veut faire disparaitre des onglets. - return 0; - } elseif ($parameters['mode'] == 'add') { - $langs->load('dolicar@dolicar'); - // utilisé si on veut ajouter des onglets. - $counter = count($parameters['head']); - $element = $parameters['object']->element; - $id = $parameters['object']->id; - // verifier le type d'onglet comme member_stats où ça ne doit pas apparaitre - // if (in_array($element, ['societe', 'member', 'contrat', 'fichinter', 'project', 'propal', 'commande', 'facture', 'order_supplier', 'invoice_supplier'])) { - if (in_array($element, ['context1', 'context2'])) { - $datacount = 0; - - $parameters['head'][$counter][0] = dol_buildpath('/dolicar/dolicar_tab.php', 1) . '?id=' . $id . '&module='.$element; - $parameters['head'][$counter][1] = $langs->trans('DoliCarTab'); - if ($datacount > 0) { - $parameters['head'][$counter][1] .= '' . $datacount . ''; - } - $parameters['head'][$counter][2] = 'dolicaremails'; - $counter++; - } - if ($counter > 0 && (int) DOL_VERSION < 14) { - $this->results = $parameters['head']; - // return 1 to replace standard code - return 1; - } else { - // en V14 et + $parameters['head'] est modifiable par référence - return 0; - } - } - } - - /** - * Execute action extendSheetLinkableObjectsList - * - * @param array $linkableObjectTypes Array of linkable objects - * @return int 1 - */ - public function extendSheetLinkableObjectsList(array $linkableObjectTypes): int { - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - require_once __DIR__ . '/../lib/dolicar_registrationcertificatefr.lib.php'; - - $registrationCertificate = new RegistrationCertificateFr($this->db); - $linkableObjectTypes['dolicar_regcertfr'] = [ - 'langs' => 'RegistrationCertificate', - 'langfile' => 'dolicar@dolicar', - 'picto' => $registrationCertificate->picto, - 'className' => 'registrationCertificateFr', - 'post_name' => 'fk_registrationcertificatefr', - 'link_name' => 'dolicar_regcertfr', - 'name_field' => 'ref', - 'create_url' => 'custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', - 'class_path' => 'custom/dolicar/class/registrationcertificatefr.class.php', - ]; - - $this->results = $linkableObjectTypes; - return 0; - } - - /** - * Execute action completeTabsHead - * - * @param array $parameters Array of parameters - * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) - * @param string $action 'add', 'update', 'view' - * @param Hookmanager $hookmanager hookmanager - * @return int <0 if KO, - * =0 if OK but we want to process standard actions too, - * >0 if OK and we want to replace standard actions. - */ - public function quickCreationAction(&$parameters, &$object, &$action, $hookmanager) - { - global $db, $langs, $user, $conf; - - if ($parameters['currentcontext'] == 'dolicar_quickcreation') { - require_once __DIR__ . '/../class/registrationcertificatefr.class.php'; - require_once __DIR__ . '/../lib/dolicar_registrationcertificatefr.lib.php'; - if (isModEnabled('productbatch')) { - require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; - } - if (isModEnabled('categorie')) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - } - - $object = new RegistrationCertificateFr($this->db); - if (isModEnabled('product')) { - $product = new Product($this->db); - } - if (isModEnabled('productbatch')) { - $productLot = new Productlot($this->db); - } - if (isModEnabled('categorie')) { - $category = new Categorie($this->db); - } - - $createRegistrationCertificate = 1; - require_once __DIR__ . '/../core/tpl/dolicar_registrationcertificatefr_immatriculation_api_fetch_action.tpl.php'; - - if ($conf->global->DOLICAR_AUTOMATIC_CONTACT_CREATION > 0 && empty($parameters['$contactID'])) { - require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; - require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; - - if (isModEnabled('societe')) { - $thirdparty = new Societe($this->db); - $contact = new Contact($this->db); - - $thirdpartyID = $parameters['thirdpartyID']; - - $thirdparty->fetch($thirdpartyID); - - $contact->socid = !empty($thirdpartyID) ? $thirdpartyID : ''; - $contact->lastname = $thirdparty->name; - $contact->email = $thirdparty->email; - $contact->phone_pro = $thirdparty->phone; - - $contactID = $contact->create($user); - if ($contactID < 0) { - setEventMessages($contact->error, $contact->errors, 'errors'); + $createRegistrationCertificate = 1; + require_once __DIR__ . '/../core/tpl/dolicar_registrationcertificatefr_immatriculation_api_fetch_action.tpl.php'; + + if ($conf->global->DOLICAR_AUTOMATIC_CONTACT_CREATION > 0 && empty($parameters['$contactID'])) { + require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; + require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; + + if (isModEnabled('societe')) { + $thirdparty = new Societe($this->db); + $contact = new Contact($this->db); + + $thirdpartyID = $parameters['thirdpartyID']; + + $thirdparty->fetch($thirdpartyID); + + $contact->socid = !empty($thirdpartyID) ? $thirdpartyID : ''; + $contact->lastname = $thirdparty->name; + $contact->email = $thirdparty->email; + $contact->phone_pro = $thirdparty->phone; + + $contactID = $contact->create($user); + if ($contactID < 0) { + setEventMessages($contact->error, $contact->errors, 'errors'); $error++; - } - } - } - if (dol_strlen($backtopage) > 0){ - $this->resprints = $backtopage; + } + } + } + if (dol_strlen($backtopage) > 0){ + $this->resprints = $backtopage; + return 1; + } + if (!$error) { return 1; - } - if (!$error) { - return 1; - } - } - } + } + } + } } diff --git a/class/registrationcertificatefr.class.php b/class/registrationcertificatefr.class.php index 878b2c4..14e40f1 100644 --- a/class/registrationcertificatefr.class.php +++ b/class/registrationcertificatefr.class.php @@ -1,6 +1,5 @@ - * Copyright (C) ---Put here your own copyright and developer email--- +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ -17,1476 +16,426 @@ */ /** - * \file class/registrationcertificatefr.class.php - * \ingroup dolicar - * \brief This file is a CRUD class file for RegistrationCertificateFr (Create/Read/Update/Delete) + * \file class/registrationcertificatefr.class.php + * \ingroup dolicar + * \brief This file is a CRUD class file for RegistrationCertificateFr (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.'/product/class/product.class.php'; -require_once __DIR__.'/../lib/dolicar_functions.lib.php'; -//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; -//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; +// Load Saturne libraries +require_once __DIR__ . '/../../saturne/class/saturneobject.class.php'; + +// Load DoliCar libraries +require_once __DIR__ .'/../lib/dolicar_functions.lib.php'; /** * Class for RegistrationCertificateFr */ -class RegistrationCertificateFr extends CommonObject +class RegistrationCertificateFr extends SaturneObject { - /** - * @var string ID of module. - */ - public $module = 'dolicar'; - - /** - * @var string ID to identify managed object. - */ - public $element = 'registrationcertificatefr'; - - /** - * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. - */ - public $table_element = 'dolicar_registrationcertificatefr'; - - /** - * @var int Does this object support multicompany module ? - * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table - */ - public $ismultientitymanaged = 1; - - /** - * @var int Does object support extrafields ? 0=No, 1=Yes - */ - public $isextrafieldmanaged = 1; - - /** - * @var string String with name of icon for registrationcertificatefr. Must be the part after the 'object_' into object_registrationcertificatefr.png - */ - public $picto = 'fontawesome_fa-car_fas_#d35968'; - - const STATUS_VALIDATED = 1; - const STATUS_LOCKED = 2; - const STATUS_ARCHIVED = 3; - - /** - * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') - * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" - * 'label' the translation key. - * 'picto' is code of a picto to show before value in forms - * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM) - * 'position' is the sort order of field. - * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). - * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) - * 'noteditable' says if field is not editable (1 or 0) - * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. - * 'index' if we want an index in database. - * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). - * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. - * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage) - * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200' - * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. - * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record - * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. - * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar' - * '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. - * 'validate' is 1 if need to validate with $this->validateField() - * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value) - * - * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. - */ - - /** - * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. - */ - public $fields=array( - 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"), - 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'index'=>1, 'searchall'=>1, 'validate'=>'1', 'comment'=>"Reference of object"), - 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1:(status:=:1)', 'label'=>'ThirdParty', 'enabled'=>'1', 'position'=>14, 'notnull'=>-1, 'visible'=>1, 'index'=>1, 'css'=>'maxwidth500 widthcentpercentminusxx', 'help'=>"LinkToThirparty", 'validate'=>'1',), - 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>40, 'notnull'=>1, 'visible'=>-2,), - 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>50, 'notnull'=>0, 'visible'=>-2,), - 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>540, 'notnull'=>1, 'visible'=>-2,), - 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>550, 'notnull'=>-1, 'visible'=>-2,), - 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => '1', 'position' => 30, 'notnull' => 1, 'visible' => 0,), - 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>60, 'notnull'=>-1, 'visible'=>-2,), - 'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>'1', 'position'=>70, 'notnull'=>1, 'visible'=>0, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Validé', '9'=>'Annulé')), - 'ref_ext' => array('type'=>'varchar(128)', 'label'=>'RefExt', 'enabled'=>'1', 'position'=>20, 'notnull'=>0, 'visible'=>0,), - 'a_registration_number' => array('type'=>'varchar(128)', 'label'=>'RegistrationNumber', 'enabled'=>'1', 'position'=>11, 'notnull'=>1, 'visible'=>1,), - 'b_first_registration_date' => array('type'=>'date', 'label'=>'FirstRegistrationDate', 'enabled'=>'1', 'position'=>90, 'notnull'=>0, 'visible'=>3,), - 'c1_owner_fullname' => array('type'=>'varchar(255)', 'label'=>'OwnerFullName', 'enabled'=>'1', 'position'=>100, 'notnull'=>0, 'visible'=>3,), - 'c3_registration_address' => array('type'=>'text', 'label'=>'RegistrationAddress', 'enabled'=>'1', 'position'=>110, 'notnull'=>0, 'visible'=>3,), - 'c4a_vehicle_owner' => array('type'=>'boolean', 'label'=>'VehicleOwner', 'enabled'=>'1', 'position'=>120, 'notnull'=>0, 'visible'=>3,), - 'c41_second_owner_number' => array('type'=>'integer', 'label'=>'SecondOwnerNumber', 'enabled'=>'1', 'position'=>130, 'notnull'=>0, 'visible'=>3,), - 'c41_second_owner_name' => array('type'=>'varchar(128)', 'label'=>'SecondOwnerName', 'enabled'=>'1', 'position'=>140, 'notnull'=>0, 'visible'=>3,), - 'd1_vehicle_brand' => array('type'=>'varchar(128)', 'label'=>'VehicleBrand', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>3,), - 'd2_vehicle_type' => array('type'=>'varchar(128)', 'label'=>'VehicleType', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>3,), - 'd21_vehicle_cnit' => array('type'=>'varchar(128)', 'label'=>'VehicleCNIT', 'enabled'=>'1', 'position'=>170, 'notnull'=>0, 'visible'=>3,), - 'd3_vehicle_model' => array('type'=>'varchar(128)', 'label'=>'VehicleModel', 'enabled'=>'1', 'position'=>175, 'notnull'=>0, 'visible'=>3,), - 'e_vehicle_serial_number' => array('type'=>'varchar(128)', 'label'=>'VehicleSerialNumber', 'enabled'=>'1', 'position'=>190, 'notnull'=>0, 'visible'=>3,), - 'f1_technical_ptac' => array('type'=>'integer', 'label'=>'TechnicalPTAC', 'enabled'=>'1', 'position'=>200, 'notnull'=>0, 'visible'=>3,), - 'f2_ptac' => array('type'=>'integer', 'label'=>'PTAC', 'enabled'=>'1', 'position'=>210, 'notnull'=>0, 'visible'=>3,), - 'f3_ptra' => array('type'=>'integer', 'label'=>'PTRA', 'enabled'=>'1', 'position'=>220, 'notnull'=>0, 'visible'=>3,), - 'g_vehicle_weight' => array('type'=>'integer', 'label'=>'VehicleWeight', 'enabled'=>'1', 'position'=>230, 'notnull'=>0, 'visible'=>3,), - 'g1_vehicle_empty_weight' => array('type'=>'integer', 'label'=>'VehicleEmptyWeight', 'enabled'=>'1', 'position'=>240, 'notnull'=>0, 'visible'=>3,), - 'h_validity_period' => array('type'=>'varchar(128)', 'label'=>'ValidityPeriod', 'enabled'=>'1', 'position'=>250, 'notnull'=>0, 'visible'=>3,), - 'i_vehicle_registration_date' => array('type'=>'datetime', 'label'=>'VehicleRegistrationDate', 'enabled'=>'1', 'position'=>260, 'notnull'=>0, 'visible'=>3,), - 'j_vehicle_category' => array('type'=>'varchar(128)', 'label'=>'VehicleCategory', 'enabled'=>'1', 'position'=>270, 'notnull'=>0, 'visible'=>3,), - 'j1_national_type' => array('type'=>'varchar(128)', 'label'=>'NationalType', 'enabled'=>'1', 'position'=>280, 'notnull'=>0, 'visible'=>3,), - 'j2_european_bodywork' => array('type'=>'varchar(128)', 'label'=>'EuropeanBodyWork', 'enabled'=>'1', 'position'=>290, 'notnull'=>0, 'visible'=>3,), - 'j3_national_bodywork' => array('type'=>'varchar(128)', 'label'=>'NationalBodyWork', 'enabled'=>'1', 'position'=>300, 'notnull'=>0, 'visible'=>3,), - 'k_type_approval_number' => array('type'=>'varchar(128)', 'label'=>'TypeApprovalNumber', 'enabled'=>'1', 'position'=>310, 'notnull'=>0, 'visible'=>3,), - 'p1_cylinder_capacity' => array('type'=>'integer', 'label'=>'CylinderCapacity', 'enabled'=>'1', 'position'=>320, 'notnull'=>0, 'visible'=>3,), - 'p2_maximum_net_power' => array('type'=>'integer', 'label'=>'MaximumNetPower', 'enabled'=>'1', 'position'=>330, 'notnull'=>0, 'visible'=>3,), - 'p3_fuel_type' => array('type'=>'varchar(128)', 'label'=>'FuelType', 'enabled'=>'1', 'position'=>340, 'notnull'=>0, 'visible'=>3,), - 'p6_national_administrative_power' => array('type'=>'integer', 'label'=>'NationalAdministrativePower', 'enabled'=>'1', 'position'=>350, 'notnull'=>0, 'visible'=>3,), - 'q_power_to_weight_ratio' => array('type'=>'integer', 'label'=>'PowerToWeightRatio', 'enabled'=>'1', 'position'=>360, 'notnull'=>0, 'visible'=>3,), - 's1_seating_capacity' => array('type'=>'integer', 'label'=>'SeatingCapacity', 'enabled'=>'1', 'position'=>370, 'notnull'=>0, 'visible'=>3,), - 's2_standing_capacity' => array('type'=>'integer', 'label'=>'StationaryCapacity', 'enabled'=>'1', 'position'=>380, 'notnull'=>0, 'visible'=>3,), - 'u1_stationary_noise_level' => array('type'=>'integer', 'label'=>'StationaryNoiseLevel', 'enabled'=>'1', 'position'=>390, 'notnull'=>0, 'visible'=>3,), - 'u2_motor_speed' => array('type'=>'integer', 'label'=>'MotorSpeed', 'enabled'=>'1', 'position'=>400, 'notnull'=>0, 'visible'=>3,), - 'v7_co2_emission' => array('type'=>'integer', 'label'=>'CO2Emission', 'enabled'=>'1', 'position'=>410, 'notnull'=>0, 'visible'=>3,), - 'v9_environmental_category' => array('type'=>'varchar(128)', 'label'=>'EnvironmentalCategory', 'enabled'=>'1', 'position'=>420, 'notnull'=>0, 'visible'=>3,), - 'x1_first_technical_inspection_date' => array('type'=>'datetime', 'label'=>'FirstTechnicalInspectionDate', 'enabled'=>'1', 'position'=>430, 'notnull'=>0, 'visible'=>3,), - 'y1_regional_tax' => array('type'=>'double(24,8)', 'label'=>'RegionalTax', 'enabled'=>'1', 'position'=>440, 'notnull'=>0, 'visible'=>3,), - 'y2_professional_tax' => array('type'=>'double(24,8)', 'label'=>'ProfessionalTax', 'enabled'=>'1', 'position'=>450, 'notnull'=>0, 'visible'=>3,), - 'y3_ecological_tax' => array('type'=>'double(24,8)', 'label'=>'EcologicalTax', 'enabled'=>'1', 'position'=>460, 'notnull'=>0, 'visible'=>3,), - 'y4_management_tax' => array('type'=>'double(24,8)', 'label'=>'ManagementTax', 'enabled'=>'1', 'position'=>470, 'notnull'=>0, 'visible'=>3,), - 'y5_forwarding_expenses_tax' => array('type'=>'double(24,8)', 'label'=>'ForwardingExpensesTax', 'enabled'=>'1', 'position'=>480, 'notnull'=>0, 'visible'=>3,), - 'y6_total_price_vehicle_registration' => array('type'=>'double(24,8)', 'label'=>'TotalPriceVehicleRegistration', 'enabled'=>'1', 'position'=>490, 'notnull'=>0, 'visible'=>3,), - 'z1_specific_details' => array('type'=>'text', 'label'=>'SpecificDetails1', 'enabled'=>'1', 'position'=>500, 'notnull'=>0, 'visible'=>3,), - 'z2_specific_details' => array('type'=>'text', 'label'=>'SpecificDetails2', 'enabled'=>'1', 'position'=>510, 'notnull'=>0, 'visible'=>3,), - 'z3_specific_details' => array('type'=>'text', 'label'=>'SpecificDetails3', 'enabled'=>'1', 'position'=>520, 'notnull'=>0, 'visible'=>3,), - 'z4_specific_details' => array('type'=>'text', 'label'=>'SpecificDetails4', 'enabled'=>'1', 'position'=>530, 'notnull'=>0, 'visible'=>3,), - 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'LinkedProduct', 'enabled'=>'1', 'position'=>13, 'notnull'=>0, 'visible'=>1, 'css'=>'maxwidth500'), - 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1', 'label'=>'Project', 'enabled'=>'1', 'position'=>16, 'notnull'=>-1, 'visible'=>-1, 'index'=>1, 'css'=>'maxwidth500', 'validate'=>'1',), - 'fk_lot' => array('type'=>'integer:Productlot:product/stock/class/productlot.class.php:1', 'label'=>'DolicarBatch', 'enabled'=>'1', 'position'=>15, 'notnull'=>-1, 'visible'=>-1, 'index'=>1, 'css'=>'maxwidth500', 'validate'=>'1',), - 'json' => array('type'=>'text', 'label'=>'JSON', 'enabled'=>'1', 'position'=>15, 'notnull'=>-1, 'visible'=>3, 'index'=>1, 'css'=>'maxwidth500'), - ); - // BEGIN MODULEBUILDER PROPERTIES - public $rowid; - public $ref; - public $fk_soc; - public $date_creation; - public $tms; - public $fk_user_creat; - public $fk_user_modif; - public $import_key; - public $entity; - public $status; - public $ref_ext; - public $a_registration_number; - public $b_first_registration_date; - public $c1_owner_fullname; - public $c3_registration_address; - public $c41_ownerNumber; - public $c41_second_owner_name; - public $e_vehicle_serial_number; - public $f1_techincal_ptac; - public $f2_ptac; - public $c4a_owner_vehicle; - public $fk_product; - public $d1_vehicle_brand; - public $d2_vehicle_type; - public $d21_vehicle_cnit; - public $d3_vehicle_model; - public $f3_ptra; - public $g_vehicle_weight; - public $g1_vehicle_empty_weight; - public $h_validity_period; - public $i_vehicle_registration_date; - public $j_vehicleCategory; - public $j1_national_type; - public $j2_european_bodywork; - public $j3_national_bodywork; - public $k_type_approval_number; - public $p1_cylinder_capacity; - public $p2_maximum_net_power; - public $p3_fuel_type; - public $p6_national_administrative_power; - public $q_power_to_weight_ratio; - public $s1_seatingCapacity; - public $s2_standing_capacity; - public $u1_stationary_noise_level; - public $u2_motor_speed; - public $v7_co2_emission; - public $v9_environmental_category; - public $x1_first_technical_inspection_date; - public $y1_regional_tax; - public $y2_professional_tax; - public $y3_ecological_tax; - public $y4_management_tax; - public $y5_forwarding_expenses_tax; - public $y6_total_price_vehicle_registration; - public $z1_specific_details; - public $z2_specific_details; - public $z3_specific_details; - public $z4_specific_details; - public $fk_project; - public $fk_lot; - public $json; - // END MODULEBUILDER PROPERTIES - + /** + * @var string Module name + */ + public $module = 'dolicar'; - // If this object has a subtable with lines + /** + * @var string Element type of object + */ + public $element = 'registrationcertificatefr'; - // /** - // * @var string Name of subtable line - // */ - // public $table_element_line = 'dolicar_registrationcertificatefrline'; + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management + */ + public $table_element = 'dolicar_registrationcertificatefr'; - // /** - // * @var string Field with ID of parent key if this object has a parent - // */ - // public $fk_element = 'fk_registrationcertificatefr'; + /** + * @var int Does this object support multicompany module ? + * 0 = No test on entity, 1 = Test with field entity, 'field@table' = Test with link by field@table + */ + public $ismultientitymanaged = 1; - // /** - // * @var string Name of subtable class that manage subtable lines - // */ - // public $class_element_line = 'RegistrationCertificateFrline'; + /** + * @var int Does object support extrafields ? 0 = No, 1 = Yes + */ + public $isextrafieldmanaged = 1; - // /** - // * @var array List of child tables. To test if we can delete object. - // */ - // protected $childtables = array(); + /** + * @var string Name of icon for registrationcertificatefr. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'registrationcertificatefr@dolicar' if picto is file 'img/object_registrationcertificatefr.png' + */ + public string $picto = 'fontawesome_fa-car_fas_#d35968'; - // /** - // * @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('dolicar_registrationcertificatefrdet'); + public const STATUS_VALIDATED = 1; + public const STATUS_LOCKED = 2; + public const STATUS_ARCHIVED = 3; - // /** - // * @var RegistrationCertificateFrLine[] Array of subtable lines - // */ - // public $lines = array(); + /** + * 'type' field format: + * 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', + * 'select' (list of values are in 'options'), + * 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', + * 'chkbxlst:...', + * 'varchar(x)', + * 'text', 'text:none', 'html', + * 'double(24,8)', 'real', 'price', + * 'date', 'datetime', 'timestamp', 'duration', + * 'boolean', 'checkbox', 'radio', 'array', + * 'mail', 'phone', 'url', 'password', 'ip' + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'picto' is code of a picto to show before value in forms + * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM' or '!empty($conf->multicurrency->enabled)' ...) + * '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 overwroted 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 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage) + * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200' + * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar' + * '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. + * 'validate' is 1 if you need to validate with $this->validateField() + * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value) + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor + */ + public $fields = [ + 'rowid' => ['type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'comment' => 'Id'], + 'ref' => ['type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 10, 'notnull' => 1, 'visible' => 4, 'noteditable' => 1, 'index' => 1, 'searchall' => 1, 'comment' => 'Reference of object'], + 'ref_ext' => ['type' => 'varchar(128)', 'label' => 'RefExt', 'enabled' => 1, 'position' => 20, 'notnull' => 0, 'visible' => 0], + 'entity' => ['type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 0, 'index' => 1], + 'date_creation' => ['type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 40, 'notnull' => 1, 'visible' => 2], + 'tms' => ['type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 50, 'notnull' => 0, 'visible' => 0], + 'import_key' => ['type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 0], + 'status' => ['type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'position' => 70, 'notnull' => 1, 'visible' => 0, 'index' => 1, 'default' => 1, 'arrayofkeyval' => [1 => 'Validated', 3 => 'Archived']], + 'a_registration_number' => ['type' => 'varchar(128)', 'label' => 'RegistrationNumber', 'enabled' => 1, 'position' => 11, 'notnull' => 1, 'visible' => 1], + 'b_first_registration_date' => ['type' => 'date', 'label' => 'FirstRegistrationDate', 'enabled' => 1, 'position' => 80, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'c1_owner_fullname' => ['type' => 'varchar(255)', 'label' => 'OwnerFullName', 'enabled' => 1, 'position' => 90, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'c3_registration_address' => ['type' => 'html', 'label' => 'RegistrationAddress', 'enabled' => 1, 'position' => 100, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'c4a_vehicle_owner' => ['type' => 'boolean', 'label' => 'VehicleOwner', 'enabled' => 1, 'position' => 110, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'c41_second_owner_number' => ['type' => 'integer', 'label' => 'SecondOwnerNumber', 'enabled' => 1, 'position' => 120, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'c41_second_owner_name' => ['type' => 'varchar(128)', 'label' => 'SecondOwnerName', 'enabled' => 1, 'position' => 130, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'd1_vehicle_brand' => ['type' => 'varchar(128)', 'label' => 'VehicleBrand', 'enabled' => 1, 'position' => 140, 'notnull' => 0, 'visible' => 3, 'default' => 'DefaultBrand', 'config' => 1], + 'd2_vehicle_type' => ['type' => 'varchar(128)', 'label' => 'VehicleType', 'enabled' => 1, 'position' => 150, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'd21_vehicle_cnit' => ['type' => 'varchar(128)', 'label' => 'VehicleCNIT', 'enabled' => 1, 'position' => 160, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'd3_vehicle_model' => ['type' => 'varchar(128)', 'label' => 'VehicleModel', 'enabled' => 1, 'position' => 170, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'e_vehicle_serial_number' => ['type' => 'varchar(128)', 'label' => 'VehicleSerialNumber', 'enabled' => 1, 'position' => 180, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'f1_technical_ptac' => ['type' => 'integer', 'label' => 'TechnicalPTAC', 'enabled' => 1, 'position' => 190, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'f2_ptac' => ['type' => 'integer', 'label' => 'PTAC', 'enabled' => 1, 'position' => 200, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'f3_ptra' => ['type' => 'integer', 'label' => 'PTRA', 'enabled' => 1, 'position' => 210, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'g_vehicle_weight' => ['type' => 'integer', 'label' => 'VehicleWeight', 'enabled' => 1, 'position' => 220, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'g1_vehicle_empty_weight' => ['type' => 'integer', 'label' => 'VehicleEmptyWeight', 'enabled' => 1, 'position' => 230, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'h_validity_period' => ['type' => 'varchar(128)', 'label' => 'ValidityPeriod', 'enabled' => 1, 'position' => 240, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'i_vehicle_registration_date' => ['type' => 'datetime', 'label' => 'VehicleRegistrationDate', 'enabled' => 1, 'position' => 250, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'j_vehicle_category' => ['type' => 'varchar(128)', 'label' => 'VehicleCategory', 'enabled' => 1, 'position' => 260, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'j1_national_type' => ['type' => 'varchar(128)', 'label' => 'NationalType', 'enabled' => 1, 'position' => 270, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'j2_european_bodywork' => ['type' => 'varchar(128)', 'label' => 'EuropeanBodyWork', 'enabled' => 1, 'position' => 280, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'j3_national_bodywork' => ['type' => 'varchar(128)', 'label' => 'NationalBodyWork', 'enabled' => 1, 'position' => 290, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'k_type_approval_number' => ['type' => 'varchar(128)', 'label' => 'TypeApprovalNumber', 'enabled' => 1, 'position' => 300, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'p1_cylinder_capacity' => ['type' => 'integer', 'label' => 'CylinderCapacity', 'enabled' => 1, 'position' => 310, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'p2_maximum_net_power' => ['type' => 'integer', 'label' => 'MaximumNetPower', 'enabled' => 1, 'position' => 320, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'p3_fuel_type' => ['type' => 'varchar(128)', 'label' => 'FuelType', 'enabled' => 1, 'position' => 330, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'p6_national_administrative_power' => ['type' => 'integer', 'label' => 'NationalAdministrativePower', 'enabled' => 1, 'position' => 340, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'q_power_to_weight_ratio' => ['type' => 'integer', 'label' => 'PowerToWeightRatio', 'enabled' => 1, 'position' => 350, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 's1_seating_capacity' => ['type' => 'integer', 'label' => 'SeatingCapacity', 'enabled' => 1, 'position' => 360, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 's2_standing_capacity' => ['type' => 'integer', 'label' => 'StationaryCapacity', 'enabled' => 1, 'position' => 370, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'u1_stationary_noise_level' => ['type' => 'integer', 'label' => 'StationaryNoiseLevel', 'enabled' => 1, 'position' => 380, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'u2_motor_speed' => ['type' => 'integer', 'label' => 'MotorSpeed', 'enabled' => 1, 'position' => 390, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'v7_co2_emission' => ['type' => 'integer', 'label' => 'CO2Emission', 'enabled' => 1, 'position' => 400, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'v9_environmental_category' => ['type' => 'varchar(128)', 'label' => 'EnvironmentalCategory', 'enabled' => 1, 'position' => 410, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'x1_first_technical_inspection_date' => ['type' => 'datetime', 'label' => 'FirstTechnicalInspectionDate', 'enabled' => 1, 'position' => 420, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'y1_regional_tax' => ['type' => 'double(24,8)', 'label' => 'RegionalTax', 'enabled' => 1, 'position' => 430, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'y2_professional_tax' => ['type' => 'double(24,8)', 'label' => 'ProfessionalTax', 'enabled' => 1, 'position' => 440, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'y3_ecological_tax' => ['type' => 'double(24,8)', 'label' => 'EcologicalTax', 'enabled' => 1, 'position' => 450, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'y4_management_tax' => ['type' => 'double(24,8)', 'label' => 'ManagementTax', 'enabled' => 1, 'position' => 460, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'y5_forwarding_expenses_tax' => ['type' => 'double(24,8)', 'label' => 'ForwardingExpensesTax', 'enabled' => 1, 'position' => 470, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'y6_total_price_vehicle_registration' => ['type' => 'double(24,8)', 'label' => 'TotalPriceVehicleRegistration', 'enabled' => 1, 'position' => 480, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'z1_specific_details' => ['type' => 'html', 'label' => 'SpecificDetails1', 'enabled' => 1, 'position' => 490, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'z2_specific_details' => ['type' => 'html', 'label' => 'SpecificDetails2', 'enabled' => 1, 'position' => 500, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'z3_specific_details' => ['type' => 'html', 'label' => 'SpecificDetails3', 'enabled' => 1, 'position' => 510, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'z4_specific_details' => ['type' => 'html', 'label' => 'SpecificDetails4', 'enabled' => 1, 'position' => 520, 'notnull' => 0, 'visible' => 3, 'config' => 1], + 'json' => ['type' => 'html', 'label' => 'JSON', 'enabled' => 1, 'position' => 530, 'notnull' => 0, 'visible' => 0], + 'fk_product' => ['type' => 'integer:Product:product/class/product.class.php:1', 'label' => 'Product', 'picto' => 'product', 'enabled' => 1, 'position' => 12, 'notnull' => 0, 'visible' => 1, 'index' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'foreignkey' => 'product.rowid'], + 'fk_lot' => ['type' => 'integer:Productlot:product/stock/class/productlot.class.php:1', 'label' => 'DolicarBatch', 'picto' => 'lot', 'enabled' => 1, 'position' => 13, 'notnull' => 0, 'visible' => 5, 'index' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'foreignkey' => 'productlot.rowid'], + 'fk_soc' => ['type' => 'integer:Societe:societe/class/societe.class.php:1', 'label' => 'ThirdParty', 'picto' => 'company', 'enabled' => 1, 'position' => 14, 'notnull' => 0, 'visible' => 1, 'index' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'foreignkey' => 'societe.rowid'], + 'fk_project' => ['type' => 'integer:Project:projet/class/project.class.php:1', 'label' => 'Project', 'picto' => 'project', 'enabled' => 1, 'position' => 15, 'notnull' => 0, 'visible' => 1, 'index' => 1, 'css' => 'maxwidth500 widthcentpercentminusxx', 'foreignkey' => 'projet.rowid'], + 'fk_user_creat' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'picto' => 'user', 'enabled' => 1, 'position' => 540, 'notnull' => 1, 'visible' => 0, 'foreignkey' => 'user.rowid'], + 'fk_user_modif' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'picto' => 'user', 'enabled' => 1, 'position' => 550, 'notnull' => 0, 'visible' => 0, 'foreignkey' => 'user.rowid'] + ]; + /** + * @var int ID + */ + public int $rowid; - /** - * Constructor - * - * @param DoliDb $db Database handler - */ - public function __construct(DoliDB $db) - { - global $conf, $langs; + /** + * @var string Ref + */ + public $ref; - $this->db = $db; + /** + * @var string Ref ext + */ + public $ref_ext; - 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; - } + /** + * @var int Entity + */ + public $entity; - // Example to show how to set values of fields definition dynamically - /*if ($user->rights->dolicar->registrationcertificatefr->read) { - $this->fields['myfield']['visible'] = 1; - $this->fields['myfield']['noteditable'] = 0; - }*/ + /** + * @var int|string Creation date + */ + public $date_creation; - // Unset fields that are disabled - foreach ($this->fields as $key => $val) { - if (isset($val['enabled']) && empty($val['enabled'])) { - unset($this->fields[$key]); - } - } + /** + * @var int|string Timestamp + */ + public $tms; - // Translate some data of arrayofkeyval - if (is_object($langs)) { - foreach ($this->fields as $key => $val) { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { - foreach ($val['arrayofkeyval'] as $key2 => $val2) { - $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); - } - } - } - } - } + /** + * @var string Import key + */ + public $import_key; - /** - * 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) - { - global $conf, $langs; - $registrationNumber = $this->a_registration_number; - $registrationNumber = strtoupper($registrationNumber); + /** + * @var int Status + */ + public $status = 1; + + public $fk_soc; + public $a_registration_number; + public $b_first_registration_date; + public $c1_owner_fullname; + public $c3_registration_address; + public $c41_ownerNumber; + public $c41_second_owner_name; + public $e_vehicle_serial_number; + public $f1_techincal_ptac; + public $f2_ptac; + public $c4a_owner_vehicle; + public $fk_product; + public $d1_vehicle_brand; + public $d2_vehicle_type; + public $d21_vehicle_cnit; + public $d3_vehicle_model; + public $f3_ptra; + public $g_vehicle_weight; + public $g1_vehicle_empty_weight; + public $h_validity_period; + public $i_vehicle_registration_date; + public $j_vehicleCategory; + public $j1_national_type; + public $j2_european_bodywork; + public $j3_national_bodywork; + public $k_type_approval_number; + public $p1_cylinder_capacity; + public $p2_maximum_net_power; + public $p3_fuel_type; + public $p6_national_administrative_power; + public $q_power_to_weight_ratio; + public $s1_seatingCapacity; + public $s2_standing_capacity; + public $u1_stationary_noise_level; + public $u2_motor_speed; + public $v7_co2_emission; + public $v9_environmental_category; + public $x1_first_technical_inspection_date; + public $y1_regional_tax; + public $y2_professional_tax; + public $y3_ecological_tax; + public $y4_management_tax; + public $y5_forwarding_expenses_tax; + public $y6_total_price_vehicle_registration; + public $z1_specific_details; + public $z2_specific_details; + public $z3_specific_details; + public $z4_specific_details; + public $fk_project; + public $fk_lot; + public $json; - $registrationNumber = normalize_registration_number($registrationNumber); + /** + * @var int User ID + */ + public $fk_user_creat; - $this->a_registration_number = $registrationNumber; - $this->ref = $registrationNumber; - $this->status = 1; - if (empty($this->fk_lot) || $this->fk_lot == -1) { - $lot_id = createDefaultLot($this->fk_product); - $this->fk_lot = $lot_id; - } - if (empty($this->fk_product) || $this->fk_product == -1) { - $this->fk_product = $conf->global->DOLICAR_DEFAULT_VEHICLE; - } - if (empty($this->d1_vehicle_brand) || $this->d1_vehicle_brand == -1) { - $this->d1_vehicle_brand = $langs->trans('DefaultBrand'); - } + /** + * @var int|null User ID + */ + public $fk_user_modif; - $resultcreate = $this->createCommon($user, $notrigger); + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; - return $resultcreate; - } + parent::__construct($db, $this->module, $this->element); - /** - * 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; + foreach ($this->fields as $key => $val) { + if ($val['config'] == 1) { + $confName = 'DOLICAR_' . dol_strtoupper($key) . '_VISIBLE'; + if ($conf->global->$confName == 0) { + $this->fields[$key]['visible'] = 0; + } + } + } + } - dol_syslog(__METHOD__, LOG_DEBUG); + /** + * 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, bool $notrigger = false): int + { + global $langs; - $object = new self($this->db); + $registrationNumber = normalize_registration_number(dol_strtoupper($this->a_registration_number)); + $this->ref = $registrationNumber; + $this->a_registration_number = $registrationNumber; - $this->db->begin(); + if (empty($this->fk_product) || $this->fk_product == -1) { + $this->fk_product = getDolGlobalInt('DOLICAR_DEFAULT_VEHICLE'); + } + $this->fk_lot = create_default_product_lot($this->fk_product); + if (empty($this->d1_vehicle_brand) || $this->d1_vehicle_brand == -1) { + $this->d1_vehicle_brand = $langs->transnoentities('DefaultBrand'); + } - // Load source object - $result = $object->fetchCommon($fromid); - if ($result > 0 && !empty($object->table_element_line)) { - $object->fetchLines(); - } + return $this->createCommon($user, $notrigger); + } - // get lines so they will be clone - //foreach($this->lines as $line) - // $line->fetch_optionals(); + /** + * 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, bool $notrigger = false): int + { + global $langs; - // Reset some properties - unset($object->id); - unset($object->fk_user_creat); - unset($object->import_key); + $registrationNumber = normalize_registration_number(dol_strtoupper($this->a_registration_number)); + $this->ref = $registrationNumber; + $this->a_registration_number = $registrationNumber; - // Clear fields - if (property_exists($object, 'ref')) { - $object->ref = $object->a_registration_number; - } - if (property_exists($object, 'label')) { - $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default']; - } - if (property_exists($object, 'status')) { - $object->status = self::STATUS_VALIDATED; - } - if (property_exists($object, 'date_creation')) { - $object->date_creation = dol_now(); - } - if (property_exists($object, 'date_modification')) { - $object->date_modification = null; - } - // ... - // 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]); - } - } - } + if (empty($this->d1_vehicle_brand) || $this->d1_vehicle_brand == -1) { + $this->d1_vehicle_brand = $langs->transnoentities('DefaultBrand'); + } + return $this->updateCommon($user, $notrigger); + } - // Create clone - $object->context['createfromclone'] = 'createfromclone'; - $result = $object->createCommon($user); - if ($result < 0) { - $error++; - $this->error = $object->error; - $this->errors = $object->errors; - } + /** + * 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(int $status, int $mode = 0): string + { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; - if (!$error) { - // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) { - $error++; - } - } + $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatus[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); - if (!$error) { - // copy external contacts if same company - if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) { - if ($this->copy_linked_contact($object, 'external') < 0) { - $error++; - } - } - } + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatusShort[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); + } - unset($object->context['createfromclone']); + $statusType = 'status' . $status; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } + if ($status == self::STATUS_ARCHIVED) { + $statusType = 'status8'; + } - // End - if (!$error) { - $this->db->commit(); - return $object; - } else { - $this->db->rollback(); - return -1; - } - } + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); + } /** - * Load object in memory from the database + * Sets object to supplied categories * - * @param int|string $id ID object - * @param string|null $ref Ref - * @param string $morewhere More SQL filters (' AND ...') - * @return int 0 < if KO, 0 if not found, > 0 if OK + * Deletes object from existing categories not supplied + * Adds it to non-existing supplied categories + * Existing categories are left untouched + * + * @param int[]|int $categories Category or categories IDs + * @return string */ - public function fetch($id, string $ref = null, string $morewhere = ''): int + public function setCategories($categories): string { - $result = $this->fetchCommon($id, $ref, $morewhere); - if ($result > 0 && !empty($this->table_element_line)) { - $this->fetchLines(); - } - return $result; + return ''; } - /** - * 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('t'); - $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." = ".((int) $value); - } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) { - $sqlwhere[] = $key." = '".$this->db->idate($value)."'"; - } elseif ($key == 'customsql') { - $sqlwhere[] = $value; - } elseif (strpos($value, '%') === false) { - $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($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) - { - global $langs; - $this->ref = $this->a_registration_number; - if (empty($this->d1_vehicle_brand) || $this->d1_vehicle_brand == -1) { - $this->d1_vehicle_brand = $langs->trans('DefaultBrand'); - } - 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); - } - - - /** - * 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->dolicar->registrationcertificatefr->write)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->dolicar->registrationcertificatefr->registrationcertificatefr_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('REGISTRATIONCERTIFICATEFR_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 = 'registrationcertificatefr/".$this->db->escape($this->newref)."'"; - $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'registrationcertificatefr/".$this->db->escape($this->ref)."' and entity = ".$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->dolicar->dir_output.'/registrationcertificatefr/'.$oldref; - $dirdest = $conf->dolicar->dir_output.'/registrationcertificatefr/'.$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->dolicar->dir_output.'/registrationcertificatefr/'.$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 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->dolicar->write)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->dolicar->dolicar_advance->validate)))) - { - $this->error='Permission denied'; - return -1; - }*/ - - return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'REGISTRATIONCERTIFICATEFR_CANCEL'); - } - - /** - * 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->dolicar->write)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->dolicar->dolicar_advance->validate)))) - { - $this->error='Permission denied'; - return -1; - }*/ - - return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'REGISTRATIONCERTIFICATEFR_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 = img_picto('', $this->picto).' '.$langs->trans("RegistrationCertificateFr").''; - if (isset($this->status)) { - $label .= ' '.$this->getLibStatut(5); - } - $label .= '
'; - $label .= ''.$langs->trans('Ref').': '.$this->ref; - - $url = dol_buildpath('/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1).'?id='.$this->id; - - if ($option != 'nolink') { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { - $add_save_lastsearch_values = 1; - } - if ($url && $add_save_lastsearch_values) { - $url .= '&save_lastsearch_values=1'; - } - } - - $linkclose = ''; - if (empty($notooltip)) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label = $langs->trans("ShowRegistrationCertificateFr"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else { - $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); - } - - if ($option == 'nolink' || empty($url)) { - $linkstart = ''; - if ($option == 'nolink' || empty($url)) { - $linkend = ''; - } else { - $linkend = ''; - } - - $result .= $linkstart; - - if (empty($this->showphoto_on_popup)) { - if ($withpicto) { - $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - } - } else { - if ($withpicto) { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - - list($class, $module) = explode('@', $this->picto); - $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref); - $filearray = dol_dir_list($upload_dir, "files"); - $filename = $filearray[0]['name']; - if (!empty($filename)) { - $pospoint = strpos($filearray[0]['name'], '.'); - - $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint); - if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) { - $result .= '
No photo
'; - } else { - $result .= '
No photo
'; - } - - $result .= ''; - } else { - $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - } - } - } - - if ($withpicto != 2) { - $result .= $this->ref; - } - - $result .= $linkend; - //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); - - global $action, $hookmanager; - $hookmanager->initHooks(array('registrationcertificatefrdao')); - $parameters = array('id'=>$this->id, 'getnomurl'=>$result); - $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) { - $result = $hookmanager->resPrint; - } else { - $result .= $hookmanager->resPrint; - } - - return $result; - } - - /** - * Return the label of the status - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto - * @return string Label of status - */ - public function getLabelStatus($mode = 0) - { - return $this->LibStatut($this->status, $mode); - } - - /** - * Return the label of the status - * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto - * @return string Label of status - */ - public function 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("dolicar@dolicar"); - $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); - $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); - } - - $statusType = 'status'.$status; - - 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 (!empty($obj->fk_user_author)) { - $cuser = new User($this->db); - $cuser->fetch($obj->fk_user_author); - $this->user_creation = $cuser; - } - - if (!empty($obj->fk_user_valid)) { - $vuser = new User($this->db); - $vuser->fetch($obj->fk_user_valid); - $this->user_validation = $vuser; - } - - if (!empty($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() - { - // Set here init that are not commonf fields - // $this->property1 = ... - // $this->property2 = ... - - $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 RegistrationCertificateFrLine($this->db); - $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_registrationcertificatefr = '.((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("dolicar@dolicar"); - - if (empty($conf->global->DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON)) { - $conf->global->DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON = 'mod_registrationcertificatefr_standard'; - } - - if (!empty($conf->global->DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON)) { - $mybool = false; - - $file = $conf->global->DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON.".php"; - $classname = $conf->global->DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON; - - // Include file with class - $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/dolicar/"); - - // 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 ""; - } - } - - /** - * Output html form to select a third party. - * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company. - * - * @param string $selected Preselected type - * @param string $htmlname Name of field in form - * @param string $filter Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)') - * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') - * @param int $forcecombo Force to use standard HTML select component without beautification - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $limit Limit number of answers - * @param string $morecss Add more css styles to the SELECT component - * @param int $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container - * @param bool $multiple add [] in the name of element and add 'multiple' attribut - * @param int $noroot - * @return string HTML string with - * @throws Exception - */ - public function selectRegistrationCertificateList($selected = '', $htmlname = 'options_registrationcertificatefr', $filter = [], $showempty = '1', $forcecombo = 0, $events = array(), $outputmode = 0, $limit = 0, $morecss = 'minwidth100 maxwidth300', $moreparam = 0, $multiple = false, $noroot = 0, $contextpage = '', $multientitymanagedoff = true) - { - global $form; + /** + * Get linked object from extrafields on registration certificate + * + * @param string $objectType Object type + * @return array|int Int 0 < if KO, array of records if OK + */ + public function getLinkedObject(string $objectType) + { + $sql = 'SELECT *'; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $objectType . '_extrafields as t'; + $sql .= ' WHERE 1 = 1'; + $sql .= ' AND registrationcertificatefr = ' . $this->id; + $sql .= ' ORDER BY t.mileage DESC'; + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + $records = []; + while ($i < $num) { + $obj = $this->db->fetch_object($resql); + $records[$objectType][$obj->fk_object] = $obj->fk_object; + $i++; + } + $this->db->free($resql); - $product = new Product($this->db); + return $records; + } else { + $this->errors[] = 'Error ' . $this->db->lasterror(); + return -1; + } + } - $objectList = saturne_fetch_all_object_type('registrationcertificatefr', '', '', $limit, 0, $filter); - $registrationCertificatesData = []; - if (is_array($objectList) && !empty($objectList)) { - foreach ($objectList as $registrationCertificate) { - $product->fetch($registrationCertificate->fk_product); - $registrationCertificatesData[$registrationCertificate->id] = $registrationCertificate->ref . ' - ' . $product->label; + /** + * Get linked objects + * + * @return array array of linked objects + */ + { + $linkedObjects = []; + $objectTypes = ['propal', 'commande', 'facture']; + foreach ($objectTypes as $objectType) { + $linkedObject = $this->getLinkedObject($objectType); + if (is_array($linkedObject) && !empty($linkedObject)) { + $linkedObjects[] = $linkedObject; + public function getLinkedObjects(): array } } - return $form::selectarray($htmlname, $registrationCertificatesData, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss); - } - - /** - * 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("dolicar@dolicar"); - - if (!dol_strlen($modele)) { - $modele = 'standard_registrationcertificatefr'; - - if (!empty($this->model_pdf)) { - $modele = $this->model_pdf; - } elseif (!empty($conf->global->REGISTRATIONCERTIFICATEFR_ADDON_PDF)) { - $modele = $conf->global->REGISTRATIONCERTIFICATEFR_ADDON_PDF; - } - } - - $modelpath = "core/modules/dolicar/doc/"; - - if ($includedocgeneration && !empty($modele)) { - $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; - } - - /** - * 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 getFactureLinked() - { - global $conf; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $records = array(); - - $sql = "SELECT *"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture_extrafields as t"; - $sql .= " WHERE 1 = 1"; - $sql .= ' AND registrationcertificatefr =' . $this->id; - $sql .= ' ORDER BY t.mileage DESC'; - - $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); - - $records['facture'][$obj->fk_object] = $obj->fk_object; - - $i++; - } - $this->db->free($resql); - - return $records; - } else { - $this->errors[] = 'Error '.$this->db->lasterror(); - dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - - return -1; - } - } - - - /** - * 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 getFactureDetLinked() - { - global $conf; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $records = array(); - - $sql = "SELECT *"; - $sql .= " FROM ".MAIN_DB_PREFIX."facturedet_extrafields as t"; - $sql .= " WHERE 1 = 1"; - $sql .= ' AND registrationcertificatefr =' . $this->id; - $sql .= ' ORDER BY t.mileage DESC'; - - $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); - - $records['facturedet'][$obj->fk_object] = $obj->fk_object; - - $i++; - } - $this->db->free($resql); - - return $records; - } else { - $this->errors[] = 'Error '.$this->db->lasterror(); - dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - - return -1; - } - } - - /** - * 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 getPropalLinked() - { - global $conf; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $records = array(); - - $sql = "SELECT *"; - $sql .= " FROM ".MAIN_DB_PREFIX."propal_extrafields as t"; - $sql .= " WHERE 1 = 1"; - $sql .= ' AND registrationcertificatefr =' . $this->id; - $sql .= ' ORDER BY t.mileage DESC'; - - $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); - - $records['propal'][$obj->fk_object] = $obj->fk_object; - - $i++; - } - $this->db->free($resql); - - return $records; - } else { - $this->errors[] = 'Error '.$this->db->lasterror(); - dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - - return -1; - } - } - - /** - * 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 getPropalDetLinked() - { - global $conf; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $records = array(); - - $sql = "SELECT *"; - $sql .= " FROM ".MAIN_DB_PREFIX."propaldet_extrafields as t"; - $sql .= " WHERE 1 = 1"; - $sql .= ' AND registrationcertificatefr =' . $this->id; - $sql .= ' ORDER BY t.mileage DESC'; - - $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); - - $records['propaldet'][$obj->fk_object] = $obj->fk_object; - - $i++; - } - $this->db->free($resql); - - return $records; - } else { - $this->errors[] = 'Error '.$this->db->lasterror(); - dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - - return -1; - } - } - - /** - * 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 getCommandeLinked() - { - global $conf; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $records = array(); - - $sql = "SELECT *"; - $sql .= " FROM ".MAIN_DB_PREFIX."commande_extrafields as t"; - $sql .= " WHERE 1 = 1"; - $sql .= ' AND registrationcertificatefr =' . $this->id; - $sql .= ' ORDER BY t.mileage DESC'; - - $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); - - $records['commande'][$obj->fk_object] = $obj->fk_object; - - $i++; - } - $this->db->free($resql); - - return $records; - } else { - $this->errors[] = 'Error '.$this->db->lasterror(); - dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - - return -1; - } - } - - /** - * 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 getCommandeDetLinked() - { - global $conf; - - dol_syslog(__METHOD__, LOG_DEBUG); - - $records = array(); - - $sql = "SELECT *"; - $sql .= " FROM ".MAIN_DB_PREFIX."commandedet_extrafields as t"; - $sql .= " WHERE 1 = 1"; - $sql .= ' AND registrationcertificatefr =' . $this->id; - $sql .= ' ORDER BY t.mileage DESC'; - - $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); - - $records['commandedet'][$obj->fk_object] = $obj->fk_object; - - $i++; - } - $this->db->free($resql); - - return $records; - } else { - $this->errors[] = 'Error '.$this->db->lasterror(); - dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); - - return -1; - } - } - - /** - * 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 getObjectsLinked() - { - $facture_list = $this->getFactureLinked(); - $facturedet_list = $this->getFactureDetLinked(); - $propal_list = $this->getPropalLinked(); - $propaldet_list = $this->getPropalDetLinked(); - $commande_list = $this->getCommandeLinked(); - $commandedet_list = $this->getCommandeDetLinked(); - - - return array_merge($facture_list, $facturedet_list, $propal_list, $propaldet_list, $commande_list, $commandedet_list); - } -} - - -require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; - -/** - * Class RegistrationCertificateFrLine. You can also remove this and generate a CRUD class for lines objects. - */ -class RegistrationCertificateFrLine extends CommonObjectLine -{ - // To complete with content of an object RegistrationCertificateFrLine - // We should have a field rowid, fk_registrationcertificatefr 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; - } + return $linkedObjects; + } } diff --git a/core/modules/dolicar/doc/doc_generic_registrationcertificatefr_odt.modules.php b/core/modules/dolicar/doc/doc_generic_registrationcertificatefr_odt.modules.php deleted file mode 100644 index 577c8d1..0000000 --- a/core/modules/dolicar/doc/doc_generic_registrationcertificatefr_odt.modules.php +++ /dev/null @@ -1,512 +0,0 @@ - - * Copyright (C) 2012 Juanjo Menent - * Copyright (C) 2014 Marcos García - * Copyright (C) 2016 Charlie Benke - * Copyright (C) 2018-2021 Philippe Grand - * Copyright (C) 2018 Frédéric France - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * or see https://www.gnu.org/ - */ - -/** - * \file htdocs/core/modules/dolicar/doc/doc_generic_registrationcertificatefr_odt.modules.php - * \ingroup dolicar - * \brief File of class to build ODT documents for registrationcertificatefrs - */ - -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/files.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/doc.lib.php'; - -require_once __DIR__ . '/../../../core/modules/dolicar/modules_registrationcertificatefr.php'); - -/** - * Class to build documents using ODF templates generator - */ -class doc_generic_registrationcertificatefr_odt extends ModelePDFRegistrationCertificateFr -{ - /** - * Issuer - * @var Societe - */ - public $emetteur; - - /** - * @var array Minimum version of PHP required by module. - * e.g.: PHP ≥ 5.6 = array(5, 6) - */ - public $phpmin = array(5, 6); - - /** - * @var string Dolibarr version of the loaded document - */ - public $version = 'dolibarr'; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $conf, $langs, $mysoc; - - // Load translation files required by the page - $langs->loadLangs(array("main", "companies")); - - $this->db = $db; - $this->name = "ODT templates"; - $this->description = $langs->trans("DocumentModelOdt"); - $this->scandir = 'DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON_PDF_ODT_PATH'; // Name of constant that is used to save list of directories to scan - - // Page size for A4 format - $this->type = 'odt'; - $this->page_largeur = 0; - $this->page_hauteur = 0; - $this->format = array($this->page_largeur, $this->page_hauteur); - $this->marge_gauche = 0; - $this->marge_droite = 0; - $this->marge_haute = 0; - $this->marge_basse = 0; - - $this->option_logo = 1; // Display logo - $this->option_tva = 0; // Manage the vat option FACTURE_TVAOPTION - $this->option_modereg = 0; // Display payment mode - $this->option_condreg = 0; // Display payment terms - $this->option_codeproduitservice = 0; // 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 = 0; // Support add of a watermark on drafts - - // Get source company - $this->emetteur = $mysoc; - if (!$this->emetteur->country_code) { - $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined - } - } - - - /** - * Return description of a module - * - * @param Translate $langs Lang object to use for output - * @return string Description - */ - public function info($langs) - { - global $conf, $langs; - - // Load translation files required by the page - $langs->loadLangs(array("errors", "companies")); - - $form = new Form($this->db); - - $texte = $this->description.".
\n"; - $texte .= '
'; - $texte .= ''; - $texte .= ''; - $texte .= ''; - $texte .= ''; - $texte .= ''; - - // List of directories area - $texte .= ''; - - // Add input to upload a new template file. - $texte .= '
'.$langs->trans("UploadNewTemplate").' '; - $texte .= ''; - $texte .= ''; - $texte .= '
'; - $texte .= ''; - - $texte .= ''; - $texte .= ''; - - $texte .= '
'; - $texttitle = $langs->trans("ListOfDirectories"); - $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON_PDF_ODT_PATH))); - $listoffiles = array(); - foreach ($listofdir as $key => $tmpdir) { - $tmpdir = trim($tmpdir); - $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); - if (!$tmpdir) { - unset($listofdir[$key]); - continue; - } - if (!is_dir($tmpdir)) { - $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0); - } else { - $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.(ods|odt)'); - if (count($tmpfiles)) { - $listoffiles = array_merge($listoffiles, $tmpfiles); - } - } - } - $texthelp = $langs->trans("ListOfDirectoriesForModelGenODT"); - // Add list of substitution keys - $texthelp .= '
'.$langs->trans("FollowingSubstitutionKeysCanBeUsed").'
'; - $texthelp .= $langs->transnoentitiesnoconv("FullListOnOnlineDocumentation"); // This contains an url, we don't modify it - - $texte .= $form->textwithpicto($texttitle, $texthelp, 1, 'help', '', 1); - $texte .= '
'; - $texte .= ''; - $texte .= '
'; - $texte .= ''; - $texte .= '
'; - - // Scan directories - $nbofiles = count($listoffiles); - if (!empty($conf->global->DOLICAR_REGISTRATIONCERTIFICATEFR_ADDON_PDF_ODT_PATH)) { - $texte .= $langs->trans("NumberOfModelFilesFound").': '; - //$texte.=$nbofiles?'':''; - $texte .= count($listoffiles); - //$texte.=$nbofiles?'':''; - $texte .= ''; - } - - if ($nbofiles) { - $texte .= ''; - } - - $texte .= '
'; - $texte .= ''; - $texte .= $langs->trans("ExampleOfDirectoriesForModelGen"); - $texte .= ''; - $texte .= '
'; - $texte .= '
'; - - return $texte; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Function to build a document on disk using the generic odt module. - * - * @param RegistrationCertificateFr $object Object source to build document - * @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 if OK, <=0 if KO - */ - public function write_file($object, $outputlangs, $srctemplatepath, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - // phpcs:enable - global $user, $langs, $conf, $mysoc, $hookmanager; - - if (empty($srctemplatepath)) { - dol_syslog("doc_generic_odt::write_file parameter srctemplatepath empty", LOG_WARNING); - return -1; - } - - // Add odtgeneration hook - if (!is_object($hookmanager)) { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($this->db); - } - $hookmanager->initHooks(array('odtgeneration')); - global $action; - - if (!is_object($outputlangs)) { - $outputlangs = $langs; - } - $sav_charset_output = $outputlangs->charset_output; - $outputlangs->charset_output = 'UTF-8'; - - $outputlangs->loadLangs(array("main", "dict", "companies", "bills")); - - if ($conf->dolicar->dir_output) { - // If $object is id instead of object - if (!is_object($object)) { - $id = $object; - $object = new RegistrationCertificateFr($this->db); - $result = $object->fetch($id); - if ($result < 0) { - dol_print_error($this->db, $object->error); - return -1; - } - } - - $object->fetch_thirdparty(); - - $dir = $conf->dolicar->multidir_output[isset($object->entity) ? $object->entity : 1]; - $objectref = dol_sanitizeFileName($object->ref); - if (!preg_match('/specimen/i', $objectref)) { - $dir .= "/".$objectref; - } - $file = $dir."/".$objectref.".odt"; - - if (!file_exists($dir)) { - if (dol_mkdir($dir) < 0) { - $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); - return -1; - } - } - - if (file_exists($dir)) { - //print "srctemplatepath=".$srctemplatepath; // Src filename - $newfile = basename($srctemplatepath); - $newfiletmp = preg_replace('/\.od(t|s)/i', '', $newfile); - $newfiletmp = preg_replace('/template_/i', '', $newfiletmp); - $newfiletmp = preg_replace('/modele_/i', '', $newfiletmp); - $newfiletmp = $objectref.'_'.$newfiletmp; - //$file=$dir.'/'.$newfiletmp.'.'.dol_print_date(dol_now(),'%Y%m%d%H%M%S').'.odt'; - // Get extension (ods or odt) - $newfileformat = substr($newfile, strrpos($newfile, '.') + 1); - if (!empty($conf->global->MAIN_DOC_USE_TIMING)) { - $format = $conf->global->MAIN_DOC_USE_TIMING; - if ($format == '1') { - $format = '%Y%m%d%H%M%S'; - } - $filename = $newfiletmp.'-'.dol_print_date(dol_now(), $format).'.'.$newfileformat; - } else { - $filename = $newfiletmp.'.'.$newfileformat; - } - $file = $dir.'/'.$filename; - //print "newdir=".$dir; - //print "newfile=".$newfile; - //print "file=".$file; - //print "conf->societe->dir_temp=".$conf->societe->dir_temp; - - dol_mkdir($conf->dolicar->dir_temp); - if (!is_writable($conf->dolicar->dir_temp)) { - $this->error = "Failed to write in temp directory ".$conf->dolicar->dir_temp; - dol_syslog('Error in write_file: '.$this->error, LOG_ERR); - return -1; - } - - // If CUSTOMER contact defined on order, we use it - $usecontact = false; - $arrayidcontact = $object->getIdContact('external', 'CUSTOMER'); - if (count($arrayidcontact) > 0) { - $usecontact = true; - $result = $object->fetch_contact($arrayidcontact[0]); - } - - // Recipient name - $contactobject = null; - if (!empty($usecontact)) { - // We can use the company of contact instead of thirdparty company - if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT))) { - $object->contact->fetch_thirdparty(); - $socobject = $object->contact->thirdparty; - $contactobject = $object->contact; - } else { - $socobject = $object->thirdparty; - // if we have a CUSTOMER contact and we dont use it as thirdparty recipient we store the contact object for later use - $contactobject = $object->contact; - } - } else { - $socobject = $object->thirdparty; - } - - // Make substitution - $substitutionarray = array( - '__FROM_NAME__' => $this->emetteur->name, - '__FROM_EMAIL__' => $this->emetteur->email, - '__TOTAL_TTC__' => $object->total_ttc, - '__TOTAL_HT__' => $object->total_ht, - '__TOTAL_VAT__' => $object->total_tva - ); - complete_substitutions_array($substitutionarray, $langs, $object); - // Call the ODTSubstitution hook - $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$substitutionarray); - $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - - // Line of free text - $newfreetext = ''; - $paramfreetext = 'ORDER_FREE_TEXT'; - if (!empty($conf->global->$paramfreetext)) { - $newfreetext = make_substitutions($conf->global->$paramfreetext, $substitutionarray); - } - - // Open and load template - require_once ODTPHP_PATH.'odf.php'; - try { - $odfHandler = new odf( - $srctemplatepath, - array( - 'PATH_TO_TMP' => $conf->dolicar->dir_temp, - 'ZIP_PROXY' => 'PclZipProxy', // PhpZipProxy or PclZipProxy. Got "bad compression method" error when using PhpZipProxy. - 'DELIMITER_LEFT' => '{', - 'DELIMITER_RIGHT' => '}' - ) - ); - } catch (Exception $e) { - $this->error = $e->getMessage(); - dol_syslog($e->getMessage(), LOG_INFO); - return -1; - } - // After construction $odfHandler->contentXml contains content and - // [!-- BEGIN row.lines --]*[!-- END row.lines --] has been replaced by - // [!-- BEGIN lines --]*[!-- END lines --] - //print html_entity_decode($odfHandler->__toString()); - //print exit; - - - // Make substitutions into odt of freetext - try { - $odfHandler->setVars('free_text', $newfreetext, true, 'UTF-8'); - } catch (OdfException $e) { - dol_syslog($e->getMessage(), LOG_INFO); - } - - // Define substitution array - $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object); - $array_object_from_properties = $this->get_substitutionarray_each_var_object($object, $outputlangs); - $array_objet = $this->get_substitutionarray_object($object, $outputlangs); - $array_user = $this->get_substitutionarray_user($user, $outputlangs); - $array_soc = $this->get_substitutionarray_mysoc($mysoc, $outputlangs); - $array_thirdparty = $this->get_substitutionarray_thirdparty($socobject, $outputlangs); - $array_other = $this->get_substitutionarray_other($outputlangs); - // retrieve contact information for use in object as contact_xxx tags - $array_thirdparty_contact = array(); - if ($usecontact && is_object($contactobject)) { - $array_thirdparty_contact = $this->get_substitutionarray_contact($contactobject, $outputlangs, 'contact'); - } - - $tmparray = array_merge($substitutionarray, $array_object_from_properties, $array_user, $array_soc, $array_thirdparty, $array_objet, $array_other, $array_thirdparty_contact); - complete_substitutions_array($tmparray, $outputlangs, $object); - - // Call the ODTSubstitution hook - $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); - $reshook = $hookmanager->executeHooks('ODTSubstitution', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - - foreach ($tmparray as $key => $value) { - try { - if (preg_match('/logo$/', $key)) { - // Image - if (file_exists($value)) { - $odfHandler->setImage($key, $value); - } else { - $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); - } - } else { - // Text - $odfHandler->setVars($key, $value, true, 'UTF-8'); - } - } catch (OdfException $e) { - dol_syslog($e->getMessage(), LOG_INFO); - } - } - // Replace tags of lines - try { - $foundtagforlines = 1; - try { - $listlines = $odfHandler->setSegment('lines'); - } catch (OdfException $e) { - // We may arrive here if tags for lines not present into template - $foundtagforlines = 0; - dol_syslog($e->getMessage(), LOG_INFO); - } - if ($foundtagforlines) { - $linenumber = 0; - foreach ($object->lines as $line) { - $linenumber++; - $tmparray = $this->get_substitutionarray_lines($line, $outputlangs, $linenumber); - complete_substitutions_array($tmparray, $outputlangs, $object, $line, "completesubstitutionarray_lines"); - // Call the ODTSubstitutionLine hook - $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray, 'line'=>$line); - $reshook = $hookmanager->executeHooks('ODTSubstitutionLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - foreach ($tmparray as $key => $val) { - try { - $listlines->setVars($key, $val, true, 'UTF-8'); - } catch (OdfException $e) { - dol_syslog($e->getMessage(), LOG_INFO); - } catch (SegmentException $e) { - dol_syslog($e->getMessage(), LOG_INFO); - } - } - $listlines->merge(); - } - $odfHandler->mergeSegment($listlines); - } - } catch (OdfException $e) { - $this->error = $e->getMessage(); - dol_syslog($this->error, LOG_WARNING); - return -1; - } - - // Replace labels translated - $tmparray = $outputlangs->get_translations_for_substitutions(); - foreach ($tmparray as $key => $value) { - try { - $odfHandler->setVars($key, $value, true, 'UTF-8'); - } catch (OdfException $e) { - dol_syslog($e->getMessage(), LOG_INFO); - } - } - - // Call the beforeODTSave hook - - $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); - $reshook = $hookmanager->executeHooks('beforeODTSave', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - - // Write new file - if (!empty($conf->global->MAIN_ODT_AS_PDF)) { - try { - $odfHandler->exportAsAttachedPDF($file); - } catch (Exception $e) { - $this->error = $e->getMessage(); - dol_syslog($e->getMessage(), LOG_INFO); - return -1; - } - } else { - try { - $odfHandler->saveToDisk($file); - } catch (Exception $e) { - $this->error = $e->getMessage(); - dol_syslog($e->getMessage(), LOG_INFO); - return -1; - } - } - - $parameters = array('odfHandler'=>&$odfHandler, 'file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs, 'substitutionarray'=>&$tmparray); - $reshook = $hookmanager->executeHooks('afterODTCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - - if (!empty($conf->global->MAIN_UMASK)) { - @chmod($file, octdec($conf->global->MAIN_UMASK)); - } - - $odfHandler = null; // Destroy object - - $this->result = array('fullpath'=>$file); - - return 1; // Success - } else { - $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); - return -1; - } - } - - return -1; - } -} diff --git a/core/modules/dolicar/doc/index.php b/core/modules/dolicar/doc/index.php deleted file mode 100644 index cd6990e..0000000 --- a/core/modules/dolicar/doc/index.php +++ /dev/null @@ -1,2 +0,0 @@ - - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2008 Raphael Bertrand - * Copyright (C) 2010-2014 Juanjo Menent - * Copyright (C) 2012 Christophe Battarel - * Copyright (C) 2012 Cédric Salvador - * Copyright (C) 2012-2014 Raphaël Doursenaud - * Copyright (C) 2015 Marcos García - * Copyright (C) 2017 Ferran Marcet - * Copyright (C) 2018 Frédéric France - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * or see https://www.gnu.org/ - */ - -/** - * \file core/modules/dolicar/doc/pdf_standard.modules.php - * \ingroup dolicar - * \brief File of class to generate document from standard template - */ - -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'; - -require_once __DIR__ . '/../../../core/modules/dolicar/modules_registrationcertificatefr.php'; - -/** - * Class to manage PDF template standard_registrationcertificatefr - */ -class pdf_standard_registrationcertificatefr extends ModelePDFRegistrationCertificateFr -{ - /** - * @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.6 = array(5, 6) - */ - public $phpmin = array(5, 6); - - /** - * 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; - - /** - * @var bool Situation invoice type - */ - public $situationinvoice; - - - /** - * @var array of document table columns - */ - public $cols; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $conf, $langs, $mysoc; - - // Translations - $langs->loadLangs(array("main", "bills")); - - $this->db = $db; - $this->name = "standard"; - $this->description = $langs->trans('DocumentModelStandardPDF'); - $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; - - // 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; // used for notes ans other stuff - - - $this->tabTitleHeight = 5; // default height - - // Use new system for position of columns, view $this->defineColumnField() - - $this->tva = array(); - $this->localtax1 = array(); - $this->localtax2 = array(); - $this->atleastoneratenotnull = 0; - $this->atleastonediscount = 0; - $this->situationinvoice = false; - } - - - // 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; - - dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - - 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", "bills", "products", "dict", "companies")); - - 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", "bills", "products", "dict", "companies")); - } - - $nblines = (is_array($object->lines) ? count($object->lines) : 0); - - $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_REGISTRATIONCERTIFICATEFR_WITH_PICTURE)) - { - $objphoto = new Product($this->db); - - for ($i = 0; $i < $nblines; $i++) - { - if (empty($object->lines[$i]->fk_product)) continue; - - //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'); // 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 (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; - - if ($conf->dolicar->dir_output.'/registrationcertificatefr') { - $object->fetch_thirdparty(); - - // Definition of $dir and $file - if ($object->specimen) { - $dir = $conf->dolicar->dir_output.'/registrationcertificatefr'; - $file = $dir."/SPECIMEN.pdf"; - } else { - $objectref = dol_sanitizeFileName($object->ref); - $dir = $conf->dolicar->dir_output.'/registrationcertificatefr/'.$objectref; - $file = $dir."/".$objectref.".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 = (is_array($object->lines) ? count($object->lines) : 0); - - // Create pdf instance - $pdf = pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $pdf->SetAutoPageBreak(1, 0); - - $heightforinfotot = 50; // Height reserved to output the info and total part and payment 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("PdfTitle")); - $pdf->SetCreator("Dolibarr ".DOL_VERSION); - $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); - $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) { - $pdf->SetCompression(false); - } - - // Set certificate - $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; - // If user has no certificate, we try to take the company one - if (!$cert) { - $cert = empty($conf->global->CERTIFICATE_CRT) ? '' : $conf->global->CERTIFICATE_CRT; - } - // If a certificate is found - if ($cert) { - $info = array( - 'Name' => $this->emetteur->name, - 'Location' => getCountry($this->emetteur->country_code, 0), - 'Reason' => 'REGISTRATIONCERTIFICATEFR', - 'ContactInfo' => $this->emetteur->email - ); - $pdf->setSignature($cert, $cert, $this->emetteur->name, '', 2, $info); - } - - $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++; - - $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); - $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); - $tab_height = 130 - $top_shift; - $tab_height_newpage = 150; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) { - $tab_height_newpage -= $top_shift; - } - - $nexY = $tab_top - 1; - - // Display notes - $notetoshow = empty($object->note_public) ? '' : $object->note_public; - // Extrafields in note - $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); - if (!empty($extranote)) { - $notetoshow = dol_concatdesc($notetoshow, $extranote); - } - - $pagenb = $pdf->getPage(); - if ($notetoshow) { - $tab_top -= 2; - - $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); - - $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); - - // Table simulation to know the height of the title line - $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']; - } - } - - // Description of product line - if ($this->getColumnStatus('desc')) { - $pdf->startTransaction(); - - $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); - $pageposafter = $pdf->getPage(); - - if ($pageposafter > $pageposbefore) { // There is a pagebreak - $pdf->rollbackTransaction(true); - $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(); - //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); - } - $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 = $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; - } - - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut - - // 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); - } - - // 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, $outputlangs); - $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 - - - $sign = 1; - // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva - $prev_progress = $object->lines[$i]->get_prev_progress($object->id); - if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) { // Compute progress from previous situation - if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) { - $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; - } else { - $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; - } - } else { - if (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) { - $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; - } else { - $tvaligne = $sign * $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 = isset($localtaxtmp_array[0]) ? $localtaxtmp_array[0] : ''; - $localtax2_type = isset($localtaxtmp_array[2]) ? $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; - - $nexY = max($nexY, $posYAfterImage); - - // 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, $outputlangsbis); - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); - } - $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, $outputlangsbis); - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); - } - $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, $outputlangsbis); - $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, $object->multicurrency_code, $outputlangsbis); - $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; - } - - // Display infos area - //$posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); - - // Display total zone - //$posy = $this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); - - // Display payment area - /* - if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) - { - $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); - } - */ - - // Pagefoot - $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", "FAC_OUTPUTDIR"); - return 0; - } - } - - // 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 - return parent::liste_modeles($db, $maxfilenamelength); // TODO: Change the autogenerated stub - } - - // 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 - * @param Translate $outputlangsbis Langs object bis - * @return void - */ - protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0, $currency = '', $outputlangsbis = null) - { - 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)); - if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) { - $titre .= ' - '.$outputlangsbis->transnoentities("AmountInCurrency", $outputlangsbis->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.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 Translate $outputlangsbis Object lang for output bis - * @return void - */ - protected function _pagehead(&$pdf, $object, $showaddress, $outputlangs, $outputlangsbis = null) - { - global $conf, $langs; - - // Load traductions files required by page - $outputlangs->loadLangs(array("main", "bills", "propal", "companies")); - - $default_font_size = pdf_getPDFFontSize($outputlangs); - - pdf_pagehead($pdf, $outputlangs, $this->page_hauteur); - - // Show Draft Watermark - if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) { - pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); - } - - $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 - 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($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'); - } - } - - $pdf->SetFont('', 'B', $default_font_size + 3); - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - $title = $outputlangs->transnoentities("PdfTitle"); - if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) { - $title .= ' - '; - $title .= $outputlangsbis->transnoentities("PdfTitle"); - } - $pdf->MultiCell($w, 3, $title, '', 'R'); - - $pdf->SetFont('', 'B', $default_font_size); - - $posy += 5; - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - $textref = $outputlangs->transnoentities("Ref")." : ".$outputlangs->convToOutputCharset($object->ref); - if ($object->statut == $object::STATUS_DRAFT) { - $pdf->SetTextColor(128, 0, 0); - $textref .= ' - '.$outputlangs->transnoentities("NotValidated"); - } - $pdf->MultiCell($w, 4, $textref, '', 'R'); - - $posy += 1; - $pdf->SetFont('', '', $default_font_size - 2); - - if ($object->ref_client) { - $posy += 4; - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell($w, 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)) { - $outputlangs->load("projects"); - $posy += 3; - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell($w, 3, $outputlangs->transnoentities("RefProject")." : ".(empty($object->project->ref) ? '' : $object->project->ref), '', 'R'); - } - } - - $posy += 4; - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - - $title = $outputlangs->transnoentities("Date"); - if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) { - $title .= ' - '.$outputlangsbis->transnoentities("Date"); - } - $pdf->MultiCell($w, 3, $title." : ".dol_print_date($object->date, "day", false, $outputlangs), '', 'R'); - - if ($object->thirdparty->code_client) { - $posy += 3; - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell($w, 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($w, 3, $langs->transnoentities("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); - } - } - - $posy += 1; - - $top_shift = 0; - // Show list of linked objects - $current_y = $pdf->getY(); - $posy = pdf_writeLinkedObjects($pdf, $object, $outputlangs, $posx, $posy, $w, 3, 'R', $default_font_size); - if ($current_y < $pdf->getY()) { - $top_shift = $pdf->getY() - $current_y; - } - - if ($showaddress) { - // Sender properties - $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; - $posy += $top_shift; - $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("BillFrom").":", 0, 'L'); - $pdf->SetXY($posx, $posy); - $pdf->SetFillColor(230, 230, 230); - $pdf->MultiCell($widthrecbox, $hautcadre, "", 0, 'R', 1); - $pdf->SetTextColor(0, 0, 60); - - // Show sender name - $pdf->SetXY($posx + 2, $posy + 3); - $pdf->SetFont('', 'B', $default_font_size); - $pdf->MultiCell($widthrecbox - 2, 4, $outputlangs->convToOutputCharset($this->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 BILLING contact defined on invoice, we use it - $usecontact = false; - $arrayidcontact = $object->getIdContact('external', 'BILLING'); - if (count($arrayidcontact) > 0) { - $usecontact = true; - $result = $object->fetch_contact($arrayidcontact[0]); - } - - // Recipient name - if ($object->contact->socid != $object->thirdparty->id && (!isset($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT) || !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT))) { - $thirdparty = $object->contact; - } else { - $thirdparty = $object->thirdparty; - } - - if (is_object($thirdparty)) { - $carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs); - } - - $carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, ($usecontact ? $object->contact : ''), $usecontact, 'target', $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; - $posy += $top_shift; - $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("BillTo").":", 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.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) - { - global $conf; - $showdetails = empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 0 : $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS; - return pdf_pagefoot($pdf, $outputlangs, 'INVOICE_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, 0.5, 0.5, 0.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 - ), - ); - - // PHOTO - $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_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) { - $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' => 'PriceUHT' - ), - 'border-left' => true, // add left line separator - ); - - $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['progress'] = array( - 'rank' => $rank, - 'width' => 19, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Progress' - ), - 'border-left' => true, // add left line separator - ); - - if ($this->situationinvoice) { - $this->cols['progress']['status'] = true; - } - - $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 (!empty($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' => 'TotalHT' - ), - '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/core/modules/dolicar/mod_registrationcertificatefr_advanced.php b/core/modules/dolicar/mod_registrationcertificatefr_advanced.php deleted file mode 100644 index 6fabcc5..0000000 --- a/core/modules/dolicar/mod_registrationcertificatefr_advanced.php +++ /dev/null @@ -1,145 +0,0 @@ - - * 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 - * - * 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/dolicar/mod_registrationcertificatefr_advanced.php - * \ingroup dolicar - * \brief File containing class for advanced numbering model of RegistrationCertificateFr - */ - -require_once __DIR__ . '/../../../core/modules/dolicar/modules_registrationcertificatefr.php'); - -/** - * Class to manage customer Bom numbering rules advanced - */ -class mod_registrationcertificatefr_advanced extends ModeleNumRefRegistrationCertificateFr -{ - /** - * 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 = 'advanced'; - - - /** - * 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("RegistrationCertificateFr"), $langs->transnoentities("RegistrationCertificateFr")); - $tooltip .= $langs->trans("GenericMaskCodes2"); - $tooltip .= $langs->trans("GenericMaskCodes3"); - $tooltip .= $langs->trans("GenericMaskCodes4a", $langs->transnoentities("RegistrationCertificateFr"), $langs->transnoentities("RegistrationCertificateFr")); - $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 RegistrationCertificateFr($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->DOLICAR_REGISTRATIONCERTIFICATEFR_ADVANCED_MASK; - - if (!$mask) { - $this->error = 'NotConfigured'; - return 0; - } - - $date = $object->date; - - $numFinal = get_next_value($db, $mask, 'dolicar_registrationcertificatefr', 'ref', '', null, $date); - - return $numFinal; - } -} diff --git a/core/modules/dolicar/mod_registrationcertificatefr_standard.php b/core/modules/dolicar/mod_registrationcertificatefr_standard.php index fcc1ff4..14a4b7a 100644 --- a/core/modules/dolicar/mod_registrationcertificatefr_standard.php +++ b/core/modules/dolicar/mod_registrationcertificatefr_standard.php @@ -1,6 +1,5 @@ - * Copyright (C) 2005-2009 Regis Houssin +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ -14,148 +13,29 @@ * * 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/dolicar/mod_registrationcertificatefr_standard.php - * \ingroup dolicar - * \brief File of class to manage RegistrationCertificateFr numbering rules standard + * \file core/modules/dolicar/mod_registrationcertificatefr_standard.php + * \ingroup dolicar + * \brief File of class to manage mod_registrationcertificatefr_standard numbering rules standard */ -require_once __DIR__ . '/../../../core/modules/dolicar/modules_registrationcertificatefr.php'); +// Load Saturne libraries +require_once __DIR__ . '/../../../../saturne/core/modules/saturne/modules_saturne.php'; /** - * Class to manage customer order numbering rules standard + * Class to manage customer order numbering rules standard */ -class mod_registrationcertificatefr_standard extends ModeleNumRefRegistrationCertificateFr +class mod_registrationcertificatefr_standard extends ModeleNumRefSaturne { - /** - * Dolibarr version of the loaded document - * @var string - */ - public $version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' - - public $prefix = 'RCF'; - - /** - * @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."dolicar_registrationcertificatefr"; - $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."dolicar_registrationcertificatefr"; - $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_registrationcertificatefr_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_registrationcertificatefr_standard::getNextValue return ".$this->prefix.$yymm."-".$num); - return $this->prefix.$yymm."-".$num; - } + /** + * @var string Numbering module ref prefix + */ + public string $prefix = 'RCF'; + + /** + * @var string Name + */ + public string $name = 'Albiorix'; } diff --git a/core/modules/dolicar/modules_registrationcertificatefr.php b/core/modules/dolicar/modules_registrationcertificatefr.php deleted file mode 100644 index dc07f7c..0000000 --- a/core/modules/dolicar/modules_registrationcertificatefr.php +++ /dev/null @@ -1,158 +0,0 @@ - - * 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 - * - * 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/dolicar/modules_registrationcertificatefr.php - * \ingroup dolicar - * \brief File that contains parent class for registrationcertificatefrs document models and parent class for registrationcertificatefrs 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 ModelePDFRegistrationCertificateFr 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 = 'registrationcertificatefr'; - $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 RegistrationCertificateFr - */ -abstract class ModeleNumRefRegistrationCertificateFr -{ - /** - * @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("dolicar@dolicar"); - return $langs->trans("NoDescription"); - } - - /** - * Returns an example of numbering - * - * @return string Example - */ - public function getExample() - { - global $langs; - $langs->load("dolicar@dolicar"); - 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/core/modules/modDoliCar.class.php b/core/modules/modDoliCar.class.php index ea02fc7..54443e3 100644 --- a/core/modules/modDoliCar.class.php +++ b/core/modules/modDoliCar.class.php @@ -1,8 +1,5 @@ - * Copyright (C) 2018-2019 Nicolas ZABOURI - * Copyright (C) 2019-2020 Frédéric France - * Copyright (C) 2022 Eoxia +/* Copyright (C) 2021-2024 EVARISK * * 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 @@ -19,686 +16,644 @@ */ /** - * \defgroup dolicar Module DoliCar - * \brief DoliCar module descriptor. + * \defgroup dolicar Module DoliCar + * \brief DoliCar module descriptor * - * \file htdocs/custom/dolicar/core/modules/modDoliCar.class.php - * \ingroup dolicar - * \brief Description and activation file for module DoliCar + * \file core/modules/modDoliCar.class.php + * \ingroup dolicar + * \brief Description and activation file for module DoliCar */ -include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; + +// Load Dolibarr libraries +require_once DOL_DOCUMENT_ROOT . '/core/modules/DolibarrModules.class.php'; /** - * Description and activation class for module DoliCar + * Description and activation class for module DoliCar */ class modDoliCar extends DolibarrModules { - /** - * Constructor. Define names, constants, directories, boxes, permissions - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $langs, $conf; - - if (file_exists(__DIR__ . '/../../../saturne/lib/saturne_functions.lib.php')) { - require_once __DIR__ . '/../../../saturne/lib/saturne_functions.lib.php'; - saturne_load_langs(['dolicar@dolicar']); - } else { - $this->error++; - $this->errors[] = $langs->trans('activateModuleDependNotSatisfied', 'DoliCar', 'Saturne'); - } - - $this->db = $db; - $this->numero = 436380; // TODO Go on page https://wiki.dolibarr.org/index.php/List_of_modules_id to reserve an id number for your module - $this->rights_class = 'dolicar'; - $this->family = ""; - $this->module_position = ''; - $this->familyinfo = array('Evarisk' => array('position' => '01', 'label' => $langs->trans("Evarisk"))); - $this->name = preg_replace('/^mod/i', '', get_class($this)); - $this->description = $langs->trans("DoliCarDescription"); - $this->descriptionlong = $langs->trans("DoliCarDescription"); - $this->editor_name = 'Evarisk'; - $this->editor_url = 'https://www.evarisk.com'; - $this->version = '1.1.1'; - $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); - $this->picto = 'dolicar_color@dolicar'; - - $this->module_parts = array( - 'triggers' => 1, - 'login' => 0, - 'substitutions' => 0, - 'menus' => 0, - 'tpl' => 0, - 'barcode' => 0, - 'models' => 1, - 'printing' => 0, - 'theme' => 0, - 'css' => array( - ), - 'js' => array( - ), - 'hooks' => array( - 'productlotcard', - 'invoicecard', - 'propalcard', - 'ordercard', - 'paiementcard', - 'productlotcard', - 'registrationcertificatefrcard', - 'dolicar_quickcreation', - 'get_sheet_linkable_objects', - 'main' - ), - 'moduleforexternal' => 0, - ); - - // Data directories to create when module is enabled. - $this->dirs = array("/dolicar/temp"); - - // Config pages. Put here list of php page, stored into dolicar/admin directory, to use to setup module. - $this->config_page_url = array("setup.php@dolicar"); - - // 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('modProduct', 'modProductBatch', 'modFacture', 'modPropale', 'modCommande', 'modCategorie', 'modSaturne', 'modProjet'); - $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', ...) - - // The language file dedicated to your module - $this->langfiles = array("dolicar@dolicar"); - - // Prerequisites - $this->phpmin = array(5, 6); // Minimum version of PHP required by module - $this->need_dolibarr_version = array(11, -3); // Minimum version of Dolibarr required by module - - // Messages at activation - $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','MX'='textmx'...) - $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','MX'='textmx'...) - - $i = 0; - $this->const = array( - // CONST REGISTRATION CERTIFICATE - $i++ => array('DOLICAR_DEFAULT_PROJECT', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_DEFAULT_WAREHOUSE_ID', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_TAGS_SET', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_DEFAULT_VEHICLE_SET', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_DEFAULT_VEHICLE', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_VEHICLE_TAG', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_MENU_DEFAULT_VEHICLE_UPDATED', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_HIDE_REGISTRATIONCERTIFICATE_FIELDS', 'integer', 1, '', 0, 'current'), - $i++ => array('DOLICAR_HIDE_OBJECT_DET_DOLICAR_DETAILS', 'integer', 1, '', 0, 'current'), - $i++ => array('DOLICAR_A_REGISTRATION_NUMBER_VISIBLE', 'integer', 1, '', 0, 'current'), - $i++ => array('DOLICAR_API_REMAINING_REQUESTS_COUNTER', 'integer', 0, '', 0, 'current'), - $i++ => array('DOLICAR_API_REQUESTS_COUNTER', 'integer', 0, '', 0, 'current'), + /** + * Constructor. Define names, constants, directories, boxes, permissions + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $conf, $langs; + $this->db = $db; + + if (file_exists(__DIR__ . '/../../../saturne/lib/saturne_functions.lib.php')) { + require_once __DIR__ . '/../../../saturne/lib/saturne_functions.lib.php'; + saturne_load_langs(['dolicar@dolicar']); + } else { + $this->error++; + $this->errors[] = $langs->trans('activateModuleDependNotSatisfied', 'DoliCar', 'Saturne'); + } + + // Id for module (must be unique) + $this->numero = 436380; + + // Key text used to identify module (for permissions, menus, etc...) + $this->rights_class = 'dolicar'; + + // 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 = ''; + + // Module position in the family on 2 digits ('01', '10', '20', ...) + $this->module_position = ''; + + // 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 = ['Evarisk' => ['position' => '01', 'label' => $langs->trans('Evarisk')]]; + // Module label (no space allowed), used if translation string 'ModuleDoliCarName' not found (DoliCar is name of module) + $this->name = preg_replace('/^mod/i', '', get_class($this)); + + // Module description, used if translation string 'ModuleDoliCarDesc' not found (DoliCar is name of module) + $this->description = $langs->trans('DoliCarDescription'); + // Used only if file README.md and README-LL.md not found + $this->descriptionlong = $langs->trans('DoliCarDescription'); + + // Author + $this->editor_name = 'Evarisk'; + $this->editor_url = 'https://www.evarisk.com'; + + // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z' + $this->version = '1.1.1'; + + // 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 DoliCar 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' + // To use a supported fa-xxx css style of font awesome, use this->picto='xxx' + $this->picto = 'dolicar_color@dolicar'; + + $this->module_parts = [ + // Set this to 1 if module has its own trigger directory (core/triggers) + 'triggers' => 1, + // 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 printing directory (core/modules/printing) + 'printing' => 0, + // 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' => [], + // Set this to relative path of js file if module must load a js on all pages + 'js' => [], + // 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' => [ + 'data' => [ + 'productlotcard', + 'invoicecard', + 'propalcard', + 'ordercard', + 'paiementcard', + 'productlotcard', + 'registrationcertificatefrcard', + 'dolicar_quickcreation', + 'get_sheet_linkable_objects', + ] + ], + // Set this to 1 if features of module are opened to external users + 'moduleforexternal' => 0, + ]; + + // Data directories to create when module is enabled + // Example: this->dirs = array("/dolicar/temp","/dolicar/subdir"); + $this->dirs = ['/dolicar/temp']; + + // Config pages. Put here list of php page, stored into dolicar/admin directory, to use to set up module + $this->config_page_url = ['setup.php@dolicar']; + + // 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 = ['modProduct', 'modProductBatch', 'modFacture', 'modPropale', 'modCommande', 'modCategorie', 'modSaturne', 'modProjet']; + $this->requiredby = []; // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) + $this->conflictwith = []; // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) + + // The language file dedicated to your module + $this->langfiles = ['dolicar@dolicar']; + + // Prerequisites + $this->phpmin = [7, 4]; // Minimum version of PHP required by module + $this->need_dolibarr_version = [16, 0]; // Minimum version of Dolibarr required by module + + // Messages at activation + $this->warnings_activation = []; // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','MX'='textmx'...) + $this->warnings_activation_ext = []; // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','MX'='textmx'...) + + // 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('DoliSIRH_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1), + // 2 => array('DoliSIRH_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1) + // ); + $i = 0; + $this->const = [ + // CONST REGISTRATION CERTIFICATE + $i++ => ['DOLICAR_DEFAULT_WAREHOUSE_ID', 'integer', 0, '', 0, 'current'], + $i++ => ['DOLICAR_TAGS_SET', 'integer', 0, '', 0, 'current'], + $i++ => ['DOLICAR_DEFAULT_VEHICLE_SET', 'integer', 0, '', 0, 'current'], + $i++ => ['DOLICAR_DEFAULT_VEHICLE', 'integer', 0, '', 0, 'current'], + $i++ => ['DOLICAR_VEHICLE_TAG', 'integer', 0, '', 0, 'current'], + $i++ => ['DOLICAR_HIDE_REGISTRATIONCERTIFICATE_FIELDS', 'integer', 1, '', 0, 'current'], + $i++ => ['DOLICAR_HIDE_OBJECT_DET_DOLICAR_DETAILS', 'integer', 1, '', 0, 'current'], + $i++ => ['DOLICAR_API_REMAINING_REQUESTS_COUNTER', 'integer', 0, '', 0, 'current'], + $i++ => ['DOLICAR_API_REQUESTS_COUNTER', 'integer', 0, '', 0, 'current'], // CONST PUBLIC INTERFACE $i++ => array('DOLICAR_PUBLIC_MAX_ARRIVAL_MILEAGE', 'integer', 1000, '', 0, 'current'), - // CONST MODULE - $i++ => ['DOLICAR_VERSION','chaine', $this->version, '', 0, 'current'], - $i++ => ['DOLICAR_DB_VERSION', 'chaine', $this->version, '', 0, 'current'], - $i++ => ['DOLICAR_SHOW_PATCH_NOTE', 'integer', 1, '', 0, 'current'], - - ); - - if (!isset($conf->dolicar) || !isset($conf->dolicar->enabled)) { - $conf->dolicar = new stdClass(); - $conf->dolicar->enabled = 0; - } - - // Array to add new pages in new tabs - $this->tabs = array(); - $pictopath = dol_buildpath('/custom/dolicar/img/dolicar_color.png', 1); - $picto = img_picto('', $pictopath, '', 1, 0, 0, '', 'pictoModule'); - $this->tabs[] = array('data' => 'productlot:+registrationcertificatefr:' . $picto . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=productlot'); - $this->tabs[] = array('data' => 'thirdparty:+registrationcertificatefr:' . $picto . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=thirdparty'); - $this->tabs[] = array('data' => 'product:+registrationcertificatefr:' . $picto . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=product'); - $this->tabs[] = array('data' => 'project:+registrationcertificatefr:' . $picto . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=project'); - - // Dictionaries - $this->dictionaries = array( - 'langs' => 'dolicar@dolicar', - // List of tables we want to see into dictonnary editor - 'tabname' => array( - MAIN_DB_PREFIX . "c_car_brands", - ), - // Label of tables - 'tablib' => array( - "CarBrands" - ), - // Request to select fields - 'tabsql' => array( - 'SELECT f.rowid as rowid, f.ref, f.label, f.description, f.active FROM ' . MAIN_DB_PREFIX . 'c_car_brands as f', - ), - // Sort order - 'tabsqlsort' => array( - "label ASC" - ), - // List of fields (result of select to show dictionary) - 'tabfield' => array( - "ref,label,description" - ), - // List of fields (list of fields to edit a record) - 'tabfieldvalue' => array( - "ref,label,description" - ), - // List of fields (list of fields for insert) - 'tabfieldinsert' => array( - "ref,label,description" - ), - // Name of columns with primary key (try to always name it 'rowid') - 'tabrowid' => array( - "rowid" - ), - // Condition to show each dictionary - 'tabcond' => array( - $conf->dolicar->enabled - ) - ); - - // Boxes/Widgets - // Add here list of php file(s) stored in dolicar/core/boxes that contains a class to show a widget. - $this->boxes = array( - ); - - // 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( - ); - - // Permissions provided by this module - $this->rights = array(); - $r = 0; - // Add here entries to declare new permissions - /* BEGIN MODULEBUILDER PERMISSIONS */ - $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); - $this->rights[$r][1] = $langs->trans('LireModule', 'DoliCar'); - $this->rights[$r][4] = 'lire'; - $this->rights[$r][5] = 1; - $r++; - $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); - $this->rights[$r][1] = $langs->trans('ReadModule', 'DoliCar'); - $this->rights[$r][4] = 'read'; - $this->rights[$r][5] = 1; - $r++; - - $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used) - $this->rights[$r][1] = $langs->transnoentities('ReadObject', $langs->trans('RegistrationCertificatesFrMin')); // Permission label - $this->rights[$r][4] = 'registrationcertificatefr'; - $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->dolicar->registrationcertificatefr->write) - $r++; - $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used) - $this->rights[$r][1] = $langs->transnoentities('CreateObject', $langs->trans('RegistrationCertificatesFrMin')); // Permission label - $this->rights[$r][4] = 'registrationcertificatefr'; - $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->dolicar->registrationcertificatefr->write) - $r++; - $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used) - $this->rights[$r][1] = $langs->transnoentities('DeleteObject', $langs->trans('RegistrationCertificatesFrMin')); // Permission label - $this->rights[$r][4] = 'registrationcertificatefr'; - $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->dolicar->registrationcertificatefr->delete) - $r++; - - $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used) - $this->rights[$r][1] = $langs->transnoentities('ReadAdminPage', 'DoliCar'); - $this->rights[$r][4] = 'adminpage'; - $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->dolicar->registrationcertificatefr->delete) - $r++; - - $langs->load("dolicar@dolicar"); - - // Main menu entries to add - $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'=>'DoliCar', - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'', - 'url'=>'/dolicar/dolicarindex.php', - 'langs'=>'dolicar@dolicar', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'position'=>1000 + $r, - 'enabled'=>'$conf->dolicar->enabled', // Define condition to show or hide menu entry. Use '$conf->dolicar->enabled' if entry must be visible if module is enabled. - 'perms' => '$user->rights->dolicar->lire', - 'target'=>'', - 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both - ); - $this->menu[$r++] = array( - 'fk_menu'=>'fk_mainmenu=dolicar', // '' 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'=> $langs->trans('Dashboard'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'', - 'url'=>'/dolicar/dolicarindex.php', - 'langs'=>'dolicar@dolicar', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'position'=>1000 + $r, - 'enabled'=>'$conf->dolicar->enabled', // Define condition to show or hide menu entry. Use '$conf->dolicar->enabled' if entry must be visible if module is enabled. - 'perms' => '$user->rights->dolicar->lire', - '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=dolicar', - // This is a Left menu entry - 'type'=>'left', - 'titre' => $langs->trans('ListRegistrationCertificateFr'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'dolicar_registrationcertificatefr', - 'url'=>'/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php', - // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'langs'=>'dolicar@dolicar', - 'position'=>1000+$r, - // Define condition to show or hide menu entry. Use '$conf->dolicar->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. - 'enabled'=>'$conf->dolicar->enabled', - // Use 'perms'=>'$user->rights->dolicar->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++] = [ - 'fk_menu' => 'fk_mainmenu=dolicar', // '' 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' => $langs->transnoentities('QuickCreation'), - 'prefix' => '', - 'mainmenu' => 'dolicar', - 'leftmenu' => 'quickcreation', - 'url' => '/dolicar/view/registrationcertificatefr/quickcreation.php', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'langs' => 'dolicar@dolicar', - 'position' => 1000 + $r, - 'enabled' => '$conf->easycrm->enabled', // Define condition to show or hide menu entry. Use '$conf->easycrm->enabled' if entry must be visible if module is enabled. - 'perms' => '$user->rights->dolicar->read', // Use 'perms'=>'$user->rights->easycrm->myobject->read' if you want your menu with a permission rules - 'target' => '', - 'user' => 0, // 0=Menu for internal users, 1=external users, 2=both - ]; - $this->menu[$r++]=array( - 'fk_menu' => 'fk_mainmenu=dolicar', - 'type' => 'left', - 'titre' => $langs->trans('ThirdParty'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'dolicar_companies', - 'url'=>'/societe/index.php?mainmenu=companies', - 'langs'=>'dolicar@dolicar', - 'position'=>1050+$r, - 'enabled'=>'$conf->dolicar->enabled', - 'perms'=>'1', - 'target'=>'', - 'user'=>2 - ); - $this->menu[$r++]=array( - 'fk_menu' => 'fk_mainmenu=dolicar', - 'type' => 'left', - 'titre' => $langs->trans('Propale'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'dolicar_propales', - 'url'=>'/comm/propal/index.php?mainmenu=commercial&leftmenu=propals', - 'langs'=>'dolicar@dolicar', - 'position'=>1050+$r, - 'enabled'=>'$conf->dolicar->enabled', - 'perms'=>'1', - 'target'=>'', - 'user'=>2 - ); - $this->menu[$r++]=array( - 'fk_menu' => 'fk_mainmenu=dolicar', - 'type' => 'left', - 'titre' => $langs->trans('Invoice'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'dolicar_invoices', - 'url'=>'/compta/facture/index.php?mainmenu=billing&leftmenu=customers_bills', - 'langs'=>'dolicar@dolicar', - 'position'=>1050+$r, - 'enabled'=>'$conf->dolicar->enabled', - 'perms'=>'1', - 'target'=>'', - 'user'=>2 - ); - $this->menu[$r++]=array( - 'fk_menu' => 'fk_mainmenu=dolicar', - 'type' => 'left', - 'titre' => $langs->trans('Order'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'dolicar_orders', - 'url'=>'/commande/index.php?mainmenu=commercial&leftmenu=orders', - 'langs'=>'dolicar@dolicar', - 'position'=>1050+$r, - 'enabled'=>'$conf->dolicar->enabled', - 'perms'=>'1', - 'target'=>'', - 'user'=>2 - ); - $this->menu[$r++]=array( - 'fk_menu' => 'fk_mainmenu=dolicar', - 'type' => 'left', - 'titre' => $langs->trans('Product'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'dolicar_products', - 'url'=>'/product/index.php?mainmenu=products', - 'langs'=>'dolicar@dolicar', - 'position'=>1050+$r, - 'enabled'=>'$conf->dolicar->enabled', - 'perms'=>'1', - 'target'=>'', - 'user'=>2 - ); - $this->menu[$r++]=array( - 'fk_menu' => 'fk_mainmenu=dolicar', - 'type' => 'left', - 'titre' => $langs->trans('Lot'), - 'prefix' => '', - 'mainmenu'=>'dolicar', - 'leftmenu'=>'dolicar_lot', - 'url'=>'/product/index.php?mainmenu=products', - 'langs'=>'dolicar@dolicar', - 'position'=>1050+$r, - 'enabled'=>'$conf->dolicar->enabled', - 'perms'=>'1', - 'target'=>'', - 'user'=>2 - ); - /* END MODULEBUILDER LEFTMENU REGISTRATIONCERTIFICATEFR */ - } - - /** - * 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, $user; - - $langs->load('dolicar@dolicar'); - - if ($this->error > 0) { - setEventMessages('', $this->errors, 'errors'); - 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') - } - - dolibarr_set_const($this->db, 'DOLICAR_VERSION', $this->version, 'chaine', 0, '', $conf->entity); - dolibarr_set_const($this->db, 'DOLICAR_DB_VERSION', $this->version, 'chaine', 0, '', $conf->entity); - - //$result = $this->_load_tables('/install/mysql/tables/', 'dolicar'); - $result = $this->_load_tables('/dolicar/sql/'); - 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); - $extrafields->addExtraField('registrationcertificate_metada', $langs->transnoentities("RegistrationCertificateMetadata"), 'text', 1080, '', 'product_lot', 0, 0, '', '', 1, '', 1); - - // // Facture extrafields - // Update - $extrafields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'facture', 0, 0, 1040, '', 1,'', 1); - $extrafields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'facture', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); - - // Add - $extrafields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'facture', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extrafields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'facture', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'facture', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'facture', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'facture', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'facture', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'facture', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'facture', 0, 0, '', '', 1, '', 1); - - // Facturedet extrafields - // Update - $extrafields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'facturedet', 0, 0, 1040, '', 1,'', 1); - $extrafields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'facturedet', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); - - // Add - $extrafields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'facturedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extrafields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'facturedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'facturedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'facturedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'facturedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'facturedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'facturedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'facturedet', 0, 0, '', '', 1, '', 1); - - // Propal extrafields - // Update - $extrafields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'propal', 0, 0, 1040, '', 1,'', 1); - $extrafields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'propal', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); - - // Add - $extrafields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'propal', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extrafields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'propal', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'propal', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'propal', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'propal', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'propal', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'propal', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'propal', 0, 0, '', '', 1, '', 1); - - // Propaldet extrafields - // Update - $extrafields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'propaldet', 0, 0, 1040, '', 1,'', 1); - $extrafields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'propaldet', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); - - // Add - $extrafields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'propaldet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extrafields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'propaldet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'propaldet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'propaldet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'propaldet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'propaldet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'propaldet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'propaldet', 0, 0, '', '', 1, '', 1); - - // Commande extrafields - // Update - $extrafields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'commande', 0, 0, 1040, '', 1,'', 1); - $extrafields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'commande', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); - - // Add - $extrafields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'commande', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extrafields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'commande', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'commande', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'commande', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'commande', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'commande', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'commande', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'commande', 0, 0, '', '', 1, '', 1); - - // Commandedet extrafields - // Update - $extrafields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'commandedet', 0, 0, 1040, '', 1,'', 1); - $extrafields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'commandedet', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); - - // Add - $extrafields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'commandedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extrafields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'commandedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'commandedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'commandedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'commandedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'commandedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); - $extrafields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'commandedet', 0, 0, '', '', 1, '', 1); - $extrafields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'commandedet', 0, 0, '', '', 1, '', 1); - - $extrafields->addExtraField('starting_mileage', 'StartingMileage', 'int', 1000, '', 'actioncomm', 0, 0, '', '', 1, '', 1, '', '', 0, 'dolicar@dolicar', '$conf->dolicar->enabled'); + // CONST MODULE + $i++ => ['DOLICAR_VERSION','chaine', $this->version, '', 0, 'current'], + $i++ => ['DOLICAR_DB_VERSION', 'chaine', $this->version, '', 0, 'current'], + $i => ['DOLICAR_SHOW_PATCH_NOTE', 'integer', 1, '', 0, 'current'], + ]; + + if (!isset($conf->dolicar) || !isset($conf->dolicar->enabled)) { + $conf->dolicar = new stdClass(); + $conf->dolicar->enabled = 0; + } + + // Array to add new pages in new tabs + // Example: + // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@dolicar:$user->rights->othermodule->read:/dolicar/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'); + $this->tabs = []; + $pictoPath = dol_buildpath('custom/dolicar/img/dolicar_color.png', 1); + $pictoModule = img_picto('', $pictoPath, '', 1, 0, 0, '', 'pictoModule'); + $this->tabs[] = ['data' => 'productlot:+registrationcertificatefr:' . $pictoModule . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=productlot']; + $this->tabs[] = ['data' => 'thirdparty:+registrationcertificatefr:' . $pictoModule . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=thirdparty']; + $this->tabs[] = ['data' => 'product:+registrationcertificatefr:' . $pictoModule . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=product']; + $this->tabs[] = ['data' => 'project:+registrationcertificatefr:' . $pictoModule . ucfirst($langs->trans('RegistrationCertificateFr')) . ':dolicar@dolicar:$user->rights->dolicar->registrationcertificatefr->read:/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php?fromid=__ID__&fromtype=project']; + + // Dictionaries + $this->dictionaries = []; + + // Boxes/Widgets + // Add here list of php file(s) stored in dolicar/core/boxes that contains a class to show a widget + $this->boxes = []; + + // 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 = []; + + // Permissions provided by this module + $this->rights = []; + $r = 0; + + /* DOLICAR PERMISSIONS */ + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); // Permission id (must not be already used) + $this->rights[$r][1] = $langs->trans('LireModule', 'DoliCar'); // Permission label + $this->rights[$r][4] = 'lire'; // In php code, permission will be checked by test if ($user->rights->dolicar->level1->level2) + $r++; + + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); + $this->rights[$r][1] = $langs->trans('ReadModule', 'DoliCar'); + $this->rights[$r][4] = 'read'; + $r++; + + /* REGISTRATIONCERTIFICATEFR PERMISSIONS */ + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); + $this->rights[$r][1] = $langs->transnoentities('ReadObjects', $langs->trans('RegistrationCertificatesFrMin')); + $this->rights[$r][4] = 'registrationcertificatefr'; + $this->rights[$r][5] = 'read'; + $r++; + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); + $this->rights[$r][1] = $langs->transnoentities('CreateObjects', $langs->trans('RegistrationCertificatesFrMin')); + $this->rights[$r][4] = 'registrationcertificatefr'; + $this->rights[$r][5] = 'write'; + $r++; + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); + $this->rights[$r][1] = $langs->transnoentities('DeleteObjects', $langs->trans('RegistrationCertificatesFrMin')); + $this->rights[$r][4] = 'registrationcertificatefr'; + $this->rights[$r][5] = 'delete'; + $r++; + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); + $this->rights[$r][1] = $langs->transnoentities('ReadAdminPage', 'DoliCar'); + $this->rights[$r][4] = 'adminpage'; + $this->rights[$r][5] = 'read'; + + // Main menu entries to add + $this->menu = []; + $r = 0; + + // Add here entries to declare new menus + // DOLICAR MENU + $this->menu[$r++] = [ + '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' => 'DoliCar', + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => '', + 'url' => '/dolicar/dolicarindex.php', + 'langs' => 'dolicar@dolicar', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', // Define condition to show or hide menu entry. Use '$conf->dolicar->enabled' if entry must be visible if module is enabled. + 'perms' => '$user->rights->dolicar->lire', + 'target' => '', + 'user' => 0 // 0=Menu for internal users, 1=external users, 2=both + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('Dashboard'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => '', + 'url' => '/dolicar/dolicarindex.php', + 'langs' => 'dolicar@dolicar', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->dolicar->lire', + 'target' => '', + 'user' => 0 + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('ListRegistrationcertificatefr'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'registrationcertificatefr', + 'url' => '/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php', + 'langs' => 'dolicar@dolicar', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->dolicar->registrationcertificatefr->read', + 'target' => '', + 'user' => 0, + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('QuickCreation'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'quickcreation', + 'url' => '/dolicar/view/registrationcertificatefr/quickcreation.php', + 'langs' => 'dolicar@dolicar', + 'position' => 1000 + $r, + 'enabled' => '$conf->easycrm->enabled', + 'perms' => '$user->rights->dolicar->read', + 'target' => '', + 'user' => 0 + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('ThirdParty'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'thirdparty', + 'url' => '/societe/index.php?mainmenu=companies&leftmenu=thirdparties', + 'langs' => 'companies', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->societe->lire', + 'target' => '', + 'user' => 0 + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('Proposal'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'propal', + 'url' => '/comm/propal/index.php?mainmenu=commercial&leftmenu=propals', + 'langs' => 'propal', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->propale->lire', + 'target' => '', + 'user' => 0 + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('Invoice'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'invoice', + 'url' => '/compta/facture/index.php?mainmenu=billing&leftmenu=customers_bills', + 'langs' => 'bills', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->propale->lire', + 'target' => '', + 'user' => 2 + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('Order'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'order', + 'url' => '/commande/index.php?mainmenu=commercial&leftmenu=orders', + 'langs' => 'orders', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->commande->lire', + 'target' => '', + 'user' => 0 + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('Product'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'product', + 'url' => '/product/index.php?mainmenu=products&leftmenu=product&type=0', + 'langs' => 'products', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->produit->lire', + 'target' => '', + 'user' => 0 + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=dolicar', + 'type' => 'left', + 'titre' => $langs->transnoentities('Batch'), + 'prefix' => '', + 'mainmenu' => 'dolicar', + 'leftmenu' => 'produtlot', + 'url' => '/product/stock/productlot_list.php?mainmenu=products', + 'langs' => 'productbatch', + 'position' => 1000 + $r, + 'enabled' => '$conf->dolicar->enabled', + 'perms' => '$user->rights->produit->lire && $user->rights->stock->lire', + 'target' => '', + 'user' => 0 + ]; + } + + /** + * 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 + * @throws Exception + */ + public function init($options = ''): int + { + global $conf, $langs, $user; + + // Permissions + $this->remove($options); + + $sql = []; + + $result = $this->_load_tables('/dolicar/sql/'); + 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') + } + + dolibarr_set_const($this->db, 'DOLICAR_VERSION', $this->version, 'chaine', 0, '', $conf->entity); + dolibarr_set_const($this->db, 'DOLICAR_DB_VERSION', $this->version, 'chaine', 0, '', $conf->entity); + + // Create extrafields during init + require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; + $extraFields = new ExtraFields($this->db); + + $extraFields->addExtraField('registrationcertificate_metada', $langs->transnoentities("RegistrationCertificateMetadata"), 'text', 1080, '', 'product_lot', 0, 0, '', '', 1, '', 1); + + // // Facture extrafields + // Update + $extraFields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'facture', 0, 0, 1040, '', 1,'', 1); + $extraFields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'facture', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); + + // Add + $extraFields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'facture', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); + $extraFields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'facture', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'facture', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'facture', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'facture', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'facture', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'facture', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'facture', 0, 0, '', '', 1, '', 1); + + // Facturedet extrafields + // Update + $extraFields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'facturedet', 0, 0, 1040, '', 1,'', 1); + $extraFields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'facturedet', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); + + // Add + $extraFields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'facturedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); + $extraFields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'facturedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'facturedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'facturedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'facturedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'facturedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'facturedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'facturedet', 0, 0, '', '', 1, '', 1); + + // Propal extrafields + // Update + $extraFields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'propal', 0, 0, 1040, '', 1,'', 1); + $extraFields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'propal', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); + + // Add + $extraFields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'propal', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); + $extraFields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'propal', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'propal', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'propal', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'propal', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'propal', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'propal', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'propal', 0, 0, '', '', 1, '', 1); + + $extrafields->addExtraField('starting_mileage', 'StartingMileage', 'int', 1000, '', 'actioncomm', 0, 0, '', '', 1, '', 1, '', '', 0, 'dolicar@dolicar', '$conf->dolicar->enabled'); $extrafields->addExtraField('arrival_mileage', 'ArrivalMileage', 'int', 1010, '', 'actioncomm', 0, 0, '', '', 1, '', 1, '', '', 0, 'dolicar@dolicar', '$conf->dolicar->enabled'); $extrafields->addExtraField('json', 'JSON', 'text', 1020, '', 'actioncomm', 0, 0, '', '', 1, '', 0, '', '', 0, 'dolicar@dolicar', '$conf->dolicar->enabled'); - // Permissions - $this->remove($options); - - $sql = array(); - - require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php'; - $warehouse = new Entrepot($this->db); - - //Warehouse - if ($conf->global->DOLICAR_DEFAULT_WAREHOUSE_ID <= 0) { - $warehouse->ref = $langs->trans('DolicarWarehouse'); - $warehouse->label = $langs->trans('DolicarWarehouse'); - $warehouse_id = $warehouse->create($user); - dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_WAREHOUSE_ID', $warehouse_id, 'integer', 0, '', $conf->entity); - } - - if ($conf->global->DOLICAR_DEFAULT_WAREHOUSE_STATUS_UPDATED == 0) { - $warehouse->fetch($conf->global->DOLICAR_DEFAULT_WAREHOUSE_ID); - $warehouse->statut = 1; - $warehouseUpdated = $warehouse->update($warehouse->id, $user); - if ($warehouseUpdated > 0) { - dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_WAREHOUSE_STATUS_UPDATED', 1, 'integer', 0, '', $conf->entity); - } - } - - //Categorie - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $tag = new Categorie($this->db); - - if ($conf->global->DOLICAR_TAGS_SET == 0) { - - $tag->label = $langs->transnoentities('Vehicle'); - $tag->type = 'product'; - $vehicleTag = $tag->create($user); - - if ($vehicleTag > 0) { - $tag->label = $langs->transnoentities('Car'); - $tag->type = 'product'; - $tag->fk_parent = $vehicleTag; - $tag->create($user); - - $tag->label = $langs->transnoentities('Truck'); - $tag->type = 'product'; - $tag->fk_parent = $vehicleTag; - $tag->create($user); - - $tag->label = $langs->transnoentities('Bicycle'); - $tag->type = 'product'; - $tag->fk_parent = $vehicleTag; - $tag->create($user); - - $tag->label = $langs->transnoentities('CommercialVehicle'); - $tag->type = 'product'; - $tag->fk_parent = $vehicleTag; - $tag->create($user); - - dolibarr_set_const($this->db, 'DOLICAR_VEHICLE_TAG', $vehicleTag, 'integer', 0, '', $conf->entity); - - } - dolibarr_set_const($this->db, 'CATEGORIE_RECURSIV_ADD', 1, 'integer', 0, '', $conf->entity); - dolibarr_set_const($this->db, 'DOLICAR_TAGS_SET', 1, 'integer', 0, '', $conf->entity); - } - if ($conf->global->CATEGORIE_RECURSIV_ADD == 0) { - dolibarr_set_const($this->db, 'CATEGORIE_RECURSIV_ADD', 1, 'integer', 0, '', $conf->entity); - } - - if ($conf->global->DOLICAR_VEHICLE_TAG == 0) { - $tag->rechercher(0, $langs->transnoentities('Car'), 'product'); - if ($tag->id > 0) { - dolibarr_set_const($this->db, 'DOLICAR_VEHICLE_TAG', $tag->id, 'integer', 0, '', $conf->entity); - } - } - - //Car brands tag - if ($conf->global->DOLICAR_CAR_BRANDS_TAG_SET == 0) { - - $tag->label = $langs->transnoentities('Brands'); - $tag->type = 'product'; - $brandTag = $tag->create($user); - - if ($brandTag > 0) { - - $filename = DOL_DOCUMENT_ROOT . '/custom/dolicar/core/car_brands.txt'; - $file = fopen( $filename, "r" ); - if ($file) { - while (($line = fgets($file)) !== false) { - $tag->label = $langs->transnoentities($line); - $tag->type = 'product'; - $tag->fk_parent = $brandTag; - $tag->create($user); - } - fclose($file); - } - - $tag->label = $langs->transnoentities('DefaultBrand'); - $tag->type = 'product'; - $tag->fk_parent = $brandTag; - $defaultBrandTag = $tag->create($user); - - dolibarr_set_const($this->db, 'DOLICAR_CAR_DEFAULT_BRAND_TAG', $defaultBrandTag, 'integer', 0, '', $conf->entity); - dolibarr_set_const($this->db, 'DOLICAR_CAR_BRANDS_TAG', $brandTag, 'integer', 0, '', $conf->entity); - dolibarr_set_const($this->db, 'DOLICAR_CAR_BRANDS_TAG_SET', 1, 'integer', 0, '', $conf->entity); - } - } elseif ($conf->global->DOLICAR_CAR_BRANDS_TAG_SET == 1 && $conf->global->DOLICAR_CAR_DEFAULT_BRAND_TAG == 0) { - $tag->label = $langs->transnoentities('DefaultBrand'); - $tag->type = 'product'; - $tag->fk_parent = $conf->global->DOLICAR_CAR_BRANDS_TAG; - $defaultBrandTag = $tag->create($user); - dolibarr_set_const($this->db, 'DOLICAR_CAR_DEFAULT_BRAND_TAG', $defaultBrandTag, 'integer', 0, '', $conf->entity); - } - - // Default product - require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; - $product = new Product($this->db); - - if ($conf->global->DOLICAR_DEFAULT_VEHICLE_SET == 0) { - $product->ref = $langs->transnoentities('DefaultVehicle'); - $product->label = $langs->transnoentities('DefaultVehicle'); - $product->status_batch = 1; - $defaultVehicle = $product->create($user); - - if ($defaultVehicle > 0) { - dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_VEHICLE', $defaultVehicle, 'integer', 0, '', $conf->entity); - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - - $tag->fetch($conf->global->DOLICAR_VEHICLE_TAG); - $tag->add_type($product, 'product'); - $tag->fetch($conf->global->DOLICAR_CAR_DEFAULT_BRAND_TAG); - $tag->add_type($product, 'product'); - } - dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_VEHICLE_SET', 1, 'integer', 0, '', $conf->entity); - } elseif ($conf->global->DOLICAR_DEFAULT_VEHICLE_SET == 1) { - $product->fetch($conf->global->DOLICAR_DEFAULT_VEHICLE); - $tag->fetch($conf->global->DOLICAR_CAR_DEFAULT_BRAND_TAG); - $tag->add_type($product, 'product'); - $product->status_batch = 1; - $product->update($product->id, $user); - dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_VEHICLE_SET', 2, 'integer', 0, '', $conf->entity); - } elseif ($conf->global->DOLICAR_DEFAULT_VEHICLE_SET == 2) { - $product->fetch($conf->global->DOLICAR_DEFAULT_VEHICLE); - $product->status_batch = 1; - $product->update($product->id, $user); - dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_VEHICLE_SET', 3, 'integer', 0, '', $conf->entity); - } - return $this->_init($sql, $options); - } - - /** - * 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); - } + // Propaldet extrafields + // Update + $extraFields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'propaldet', 0, 0, 1040, '', 1,'', 1); + $extraFields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'propaldet', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); + + // Add + $extraFields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'propaldet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); + $extraFields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'propaldet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'propaldet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'propaldet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'propaldet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'propaldet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'propaldet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'propaldet', 0, 0, '', '', 1, '', 1); + + // Commande extrafields + // Update + $extraFields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'commande', 0, 0, 1040, '', 1,'', 1); + $extraFields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'commande', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); + + // Add + $extraFields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'commande', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); + $extraFields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'commande', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'commande', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'commande', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'commande', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'commande', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'commande', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'commande', 0, 0, '', '', 1, '', 1); + + // Commandedet extrafields + // Update + $extraFields->update('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar','255', 'commandedet', 0, 0, 1040, '', 1,'', 1); + $extraFields->update('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', '255', 'commandedet', 0, 0, 1070, 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}',1, '', 1); + + // Add + $extraFields->addExtraField('registrationcertificatefr', $langs->transnoentities("RegistrationCertificateFr"), 'sellist', 1030, '', 'commandedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:80:"dolicar_registrationcertificatefr:a_registration_number:rowid::entity = $ENTITY$";N;}}', '', '', 1); + $extraFields->addExtraField('vehicle_model', $langs->transnoentities("VehicleModel"), 'varchar', 1040, '255', 'commandedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('mileage', $langs->transnoentities("Mileage"), 'int', 1050, '', 'commandedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('registration_number', $langs->transnoentities("RegistrationNumber"), 'varchar', 1060, '255', 'commandedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('linked_product', $langs->transnoentities("LinkedProduct"), 'sellist', 1070, '255', 'commandedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:36:"product:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('linked_lot', $langs->transnoentities("LinkedProductBatch"), 'sellist', 1080, '255', 'commandedet', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:42:"product_lot:batch:rowid::entity = $ENTITY$";N;}}', 1, '', 1); + $extraFields->addExtraField('first_registration_date', $langs->transnoentities("FirstRegistrationDate"), 'varchar', 1090, '255', 'commandedet', 0, 0, '', '', 1, '', 1); + $extraFields->addExtraField('VIN_number', $langs->transnoentities("VINNumber"), 'varchar', 1100, '255', 'commandedet', 0, 0, '', '', 1, '', 1); + + // Warehouse + if (getDolGlobalInt('DOLICAR_DEFAULT_WAREHOUSE_ID') <= 0) { + require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php'; + + $wareHouse = new Entrepot($this->db); + + $wareHouse->ref = $langs->transnoentities('DoliCarWarehouse'); + $wareHouse->label = $langs->transnoentities('DoliCarWarehouse'); + $wareHouse->statut = Entrepot::STATUS_OPEN_ALL; + + $wareHouseID = $wareHouse->create($user); + + dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_WAREHOUSE_ID', $wareHouseID, 'integer', 0, '', $conf->entity); + } + + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $category = new Categorie($this->db); + + // Categorie + if (getDolGlobalInt('DOLICAR_TAGS_SET') == 0) { + $category->label = $langs->transnoentities('Vehicle'); + $category->type = 'product'; + $vehicleTagID = $category->create($user); + + if ($vehicleTagID > 0) { + $category->label = $langs->transnoentities('Car'); + $category->fk_parent = $vehicleTagID; + $category->create($user); + + $category->label = $langs->transnoentities('Truck'); + $category->fk_parent = $vehicleTagID; + $category->create($user); + + $category->label = $langs->transnoentities('Bicycle'); + $category->fk_parent = $vehicleTagID; + $category->create($user); + + $category->label = $langs->transnoentities('CommercialVehicle'); + $category->fk_parent = $vehicleTagID; + $category->create($user); + + dolibarr_set_const($this->db, 'DOLICAR_VEHICLE_TAG', $vehicleTagID, 'integer', 0, '', $conf->entity); + } + + dolibarr_set_const($this->db, 'DOLICAR_TAGS_SET', 1, 'integer', 0, '', $conf->entity); + } + + // Car brands tag + if (getDolGlobalInt('DOLICAR_CAR_BRANDS_TAG_SET') == 0) { + $category->label = $langs->transnoentities('Brands'); + $category->type = 'product'; + $brandTagID = $category->create($user); + + if ($brandTagID > 0) { + $filename = DOL_DOCUMENT_ROOT . '/custom/dolicar/core/car_brands.txt'; + $file = fopen($filename, 'r'); + if ($file) { + while (($line = fgets($file)) !== false) { + $category->label = $langs->transnoentities($line); + $category->fk_parent = $brandTagID; + $category->create($user); + } + fclose($file); + } + + $category->label = $langs->transnoentities('DefaultBrand'); + $category->fk_parent = $brandTagID; + $defaultBrandTagID = $category->create($user); + + dolibarr_set_const($this->db, 'DOLICAR_CAR_DEFAULT_BRAND_TAG', $defaultBrandTagID, 'integer', 0, '', $conf->entity); + dolibarr_set_const($this->db, 'DOLICAR_CAR_BRANDS_TAG', $brandTagID, 'integer', 0, '', $conf->entity); + dolibarr_set_const($this->db, 'DOLICAR_CAR_BRANDS_TAG_SET', 1, 'integer', 0, '', $conf->entity); + } + } + + // Default product + require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + $product = new Product($this->db); + + if (getDolGlobalInt('DOLICAR_DEFAULT_VEHICLE_SET') == 0) { + $product->ref = $langs->transnoentities('DefaultVehicle'); + $product->label = $langs->transnoentities('DefaultVehicle'); + $product->status_batch = 1; + $defaultVehicleID = $product->create($user); + + if ($defaultVehicleID > 0) { + dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_VEHICLE', $defaultVehicleID, 'integer', 0, '', $conf->entity); + + $category->fetch(getDolGlobalInt('DOLICAR_VEHICLE_TAG')); + $category->add_type($product, 'product'); + $category->fetch(getDolGlobalInt('DOLICAR_CAR_DEFAULT_BRAND_TAG')); + $category->add_type($product, 'product'); + } + dolibarr_set_const($this->db, 'DOLICAR_DEFAULT_VEHICLE_SET', 1, 'integer', 0, '', $conf->entity); + } + + return $this->_init($sql, $options); + } + + /** + * 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 = ''): int + { + $sql = []; + return $this->_remove($sql, $options); + } } diff --git a/core/tpl/accountancy_linked_objects.tpl.php b/core/tpl/accountancy_linked_objects.tpl.php deleted file mode 100644 index b8638cb..0000000 --- a/core/tpl/accountancy_linked_objects.tpl.php +++ /dev/null @@ -1,148 +0,0 @@ -fetchAll('', '','','',$fromProductLot ? ['fk_lot'=> GETPOST('id')] : ['rowid' => GETPOST('id')]); -$linked_rc_ids = array(); -$linked_facture_ids = array(); -if (!empty($RC_list)) { - foreach ($RC_list as $rc) { - $linked_rc_ids[] = $rc->id; - $objectsLinkedList[$rc->id] = $rc->getObjectsLinked(); - } -} -$pictopath = dol_buildpath('/dolicar/img/dolicar_color.png', 1); -$pictoDoliCar = img_picto('', $pictopath, '', 1, 0, 0, '', 'pictoModule'); - -$outputline = '
'. $pictoDoliCar . $langs->transnoentities('ObjectsLinked') .'
'; -$outputline .= '
'; -$outputline .= ''; -$outputline .= ' '; -$outputline .= ' '; -$outputline .= ' '; -$outputline .= ' '; -$outputline .= ''; - -$objectsLinkedCounter = 0; - -if (!empty($objectsLinkedList)) { - foreach ($objectsLinkedList as $subList) { - if (!empty($subList)) { - foreach ($subList as $key => $object_ids) { - $objectsLinkedCounter++; - switch ($key) { - case 'facture': - foreach ($object_ids as $object_id) { - - $facture->fetch($object_id); - $facture->fetch_optionals(); - $outputline .= ''; - - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - } - break; -// case 'facturedet': -// foreach ($object_ids as $object_id) { -// -// $facturedet->fetch($object_id); -// $facturedet->fetch_optionals(); -// $facture->fetch($facturedet->fk_facture); -// $outputline .= ''; -// -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// } -// break; - case 'propal': - foreach ($object_ids as $object_id) { - - $propal->fetch($object_id); - $propal->fetch_optionals(); - $outputline .= ''; - - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - } - break; -// case 'propaldet': -// foreach ($object_ids as $object_id) { -// -// $propaldet->fetch($object_id); -// $propaldet->fetch_optionals(); -// $propal->fetch($propaldet->fk_propal); -// $outputline .= ''; -// -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// } -// break; - case 'commande': - foreach ($object_ids as $object_id) { - - $commande->fetch($object_id); - $commande->fetch_optionals(); - $outputline .= ''; - - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - } - break; -// case 'commandedet': -// foreach ($object_ids as $object_id) { -// -// $commandedet->fetch($object_id); -// $commandedet->fetch_optionals(); -// $commande->fetch($commandedet->fk_commande); -// $outputline .= ''; -// -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// $outputline .= ''; -// } -// break; - } - } - } - } -} -if ($objectsLinkedCounter == 0) { - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; - $outputline .= ''; -} -$outputline .= '
'. $langs->transnoentities('ObjectType') .''. $langs->transnoentities('Object') .''. $langs->transnoentities('Mileage') .''. $langs->transnoentities('Date') .'
'. $langs->transnoentities($key) .''. $facture->getNomUrl(1) .''. $facture->array_options['options_mileage'] .''. dol_print_date($facture->date_creation, 'dayhour') .'
'. $langs->transnoentities($key) .''. $facture->getNomUrl() .''. $facturedet->array_options['options_mileage'] .''. dol_print_date($facturedet->date_creation, 'dayhour') .'
'. $langs->transnoentities($key) .''. $propal->getNomUrl(1) .''. $propal->array_options['options_mileage'] .''. dol_print_date($propal->date_creation, 'dayhour') .'
'. $langs->transnoentities($key) .''. $propal->getNomUrl() .''. $propaldet->array_options['options_mileage'] .''. dol_print_date($propaldet->date_creation, 'dayhour') .'
'. $langs->transnoentities($key) .''. $commande->getNomUrl(1) .''. $commande->array_options['options_mileage'] .''. dol_print_date($commande->date_creation, 'dayhour') .'
'. $langs->transnoentities($key) .''. $commande->getNomUrl() .''. $commandedet->array_options['options_mileage'] .''. dol_print_date($commandedet->date_creation, 'dayhour') .'
' . $langs->trans('NoLinkedObjectsToPrint') . '
'; -?> - diff --git a/core/tpl/dolicar_preinstall.php b/core/tpl/dolicar_preinstall.php deleted file mode 100644 index ba5e033..0000000 --- a/core/tpl/dolicar_preinstall.php +++ /dev/null @@ -1,26 +0,0 @@ -global->DOLICAR_MENU_DEFAULT_VEHICLE_UPDATED == 0) { - - require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; - - $url = '/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php?action=create&fk_product=' . $conf->global->DOLICAR_DEFAULT_VEHICLE; - - $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET"; - $sql .= " url='".$db->escape($url)."'"; - $sql .= " WHERE leftmenu='dolicar_registrationcertificatefr'"; - $sql .= " AND entity=" . $conf->entity; - - $resql = $db->query($sql); - if (!$resql) { - $error = "Error ".$db->lasterror(); - return -1; - } - dolibarr_set_const($db, 'DOLICAR_MENU_DEFAULT_VEHICLE_UPDATED', 1, 'integer', 0, '', $conf->entity); - ?> - - + * + * 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 core/tpl/dolicar_registrationcertificatefr_immatriculation_api_fetch_action.tpl.php + * \ingroup dolicar + * \brief Template page for registration certificate immatriculation api action + */ + +/** + * The following vars must be defined: + * Global : $conf, $db, $langs, $user, + * Parameters : $action, + * Objects : $object + */ + require_once __DIR__ . '/../../../../core/lib/admin.lib.php'; + // In order to avoid product creation error $conf->global->BARCODE_PRODUCT_ADDON_NUM = 0; @@ -7,249 +37,234 @@ setEventMessage($langs->trans('ZeroApiRequestsRemaining'), 'errors'); header('Location: ' . $_SERVER['PHP_SELF'] . '?action=create&a_registration_number=' . GETPOST('registrationNumber')); exit; -} else if ($conf->global->DOLICAR_API_REMAINING_REQUESTS_COUNTER <= 100) { +} elseif ($conf->global->DOLICAR_API_REMAINING_REQUESTS_COUNTER <= 100) { setEventMessage($langs->trans('LessThanHundredApiRequestsRemaining'), 'warning'); } -$apiUrl = 'http://www.immatriculationapi.com/api/reg.asmx/CheckFrance'; - -$username = $conf->global->DOLICAR_IMMATRICULATION_API_USERNAME; +$apiUrl = 'http://www.immatriculationapi.com/api/reg.asmx/CheckFrance'; +$username = getDolGlobalString('DOLICAR_IMMATRICULATION_API_USERNAME'); $registrationNumber = GETPOST('registrationNumber'); -$registrationNumber = strtoupper($registrationNumber); +$registrationNumber = dol_strtoupper($registrationNumber); if (dol_strlen($registrationNumber) > 0) { - $registrationNumber = normalize_registration_number($registrationNumber); - $existingRegistrationCertificate = $object->fetchAll('', '', 0, 0, ['customsql' => ' ref = "' . $registrationNumber . '"']); + $registrationNumber = normalize_registration_number($registrationNumber); + $existingRegistrationCertificate = $object->fetchAll('', '', 0, 0, ['customsql' => ' ref = "' . $registrationNumber . '"']); - if (is_array($existingRegistrationCertificate) && !empty($existingRegistrationCertificate)) { - $existingRegistrationCertificateObject = array_shift($existingRegistrationCertificate); - $existingRegistrationCertificateId = $existingRegistrationCertificateObject->id; + if (is_array($existingRegistrationCertificate) && !empty($existingRegistrationCertificate)) { + $existingRegistrationCertificateObject = array_shift($existingRegistrationCertificate); + $existingRegistrationCertificateId = $existingRegistrationCertificateObject->id; - setEventMessages($langs->trans("LicencePlateWasAlreadyExisting"), null, 'mesgs'); - header('Location: ' . dol_buildpath('/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1) . '?id=' . $existingRegistrationCertificateId); - exit; - } + setEventMessages($langs->trans("LicencePlateWasAlreadyExisting"), []); + header('Location: ' . dol_buildpath('/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1) . '?id=' . $existingRegistrationCertificateId); + exit; + } } if (dol_strlen($username) > 0) { - // Setup request to send json via POST + // Setup request to send json via POST - $xmlData = @file_get_contents( $apiUrl . '?RegistrationNumber=' . $registrationNumber ."&username=" . $username); + $xmlData = @file_get_contents( $apiUrl . '?RegistrationNumber=' . $registrationNumber ."&username=" . $username); - if (empty($xmlData)) { - $usernameConfigUrl = DOL_URL_ROOT . '/custom/dolicar/admin/registrationcertificate.php'; + if (empty($xmlData)) { + $usernameConfigUrl = DOL_URL_ROOT . '/custom/dolicar/admin/registrationcertificate.php'; - setEventMessage($langs->trans('BadAPIUsernameOrBadLicencePlateFormat', $usernameConfigUrl), 'errors'); - $error++; - $action = $createRegistrationCertificate ? '' : 'create'; - } else { - $xml = simplexml_load_string($xmlData); - $strJson = $xml->vehicleJson; - $registrationCertificateObject = json_decode($strJson); + setEventMessage($langs->trans('BadAPIUsernameOrBadLicencePlateFormat', $usernameConfigUrl), 'errors'); + $error++; + $action = $createRegistrationCertificate ? '' : 'create'; + } else { + $xml = simplexml_load_string($xmlData); + $strJson = $xml->vehicleJson; + $registrationCertificateObject = json_decode($strJson); dolibarr_set_const($db, 'DOLICAR_API_REMAINING_REQUESTS_COUNTER', $conf->global->DOLICAR_API_REMAINING_REQUESTS_COUNTER - 1, 'integer', 0, '', $conf->entity); - dolibarr_set_const($db, 'DOLICAR_API_REQUESTS_COUNTER', $conf->global->DOLICAR_API_REQUESTS_COUNTER + 1, 'integer', 0, '', $conf->entity); - setEventMessages($langs->trans("LicencePlateInformationsCharged"), null, 'mesgs'); - setEventMessages($langs->trans("RemainingRequests", $conf->global->DOLICAR_API_REMAINING_REQUESTS_COUNTER), null, 'mesgs'); - } + dolibarr_set_const($db, 'DOLICAR_API_REQUESTS_COUNTER', getDolGlobalString('DOLICAR_API_REMAINING_REQUESTS_COUNTER') + 1, 'integer', 0, '', $conf->entity); + setEventMessages($langs->trans('LicencePlateInformationsCharged'), []); + setEventMessages($langs->trans('RemainingRequests', getDolGlobalString('DOLICAR_API_REMAINING_REQUESTS_COUNTER')), []); + } } else { - $usernameConfigUrl = DOL_URL_ROOT . '/custom/dolicar/admin/registrationcertificate.php'; + $usernameConfigUrl = DOL_URL_ROOT . '/custom/dolicar/admin/registrationcertificate.php'; - setEventMessage($langs->trans('BadAPIUsername', $usernameConfigUrl), 'errors'); - $error++; - $action = $createRegistrationCertificate ? '' : 'create'; + setEventMessage($langs->trans('BadAPIUsername', $usernameConfigUrl), 'errors'); + $error++; + $action = $createRegistrationCertificate ? '' : 'create'; } if (is_object($registrationCertificateObject)) { - //Product Creation - $productRef = $registrationCertificateObject->CarMake->CurrentTextValue . ' ' . $registrationCertificateObject->CarModel->CurrentTextValue . ' ' . $registrationCertificateObject->ExtendedData->version; - $sanitizedProductRef = dol_sanitizeFileName(dol_string_nospecial(trim($productRef))); - $result = $product->fetch('', $sanitizedProductRef); - - if ($result <= 0) { - $product->ref = $productRef; - $product->label = $productRef; + //Product Creation + $productRef = $registrationCertificateObject->CarMake->CurrentTextValue . ' ' . $registrationCertificateObject->CarModel->CurrentTextValue . ' ' . $registrationCertificateObject->ExtendedData->version; + $sanitizedProductRef = dol_sanitizeFileName(dol_string_nospecial(trim($productRef))); + $result = $product->fetch('', $sanitizedProductRef); + + if ($result <= 0) { + $product->ref = $productRef; + $product->label = $productRef; $product->status_batch = 1; - $productId = $product->create($user); - - if ($productId > 0) { - $resultCategory = $category->fetch(0, $registrationCertificateObject->CarMake->CurrentTextValue); - - if ($category <= 0) { - $category->label = $registrationCertificateObject->CarMake->CurrentTextValue; - $category->description = $registrationCertificateObject->CarMake->CurrentTextValue; - $category->visible = 1; - $category->type = 'product'; - $category->fk_parent = $conf->global->DOLICAR_CAR_BRANDS_TAG; - $categoryID = $category->create($user); - } else { - $categoryID = $category->id; - } - - $product->setCategories(array($categoryID, $conf->global->DOLICAR_CAR_BRANDS_TAG)); - } else { - $error++; - } - } - - $productLotLabel = $registrationCertificateObject->ExtendedData->numSerieMoteur; - $resultProductlot = $productLot->fetch(0,$product->id ,$productLotLabel); - - if ($resultProductlot <= 0) { - $productLot->batch = $productLotLabel; - $productLot->fk_product = $product->id; - $resultProductLotCreation = $productLot->create($user); - $productLot->fetch($resultProductLotCreation); - $product->fetch($product->id); - $product->correct_stock_batch( - $user, - $conf->global->DOLICAR_DEFAULT_WAREHOUSE_ID, - 1, - 0, - $langs->trans('ClientVehicle'), // label movement - 0, - '', - '', - $productLot->batch, - '', - 'dolicar_registrationcertificate', - 0 - ); - - if ($resultProductLotCreation <= 0) { - $error++; - } - } - - if ($createRegistrationCertificate > 0) { - - $projectID = $parameters['projectID']; - $thirdpartyID = $parameters['thirdpartyID']; - - $object->fk_product = $product->id; - $object->fk_lot = $productLot->id; - $object->fk_soc = $thirdpartyID; - $object->fk_project = $projectID; - $object->a_registration_number = $registrationNumber; - - $registrationDateArray = str_split($registrationCertificateObject->ExtendedData->datePremiereMiseCirculation, 2); - $formattedRegistrationDate = $registrationDateArray[0] . '/' . $registrationDateArray[1] . '/' . $registrationDateArray[2] . $registrationDateArray[3]; - - $sqlDate = dol_mktime(12, 0, 0, $registrationDateArray[1], $registrationDateArray[0], $registrationDateArray[2] . $registrationDateArray[3]); // for date without hour, we use gmt - - $object->b_first_registration_date = $sqlDate; - $object->b_first_registration_dateday = $registrationDateArray[0]; - $object->b_first_registration_datemonth = $registrationDateArray[1]; - $object->b_first_registration_dateyear = $registrationDateArray[2] . $registrationDateArray[3]; - $object->c1_owner_name = ''; - $object->c3_registration_address = ''; - $object->c4a_vehicle_owner = ''; - $object->c41_second_owner_number = ''; - $object->c41_second_owner_name = ''; - $object->d1_vehicle_brand = $registrationCertificateObject->CarMake->CurrentTextValue; - $object->d2_vehicle_type = $registrationCertificateObject->ExtendedData->typeVehicule; - $object->d21_vehicle_cnit = $registrationCertificateObject->ExtendedData->CNIT; - $object->d3_vehicle_model = $registrationCertificateObject->ExtendedData->libelleModele; - $object->e_vehicle_serial_number = $registrationCertificateObject->ExtendedData->numSerieMoteur; - $object->f1_technical_ptac = ''; - $object->f2_ptac = ''; - $object->f3_ptra = ''; - $object->g_vehicle_weight = ''; - $object->g1_vehicle_empty_weight = ''; - $object->h_validity_period = ''; - $object->i_vehicle_registration_date = $registrationCertificateObject->RegistrationDate; - $object->j_vehicle_category = ''; - $object->j1_national_type = $registrationCertificateObject->ExtendedData->genre; - $object->j2_european_bodywork = ''; - $object->j3_national_bodywork = ''; - $object->k_type_approval_number = ''; - $object->p1_cylinder_capacity = $registrationCertificateObject->ExtendedData->EngineCC; - $object->p2_maximum_net_power = ''; - $object->p3_fuel_type = $registrationCertificateObject->FuelType->CurrentTextValue; - $object->p6_national_administrative_power = $registrationCertificateObject->ExtendedData->puissance; - $object->q_power_to_weight_ratio = ''; - $object->s1_seating_capacity = $registrationCertificateObject->ExtendedData->nbPlace; - $object->s2_standing_capacity = ''; - $object->u1_stationary_noise_level = ''; - $object->u2_motor_speed = ''; - $object->v7_co2_emission = $registrationCertificateObject->ExtendedData->Co2; - $object->v9_environmental_category = ''; - $object->x1_first_technical_inspection_date = ''; - $object->y1_regional_tax = ''; - $object->y2_professional_tax = ''; - $object->y3_ecological_tax = ''; - $object->y4_management_tax = ''; - $object->y5_forwarding_expenses_tax = ''; - $object->y6_total_price_vehicle_registration = ''; - $object->z1_specific_details = ''; - $object->z2_specific_details = ''; - $object->z3_specific_details = ''; - $object->z4_specific_details = ''; - $object->json = json_encode($registrationCertificateObject); - - $registrationCertificateId = $object->create($user); - - $backtopage = dol_buildpath('/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1) . '?id=' . $registrationCertificateId; - - } else { - $_POST['fk_product'] = $product->id; - $_POST['fk_lot'] = $productLot->id; - $_POST['fk_soc'] = $thirdpartyID; - $_POST['fk_project'] = $projectID; - $_POST['a_registration_number'] = $registrationNumber; - - $registrationDateArray = str_split($registrationCertificateObject->ExtendedData->datePremiereMiseCirculation, 2); - $formattedRegistrationDate = $registrationDateArray[0] . '/' . $registrationDateArray[1] . '/' . $registrationDateArray[2] . $registrationDateArray[3]; - - $_POST['b_first_registration_date'] = $formattedRegistrationDate; - $_POST['b_first_registration_dateday'] = $registrationDateArray[0]; - $_POST['b_first_registration_datemonth'] = $registrationDateArray[1]; - $_POST['b_first_registration_dateyear'] = $registrationDateArray[2] . $registrationDateArray[3]; - $_POST['c1_owner_name'] = ''; - $_POST['c3_registration_address'] = ''; - $_POST['c4a_vehicle_owner'] = ''; - $_POST['c41_second_owner_number'] = ''; - $_POST['c41_second_owner_name'] = ''; - $_POST['d1_vehicle_brand'] = $registrationCertificateObject->CarMake->CurrentTextValue; - $_POST['d2_vehicle_type'] = $registrationCertificateObject->ExtendedData->typeVehicule; - $_POST['d21_vehicle_cnit'] = $registrationCertificateObject->ExtendedData->CNIT; - $_POST['d3_vehicle_model'] = $registrationCertificateObject->ExtendedData->libelleModele; - $_POST['e_vehicle_serial_number'] = $registrationCertificateObject->ExtendedData->numSerieMoteur; - $_POST['f1_technical_ptac'] = ''; - $_POST['f2_ptac'] = ''; - $_POST['f3_ptra'] = ''; - $_POST['g_vehicle_weight'] = ''; - $_POST['g1_vehicle_empty_weight'] = ''; - $_POST['h_validity_period'] = ''; - $_POST['i_vehicle_registration_date'] = $registrationCertificateObject->RegistrationDate; - $_POST['j_vehicle_category'] = ''; - $_POST['j1_national_type'] = $registrationCertificateObject->ExtendedData->genre; - $_POST['j2_european_bodywork'] = ''; - $_POST['j3_national_bodywork'] = ''; - $_POST['k_type_approval_number'] = ''; - $_POST['p1_cylinder_capacity'] = $registrationCertificateObject->ExtendedData->EngineCC; - $_POST['p2_maximum_net_power'] = ''; - $_POST['p3_fuel_type'] = $registrationCertificateObject->FuelType->CurrentTextValue; - $_POST['p6_national_administrative_power'] = $registrationCertificateObject->ExtendedData->puissance; - $_POST['q_power_to_weight_ratio'] = ''; - $_POST['s1_seating_capacity'] = $registrationCertificateObject->ExtendedData->nbPlace; - $_POST['s2_standing_capacity'] = ''; - $_POST['u1_stationary_noise_level'] = ''; - $_POST['u2_motor_speed'] = ''; - $_POST['v7_co2_emission'] = $registrationCertificateObject->ExtendedData->Co2; - $_POST['v9_environmental_category'] = ''; - $_POST['x1_first_technical_inspection_date'] = ''; - $_POST['y1_regional_tax'] = ''; - $_POST['y2_professional_tax'] = ''; - $_POST['y3_ecological_tax'] = ''; - $_POST['y4_management_tax'] = ''; - $_POST['y5_forwarding_expenses_tax'] = ''; - $_POST['y6_total_price_vehicle_registration'] = ''; - $_POST['z1_specific_details'] = ''; - $_POST['z2_specific_details'] = ''; - $_POST['z3_specific_details'] = ''; - $_POST['z4_specific_details'] = ''; - $_POST['json'] = json_encode($registrationCertificateObject); - - $action = 'create'; - } + $productId = $product->create($user); + + if ($productId > 0) { + $resultCategory = $category->fetch(0, $registrationCertificateObject->CarMake->CurrentTextValue); + + if ($category <= 0) { + $category->label = $registrationCertificateObject->CarMake->CurrentTextValue; + $category->description = $registrationCertificateObject->CarMake->CurrentTextValue; + $category->visible = 1; + $category->type = 'product'; + $category->fk_parent = $conf->global->DOLICAR_CAR_BRANDS_TAG; + $categoryID = $category->create($user); + } else { + $categoryID = $category->id; + } + + $product->setCategories(array($categoryID, $conf->global->DOLICAR_CAR_BRANDS_TAG)); + } else { + $error++; + } + } + + $productLotLabel = $registrationCertificateObject->ExtendedData->numSerieMoteur; + $resultProductlot = $productLot->fetch(0,$product->id ,$productLotLabel); + + if ($resultProductlot <= 0) { + $productLot->batch = $productLotLabel; + $productLot->fk_product = $product->id; + $resultProductLotCreation = $productLot->create($user); + $productLot->fetch($resultProductLotCreation); + $product->fetch($product->id); + $product->correct_stock_batch($user, $conf->global->DOLICAR_DEFAULT_WAREHOUSE_ID, 1,0, $langs->transnoentities('ClientVehicle'), 0, '', '', $productLot->batch, '', 'dolicar_registrationcertificate', 0); + + if ($resultProductLotCreation <= 0) { + $error++; + } + } + + if ($createRegistrationCertificate > 0) { + + $projectID = $parameters['projectID']; + $thirdpartyID = $parameters['thirdpartyID']; + + $object->fk_product = $product->id; + $object->fk_lot = $productLot->id; + $object->fk_soc = $thirdpartyID; + $object->fk_project = $projectID; + $object->a_registration_number = $registrationNumber; + + $registrationDateArray = str_split($registrationCertificateObject->ExtendedData->datePremiereMiseCirculation, 2); + $formattedRegistrationDate = $registrationDateArray[0] . '/' . $registrationDateArray[1] . '/' . $registrationDateArray[2] . $registrationDateArray[3]; + + $sqlDate = dol_mktime(12, 0, 0, $registrationDateArray[1], $registrationDateArray[0], $registrationDateArray[2] . $registrationDateArray[3]); // for date without hour, we use gmt + + $object->b_first_registration_date = $sqlDate; + $object->b_first_registration_dateday = $registrationDateArray[0]; + $object->b_first_registration_datemonth = $registrationDateArray[1]; + $object->b_first_registration_dateyear = $registrationDateArray[2] . $registrationDateArray[3]; + $object->c1_owner_name = ''; + $object->c3_registration_address = ''; + $object->c4a_vehicle_owner = ''; + $object->c41_second_owner_number = ''; + $object->c41_second_owner_name = ''; + $object->d1_vehicle_brand = $registrationCertificateObject->CarMake->CurrentTextValue; + $object->d2_vehicle_type = $registrationCertificateObject->ExtendedData->typeVehicule; + $object->d21_vehicle_cnit = $registrationCertificateObject->ExtendedData->CNIT; + $object->d3_vehicle_model = $registrationCertificateObject->ExtendedData->libelleModele; + $object->e_vehicle_serial_number = $registrationCertificateObject->ExtendedData->numSerieMoteur; + $object->f1_technical_ptac = ''; + $object->f2_ptac = ''; + $object->f3_ptra = ''; + $object->g_vehicle_weight = ''; + $object->g1_vehicle_empty_weight = ''; + $object->h_validity_period = ''; + $object->i_vehicle_registration_date = $registrationCertificateObject->RegistrationDate; + $object->j_vehicle_category = ''; + $object->j1_national_type = $registrationCertificateObject->ExtendedData->genre; + $object->j2_european_bodywork = ''; + $object->j3_national_bodywork = ''; + $object->k_type_approval_number = ''; + $object->p1_cylinder_capacity = $registrationCertificateObject->ExtendedData->EngineCC; + $object->p2_maximum_net_power = ''; + $object->p3_fuel_type = $registrationCertificateObject->FuelType->CurrentTextValue; + $object->p6_national_administrative_power = $registrationCertificateObject->ExtendedData->puissance; + $object->q_power_to_weight_ratio = ''; + $object->s1_seating_capacity = $registrationCertificateObject->ExtendedData->nbPlace; + $object->s2_standing_capacity = ''; + $object->u1_stationary_noise_level = ''; + $object->u2_motor_speed = ''; + $object->v7_co2_emission = $registrationCertificateObject->ExtendedData->Co2; + $object->v9_environmental_category = ''; + $object->x1_first_technical_inspection_date = ''; + $object->y1_regional_tax = ''; + $object->y2_professional_tax = ''; + $object->y3_ecological_tax = ''; + $object->y4_management_tax = ''; + $object->y5_forwarding_expenses_tax = ''; + $object->y6_total_price_vehicle_registration = ''; + $object->z1_specific_details = ''; + $object->z2_specific_details = ''; + $object->z3_specific_details = ''; + $object->z4_specific_details = ''; + $object->json = json_encode($registrationCertificateObject); + + $registrationCertificateId = $object->create($user); + + $backtopage = dol_buildpath('/custom/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1) . '?id=' . $registrationCertificateId; + + } else { + $_POST['fk_product'] = $product->id; + $_POST['fk_lot'] = $productLot->id; + $_POST['fk_soc'] = $thirdpartyID; + $_POST['fk_project'] = $projectID; + + $registrationDateArray = str_split($registrationCertificateObject->ExtendedData->datePremiereMiseCirculation, 2); + + $_POST['a_registration_number'] = $registrationNumber; + $_POST['b_first_registration_date'] = $registrationDateArray[0] . '/' . $registrationDateArray[1] . '/' . $registrationDateArray[2] . $registrationDateArray[3]; + $_POST['b_first_registration_dateday'] = $registrationDateArray[0]; + $_POST['b_first_registration_datemonth'] = $registrationDateArray[1]; + $_POST['b_first_registration_dateyear'] = $registrationDateArray[2] . $registrationDateArray[3]; + $_POST['c1_owner_name'] = ''; + $_POST['c3_registration_address'] = ''; + $_POST['c4a_vehicle_owner'] = ''; + $_POST['c41_second_owner_number'] = ''; + $_POST['c41_second_owner_name'] = ''; + $_POST['d1_vehicle_brand'] = $registrationCertificateObject->CarMake->CurrentTextValue; + $_POST['d2_vehicle_type'] = $registrationCertificateObject->ExtendedData->typeVehicule; + $_POST['d21_vehicle_cnit'] = $registrationCertificateObject->ExtendedData->CNIT; + $_POST['d3_vehicle_model'] = $registrationCertificateObject->ExtendedData->libelleModele; + $_POST['e_vehicle_serial_number'] = $registrationCertificateObject->ExtendedData->numSerieMoteur; + $_POST['f1_technical_ptac'] = ''; + $_POST['f2_ptac'] = ''; + $_POST['f3_ptra'] = ''; + $_POST['g_vehicle_weight'] = ''; + $_POST['g1_vehicle_empty_weight'] = ''; + $_POST['h_validity_period'] = ''; + $_POST['i_vehicle_registration_date'] = $registrationCertificateObject->RegistrationDate; + $_POST['j_vehicle_category'] = ''; + $_POST['j1_national_type'] = $registrationCertificateObject->ExtendedData->genre; + $_POST['j2_european_bodywork'] = ''; + $_POST['j3_national_bodywork'] = ''; + $_POST['k_type_approval_number'] = ''; + $_POST['p1_cylinder_capacity'] = $registrationCertificateObject->ExtendedData->EngineCC; + $_POST['p2_maximum_net_power'] = ''; + $_POST['p3_fuel_type'] = $registrationCertificateObject->FuelType->CurrentTextValue; + $_POST['p6_national_administrative_power'] = $registrationCertificateObject->ExtendedData->puissance; + $_POST['q_power_to_weight_ratio'] = ''; + $_POST['s1_seating_capacity'] = $registrationCertificateObject->ExtendedData->nbPlace; + $_POST['s2_standing_capacity'] = ''; + $_POST['u1_stationary_noise_level'] = ''; + $_POST['u2_motor_speed'] = ''; + $_POST['v7_co2_emission'] = $registrationCertificateObject->ExtendedData->Co2; + $_POST['v9_environmental_category'] = ''; + $_POST['x1_first_technical_inspection_date'] = ''; + $_POST['y1_regional_tax'] = ''; + $_POST['y2_professional_tax'] = ''; + $_POST['y3_ecological_tax'] = ''; + $_POST['y4_management_tax'] = ''; + $_POST['y5_forwarding_expenses_tax'] = ''; + $_POST['y6_total_price_vehicle_registration'] = ''; + $_POST['z1_specific_details'] = ''; + $_POST['z2_specific_details'] = ''; + $_POST['z3_specific_details'] = ''; + $_POST['z4_specific_details'] = ''; + $_POST['json'] = json_encode($registrationCertificateObject); + + $action = 'create'; + } } diff --git a/core/tpl/registrationcertificatefr_linked_objects.tpl.php b/core/tpl/registrationcertificatefr_linked_objects.tpl.php new file mode 100644 index 0000000..6f4e996 --- /dev/null +++ b/core/tpl/registrationcertificatefr_linked_objects.tpl.php @@ -0,0 +1,101 @@ + + * + * 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 core/tpl/registrationcertificatefr_linked_objects.tpl.php + * \ingroup dolicar + * \brief Template page for registrationcertificatefr linked objects + */ + +/** + * The following vars must be defined : + * Global : $db, $langs + * Variable : $fromProductLot + */ + +// Load Dolibarr libraries +require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php'; +require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; + +// Load DoliCar libraries +require_once __DIR__ . '/../../class/registrationcertificatefr.class.php'; + +$registrationCertificate = new RegistrationCertificateFr($db); +$propal = new Propal($db); +$commande = new Commande($db); +$facture = new Facture($db); + +$registrationCertificates = $registrationCertificate->fetchAll('', '',0,0, ['customsql' => ($fromProductLot ? 't.fk_lot = ' : 't.rowid = ') . GETPOST('id')]); +if (is_array($registrationCertificates) && !empty($registrationCertificates)) { + foreach ($registrationCertificates as $registrationCertificate) { + $objectsLinkedList[$registrationCertificate->id] = $registrationCertificate->getLinkedObjects(); + } + + $out = load_fiche_titre($langs->transnoentities('LinkedObjects'), '', 'dolicar_color@dolicar'); + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + + function renderTableRows($object, $objectIDS, $langs, &$out, $key) { + foreach ($objectIDS as $objectID) { + $object->fetch($objectID); + $object->fetch_optionals(); + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + } + } + + if (!empty($objectsLinkedList)) { + foreach ($objectsLinkedList as $subList) { + if (!empty($subList)) { + foreach ($subList as $key => $objectIDS) { + switch ($key) { + case 'facture': + renderTableRows($facture, $objectIDS, $langs, $out, $key); + break; + case 'propal': + renderTableRows($propal, $objectIDS, $langs, $out, $key); + break; + case 'commande': + renderTableRows($commande, $objectIDS, $langs, $out, $key); + break; + } + } + } else { + $out .= ''; + } + } + } else { + $out .= ''; + } + $out .= '
' . $langs->trans('ObjectType') . '' . $langs->trans('Object') . '' . $langs->trans('Mileage') . '' . $langs->trans('Date') . '
'. $langs->transnoentities($key) .''. $object->getNomUrl(1) .''. $object->array_options['options_mileage'] .''. dol_print_date($object->date_creation, 'dayhour') .'
' . $langs->trans('NoLinkedObjectsToPrint') . '
' . $langs->trans('NoLinkedObjectsToPrint') . '
'; + ?> + + + +/* Copyright (C) 2022-2024 EVARISK * * 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,136 +18,115 @@ /** * \file core/triggers/interface_99_modDoliCar_DoliCarTriggers.class.php * \ingroup dolicar - * \brief Example trigger. - * - * Put detailed description here. - * - * \remarks You can create other triggers by copying this one. - * - File name should be either: - * - interface_99_modDoliCar_MyTrigger.class.php - * - interface_99_all_MyTrigger.class.php - * - The file must stay in core/triggers - * - The class name must be InterfaceMytrigger - */ - -require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; + * \brief DoliCar trigger +*/ +// Load Dolibarr libraries +require_once DOL_DOCUMENT_ROOT . '/core/triggers/dolibarrtriggers.class.php'; /** - * Class of triggers for DoliCar module + * Class of triggers for DoliCar module */ class InterfaceDoliCarTriggers extends DolibarrTriggers { - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i', '', get_class($this)); - $this->family = "demo"; - $this->description = "DoliCar triggers."; - // 'development', 'experimental', 'dolibarr' or version - $this->version = '1.1.1'; - $this->picto = 'dolicar@dolicar'; - } - - /** - * Trigger name - * - * @return string Name of trigger file - */ - public function getName() - { - return $this->name; - } - - /** - * Trigger description - * - * @return string Description of trigger file - */ - public function getDesc() - { - return $this->description; - } - - - /** - * Function called when a Dolibarrr business event is done. - * All functions "runTrigger" are triggered if file - * is inside directory core/triggers - * - * @param string $action Event action code - * @param CommonObject $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param Conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) - { - if (!isModEnabled('dolicar')) { - return 0; // If module is not enabled, we do nothing - } - - // Data and type of action are stored into $object and $action - dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . '. id=' . $object->id); - - require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; - $now = dol_now(); - $actioncomm = new ActionComm($this->db); - - $actioncomm->elementtype = $object->element . '@dolicar'; - $actioncomm->type_code = 'AC_OTH_AUTO'; - $actioncomm->datep = $now; - $actioncomm->fk_element = $object->id; - $actioncomm->userownerid = $user->id; - $actioncomm->percentage = -1; - - switch ($action) { - case 'DOLICAR_PRODUCTLOT_MILEAGE_MODIFY': - $actioncomm->elementtype = 'productlot'; - $actioncomm->code = 'AC_DOLICAR_PRODUCTLOT_MILEAGE_MODIFY'; - $actioncomm->label = $langs->trans('ProductLotMileageModifyTrigger'); - $actioncomm->note_private = $object->array_options['options_mileage']; - $actioncomm->create($user); - break; - case 'REGISTRATIONCERTIFICATEFR_CREATE' : - $actioncomm->code = 'AC_' . strtoupper($object->element) . '_CREATE'; - $actioncomm->label = $langs->trans('ObjectCreateTrigger', $langs->transnoentities(ucfirst($object->element))); - $actioncomm->create($user); - break; - - case 'REGISTRATIONCERTIFICATEFR_MODIFY' : - $actioncomm->code = 'AC_' . strtoupper($object->element) . '_MODIFY'; - $actioncomm->label = $langs->trans('ObjectModifyTrigger', $langs->transnoentities(ucfirst($object->element))); - $actioncomm->create($user); - break; - - case 'REGISTRATIONCERTIFICATEFR_DELETE' : - $actioncomm->code = 'AC_ ' . strtoupper($object->element) . '_DELETE'; - $actioncomm->label = $langs->trans('ObjectDeleteTrigger', $langs->transnoentities(ucfirst($object->element))); - $actioncomm->create($user); - break; - default: - dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); - break; - } - return 0; - - // Or you can execute some code here - switch ($action) { - - - default: - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - break; - } - - return 0; - } + /** + * @var DoliDB Database handler + */ + protected $db; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + + $this->name = preg_replace('/^Interface/i', '', get_class($this)); + $this->family = "demo"; + $this->description = 'DoliCar triggers.'; + $this->version = '1.1.1'; + $this->picto = 'dolicar@dolicar'; + } + + /** + * Trigger name + * + * @return string Name of trigger file + */ + public function getName(): string + { + return parent::getName(); + } + + /** + * Trigger description + * + * @return string Description of trigger file + */ + public function getDesc(): string + { + return parent::getDesc(); + } + + /** + * Function called when a Dolibarr business event is done + * All functions "runTrigger" are triggered if file + * is inside directory core/triggers + * + * @param string $action Event action code + * @param CommonObject $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param Conf $conf Object conf + * @return int 0 < if KO, 0 if no triggered ran, >0 if OK + * @throws Exception + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf): int + { + if (!isModEnabled('dolicar')) { + return 0; // If module is not enabled, we do nothing + } + + // Data and type of action are stored into $object and $action + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . '. id=' . $object->id); + + require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; + $now = dol_now(); + $actionComm = new ActionComm($this->db); + + $actionComm->elementtype = $object->element . '@dolicar'; + $actionComm->type_code = 'AC_OTH_AUTO'; + $actionComm->datep = $now; + $actionComm->fk_element = $object->id; + $actionComm->userownerid = $user->id; + $actionComm->percentage = -1; + + switch ($action) { + case 'REGISTRATIONCERTIFICATEFR_CREATE' : + $actionComm->code = 'AC_' . strtoupper($object->element) . '_CREATE'; + $actionComm->label = $langs->trans('ObjectCreateTrigger', $langs->transnoentities(ucfirst($object->element)), $object->ref); + $actionComm->create($user); + break; + + case 'REGISTRATIONCERTIFICATEFR_MODIFY' : + $actionComm->code = 'AC_' . strtoupper($object->element) . '_MODIFY'; + $actionComm->label = $langs->trans('ObjectModifyTrigger', $langs->transnoentities(ucfirst($object->element)), $object->ref); + $actionComm->create($user); + break; + + case 'REGISTRATIONCERTIFICATEFR_DELETE' : + $actionComm->code = 'AC_ ' . strtoupper($object->element) . '_DELETE'; + $actionComm->label = $langs->trans('ObjectDeleteTrigger', $langs->transnoentities(ucfirst($object->element)), $object->ref); + $actionComm->create($user); + break; + + default: + dol_syslog("Trigger '" . $this->name . "' for action '$action' launched by " . __FILE__ . ". id=" . $object->id); + break; + } + + return 0; + } } diff --git a/dolicar.main.inc.php b/dolicar.main.inc.php index bd661d9..fc7f5be 100644 --- a/dolicar.main.inc.php +++ b/dolicar.main.inc.php @@ -1,11 +1,34 @@ + * + * 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 . + */ -$moduleName = 'DoliCar'; +/** + * \file dolicar.main.inc.php + * \ingroup dolicar + * \brief File that defines environment for Saturne common functions + */ + +$moduleName = 'DoliCar'; $moduleNameLowerCase = strtolower($moduleName); // Load Saturne environment if (file_exists(__DIR__ . '/../saturne/saturne.main.inc.php')) { - require_once __DIR__ . '/../saturne/saturne.main.inc.php'; + require_once __DIR__ . '/../saturne/saturne.main.inc.php'; +} elseif (file_exists(__DIR__ . '/../../saturne/saturne.main.inc.php')) { + require_once __DIR__ . '/../../saturne/saturne.main.inc.php'; } else { - die('Include of saturne main fails'); + die('Include of saturne main fails'); } diff --git a/dolicarindex.php b/dolicarindex.php index d4f1f16..e51161c 100644 --- a/dolicarindex.php +++ b/dolicarindex.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2021-2024 EVARISK * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,18 +16,18 @@ */ /** - * \file dolicarindex.php - * \ingroup dolicar - * \brief Home page of dolicar top menu + * \file dolicarindex.php + * \ingroup dolicar + * \brief Home page of dolicar top menu */ -// Load DoliMeet environment +// Load DoliCar environment if (file_exists('dolicar.main.inc.php')) { - require_once __DIR__ . '/dolicar.main.inc.php'; + require_once __DIR__ . '/dolicar.main.inc.php'; } elseif (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; + require_once __DIR__ . '/../dolicar.main.inc.php'; } else { - die('Include of dolicar main fails'); + die('Include of dolicar main fails'); } $showDashboard = false; diff --git a/gulpfile.js b/gulpfile.js index 26e19a1..d282715 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,33 +1,33 @@ 'use strict'; -var gulp = require('gulp'); -var sass = require('gulp-sass')(require('sass')); -var rename = require('gulp-rename'); -var uglify = require('gulp-uglify'); -var concat = require('gulp-concat'); +const gulp = require('gulp'); +const sass = require('gulp-sass')(require('sass')); +const rename = require('gulp-rename'); +const uglify = require('gulp-uglify'); +const concat = require('gulp-concat'); -var paths = { - scss_core : [ 'css/scss/**/*.scss', 'css/' ], - js_backend: [ 'js/dolicar.js', 'js/modules/*.js' ] +const paths = { + scssCore : ['css/scss/**/*.scss', 'css/'], + jsBackend: ['js/dolicar.js', 'js/modules/*.js'] }; /** Core */ -gulp.task( 'scss_core', function() { - return gulp.src( paths.scss_core[0] ) - .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)) - .pipe(rename('./dolicar.min.css')) - .pipe(gulp.dest( paths.scss_core[1])); +gulp.task('scssCore', function() { + return gulp.src(paths.scssCore[0]) + .pipe(sass({outputStyle: 'compressed'}, '').on('error', sass.logError)) + .pipe(rename('./dolicar.min.css')) + .pipe(gulp.dest(paths.scssCore[1])); }); -gulp.task('js_backend', function () { - return gulp.src(paths.js_backend) - .pipe(concat('dolicar.min.js')) - .pipe(uglify()) - .pipe(gulp.dest('./js/')) // It will create folder client.min.js +gulp.task('jsBackend', function () { + return gulp.src(paths.jsBackend) + .pipe(concat('dolicar.min.js')) + .pipe(uglify()) + .pipe(gulp.dest('./js/')); // It will create folder client.min.js }); /** Watch */ gulp.task('default', function() { - gulp.watch(paths.scss_core[0], gulp.series('scss_core')); - gulp.watch(paths.js_backend[1], gulp.series('js_backend')); + gulp.watch(paths.scssCore[0], gulp.series('scssCore')); + gulp.watch(paths.jsBackend[1], gulp.series('jsBackend')); }); diff --git a/js/dolicar.js b/js/dolicar.js index 66b8193..e5c99c1 100644 --- a/js/dolicar.js +++ b/js/dolicar.js @@ -1,97 +1,129 @@ -/* Javascript library of module DoliCar */ +/* Copyright (C) 2023-2024 EVARISK + * + * 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 . + * + * Library javascript to enable Browser notifications + */ + +/** + * \file js/dolicar.js + * \ingroup dolicar + * \brief JavaScript file for module DoliCar + */ /** * @namespace Saturne_Framework_Init * - * @author Evarisk - * @copyright 2015-2023 Evarisk + * @author Evarisk + * @copyright 2021-2024 Evarisk */ -if ( ! window.dolicar ) { - /** - * [dolicar description] - * - * @memberof Saturne_Framework_Init - * - * @type {Object} - */ - window.dolicar = {}; - - /** - * [scriptsLoaded description] - * - * @memberof Saturne_Framework_Init - * - * @type {Boolean} - */ - window.dolicar.scriptsLoaded = false; -} - -if ( ! window.dolicar.scriptsLoaded ) { - /** - * [description] - * - * @memberof Saturne_Framework_Init - * - * @returns {void} [description] - */ - window.dolicar.init = function() { - window.dolicar.load_list_script(); - }; +'use strict'; - /** - * [description] - * - * @memberof Saturne_Framework_Init - * - * @returns {void} [description] - */ - window.dolicar.load_list_script = function() { - if ( ! window.dolicar.scriptsLoaded) { - var key = undefined, slug = undefined; - for ( key in window.dolicar ) { +if (!window.dolicar) { + /** + * Init Dolicar JS + * + * @memberof Saturne_Framework_Init + * + * @since 1.0.0 + * @version 1.2.0 + * + * @type {Object} + */ + window.dolicar = {}; - if ( window.dolicar[key].init ) { - window.dolicar[key].init(); - } - - for ( slug in window.dolicar[key] ) { + /** + * Init load script dolicar JS + * + * @memberof Saturne_Framework_Init + * + * @since 1.0.0 + * @version 1.2.0 + * + * @type {Boolean} + */ + window.dolicar.scriptsLoaded = false; +} - if ( window.dolicar[key] && window.dolicar[key][slug] && window.dolicar[key][slug].init ) { - window.dolicar[key][slug].init(); - } +if (!window.dolicar.scriptsLoaded) { + /** + * Dolicar init + * + * @memberof Saturne_Framework_Init + * + * @since 1.0.0 + * @version 1.2.0 + * + * @returns {void} + */ + window.dolicar.init = function() { + window.dolicar.load_list_script(); + }; - } - } + /** + * Load script/module of dolicar + * + * @memberof Saturne_Framework_Init + * + * @since 1.0.0 + * @version 1.2.0 + * + * @returns {void} + */ + window.dolicar.load_list_script = function() { + if (!window.dolicar.scriptsLoaded) { + for (let key in window.dolicar) { + if (window.dolicar.hasOwnProperty(key) && typeof window.dolicar[key] === 'object') { + if (typeof window.dolicar[key].init === 'function') { + window.dolicar[key].init(); + } - window.dolicar.scriptsLoaded = true; - } - }; + for (let slug in window.dolicar[key]) { + if (window.dolicar[key].hasOwnProperty(slug) && typeof window.dolicar[key][slug] === 'object' && typeof window.dolicar[key][slug].init === 'function') { + window.dolicar[key][slug].init(); + } + } + } + } - /** - * [description] - * - * @memberof Saturne_Framework_Init - * - * @returns {void} [description] - */ - window.dolicar.refresh = function() { - var key = undefined; - var slug = undefined; - for ( key in window.dolicar ) { - if ( window.dolicar[key].refresh ) { - window.dolicar[key].refresh(); - } + window.dolicar.scriptsLoaded = true; + } + }; - for ( slug in window.dolicar[key] ) { + /** + * Reload script/module of dolicar + * + * @memberof Saturne_Framework_Init + * + * @returns {void} + */ + window.dolicar.refresh = function() { + for (let key in window.dolicar) { + if (window.dolicar.hasOwnProperty(key) && typeof window.dolicar[key] === 'object') { + if (typeof window.dolicar[key].refresh === 'function') { + window.dolicar[key].refresh(); + } - if ( window.dolicar[key] && window.dolicar[key][slug] && window.dolicar[key][slug].refresh ) { - window.dolicar[key][slug].refresh(); - } - } - } - }; + for (let slug in window.dolicar[key]) { + if (window.dolicar[key].hasOwnProperty(slug) && window.dolicar[key][slug] && typeof window.dolicar[key][slug].refresh === 'function') { + window.dolicar[key][slug].refresh(); + } + } + } + } + }; - $( document ).ready( window.dolicar.init ); + $(document).ready(window.dolicar.init); } - diff --git a/js/dolicar.min.js b/js/dolicar.min.js index 9bd0a61..2a94493 100644 --- a/js/dolicar.min.js +++ b/js/dolicar.min.js @@ -1 +1 @@ -window.dolicar||(window.dolicar={},window.dolicar.scriptsLoaded=!1),window.dolicar.scriptsLoaded||(window.dolicar.init=function(){window.dolicar.load_list_script()},window.dolicar.load_list_script=function(){if(!window.dolicar.scriptsLoaded){var o=void 0,t=void 0;for(o in window.dolicar)for(t in window.dolicar[o].init&&window.dolicar[o].init(),window.dolicar[o])window.dolicar[o]&&window.dolicar[o][t]&&window.dolicar[o][t].init&&window.dolicar[o][t].init();window.dolicar.scriptsLoaded=!0}},window.dolicar.refresh=function(){var o=void 0,t=void 0;for(o in window.dolicar)for(t in window.dolicar[o].refresh&&window.dolicar[o].refresh(),window.dolicar[o])window.dolicar[o]&&window.dolicar[o][t]&&window.dolicar[o][t].refresh&&window.dolicar[o][t].refresh()},$(document).ready(window.dolicar.init)),window.dolicar.registrationcertificate={},window.dolicar.registrationcertificate.init=function(){window.dolicar.registrationcertificate.event()},window.dolicar.registrationcertificate.event=function(){$(document).on("change","#fk_product",window.dolicar.registrationcertificate.actualizeBrand),$(document).on("change","#fk_product",window.dolicar.registrationcertificate.actualizeProductlot),$(document).ready(()=>{$(document).find(".field_fk_soc .butActionNew").attr("target","_blank"),$(document).find(".field_fk_project .butActionNew").attr("target","_blank")}),$("#public-vehicle-log-book-form").on("submit",function(o){o.preventDefault(),$(this).find(".public-vehicle-log-book-validate").hasClass("button-disable")||window.dolicar.registrationcertificate.createPublicVehicleLogBook()}),$(document).on("touchstart mousedown",".canvas-signature",function(){window.saturne.toolbox.removeAddButtonClass("public-vehicle-log-book-validate","button-grey button-disable","button-blue")}),$(document).on("click",".signature-erase",function(){window.saturne.toolbox.removeAddButtonClass("public-vehicle-log-book-validate","button-blue","button-grey button-disable")})},window.dolicar.registrationcertificate.actualizeBrand=function(o){var t=$('input[name="token"]').val(),i=document.getElementById("registrationcertificatefr_create")?document.getElementById("registrationcertificatefr_create"):document.getElementById("registrationcertificatefr_edit"),i=new FormData(i).get("fk_product"),e=window.saturne.toolbox.getQuerySeparator(document.URL);$.ajax({url:document.URL+e+"subaction=getProductBrand&token="+t,data:JSON.stringify({productId:i}),type:"POST",processData:!1,contentType:!1,success:function(o){$("#d1_vehicle_brand").attr("value",$(o).find(".car-brand").val()),$("#d1_vehicle_brand").prop("readonly",!0)}})},window.dolicar.registrationcertificate.actualizeProductlot=function(o){var t=$('input[name="token"]').val(),i=document.getElementById("registrationcertificatefr_create")?document.getElementById("registrationcertificatefr_create"):document.getElementById("registrationcertificatefr_edit"),i=new FormData(i),e=i.get("fk_product");let n=i.get("action");"update"==n&&(n="edit");i=window.saturne.toolbox.getQuerySeparator(document.URL);window.saturne.loader.display($(".lot-content")),$.ajax({url:document.URL+i+"action="+n+"&fk_product="+e+"&token="+t,type:"POST",processData:!1,contentType:!1,success:function(o){$(".lot-container").html($(o).find(".lot-content")),$(".wpeo-loader").removeClass("wpeo-loader")}})},window.dolicar.registrationcertificate.createPublicVehicleLogBook=function(){var o,t=window.saturne.toolbox.getToken(),i=window.saturne.toolbox.getQuerySeparator(document.URL),e=new FormData($("#public-vehicle-log-book-form")[0]);window.saturne.signature.canvas&&(o=window.saturne.signature.canvas.toDataURL(),e.append("signature",JSON.stringify(o))),$.ajax({url:document.URL+i+"action=add&token="+t,type:"POST",processData:!1,contentType:!1,data:e,success:function(){$(".public-vehicle-log-book-confirmation-close").closest(".card__confirmation").css("display","flex"),$(".public-vehicle-log-book-confirmation-close").on("click",function(){$(".public-vehicle-log-book-confirmation-close").closest(".card__confirmation").css("display","none"),window.location.reload()})},error:function(){}})}; \ No newline at end of file +window.dolicar||(window.dolicar={},window.dolicar.scriptsLoaded=!1),window.dolicar.scriptsLoaded||(window.dolicar.init=function(){window.dolicar.load_list_script()},window.dolicar.load_list_script=function(){if(!window.dolicar.scriptsLoaded){for(var o in window.dolicar)if(window.dolicar.hasOwnProperty(o)&&"object"==typeof window.dolicar[o])for(var i in"function"==typeof window.dolicar[o].init&&window.dolicar[o].init(),window.dolicar[o])window.dolicar[o].hasOwnProperty(i)&&"object"==typeof window.dolicar[o][i]&&"function"==typeof window.dolicar[o][i].init&&window.dolicar[o][i].init();window.dolicar.scriptsLoaded=!0}},window.dolicar.refresh=function(){for(var o in window.dolicar)if(window.dolicar.hasOwnProperty(o)&&"object"==typeof window.dolicar[o])for(var i in"function"==typeof window.dolicar[o].refresh&&window.dolicar[o].refresh(),window.dolicar[o])window.dolicar[o].hasOwnProperty(i)&&window.dolicar[o][i]&&"function"==typeof window.dolicar[o][i].refresh&&window.dolicar[o][i].refresh()},$(document).ready(window.dolicar.init)),window.dolicar.registrationcertificate={},window.dolicar.registrationcertificate.init=function(){window.dolicar.registrationcertificate.event()},window.dolicar.registrationcertificate.event=function(){$(document).on("change","#fk_product",window.dolicar.registrationcertificate.reloadFields),$("#public-vehicle-log-book-form").on("submit",function(o){o.preventDefault(),$(this).find(".public-vehicle-log-book-validate").hasClass("button-disable")||window.dolicar.registrationcertificate.createPublicVehicleLogBook()}),$(document).on("touchstart mousedown",".canvas-signature",function(){window.saturne.toolbox.removeAddButtonClass("public-vehicle-log-book-validate","button-grey button-disable","button-blue")}),$(document).on("click",".signature-erase",function(){window.saturne.toolbox.removeAddButtonClass("public-vehicle-log-book-validate","button-blue","button-grey button-disable")})},window.dolicar.registrationcertificate.reloadFields=function(){var o=window.saturne.toolbox.getToken(),i=window.saturne.toolbox.getQuerySeparator(document.URL),n=$(this).val();window.saturne.loader.display($(".field_fk_lot")),window.saturne.loader.display($(".field_d1_vehicle_brand")),$.ajax({url:document.URL+i+"&fk_product="+n+"&token="+o,type:"POST",processData:!1,contentType:!1,success:function(o){$(".field_fk_lot").replaceWith($(o).find(".field_fk_lot")),$(".field_d1_vehicle_brand").replaceWith($(o).find(".field_d1_vehicle_brand"))},error:function(){}})},window.dolicar.registrationcertificate.createPublicVehicleLogBook=function(){var o,i=window.saturne.toolbox.getToken(),n=window.saturne.toolbox.getQuerySeparator(document.URL),e=new FormData($("#public-vehicle-log-book-form")[0]);window.saturne.signature.canvas&&(o=window.saturne.signature.canvas.toDataURL(),e.append("signature",JSON.stringify(o))),$.ajax({url:document.URL+n+"action=add&token="+i,type:"POST",processData:!1,contentType:!1,data:e,success:function(){$(".public-vehicle-log-book-confirmation-close").closest(".card__confirmation").css("display","flex"),$(".public-vehicle-log-book-confirmation-close").on("click",function(){$(".public-vehicle-log-book-confirmation-close").closest(".card__confirmation").css("display","none"),window.location.reload()})},error:function(){}})}; \ No newline at end of file diff --git a/js/index.php b/js/index.php new file mode 100644 index 0000000..17927e6 --- /dev/null +++ b/js/index.php @@ -0,0 +1,2 @@ + + * + * 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 . + * + * Library javascript to enable Browser notifications + */ + /** - * Initialise l'objet "registrationcertificate" ainsi que la méthode "init" obligatoire pour la bibliothèque EoxiaJS. + * \file js/modules/registrationcertificate.js + * \ingroup dolicar + * \brief JavaScript Registration Certificate file for module DoliCar + */ + +'use strict'; + +/** + * Init registrationcertificate JS + * + * @memberof DoliCar_RegistrationCertificate * * @since 1.0.0 - * @version 1.0.0 + * @version 1.2.0 + * + * @type {Object} */ window.dolicar.registrationcertificate = {}; /** - * La méthode appelée automatiquement par la bibliothèque EoxiaJS. + * RegistrationCertificate init + * + * @memberof DoliCar_RegistrationCertificate * * @since 1.0.0 - * @version 1.0.0 + * @version 1.2.0 * * @return {void} */ window.dolicar.registrationcertificate.init = function() { - window.dolicar.registrationcertificate.event(); + window.dolicar.registrationcertificate.event(); }; /** - * La méthode contenant tous les événements pour le migration. + * RegistrationCertificate event * * @since 1.0.0 - * @version 9.0.0 + * @version 1.2.0 * * @return {void} */ window.dolicar.registrationcertificate.event = function() { - $( document ).on( 'change', '#fk_product', window.dolicar.registrationcertificate.actualizeBrand ); - $( document ).on( 'change', '#fk_product', window.dolicar.registrationcertificate.actualizeProductlot ); - $( document ).ready(() => { - $(document).find('.field_fk_soc .butActionNew').attr('target', '_blank') - $(document).find('.field_fk_project .butActionNew').attr('target', '_blank') - }) - + $(document).on('change', '#fk_product', window.dolicar.registrationcertificate.reloadFields); $('#public-vehicle-log-book-form').on('submit', function(event) { event.preventDefault(); if (!$(this).find('.public-vehicle-log-book-validate').hasClass('button-disable')) { @@ -50,74 +76,33 @@ window.dolicar.registrationcertificate.event = function() { }); }; - /** - * Actualize brand input + * Reload product lot selector and vehicle brand * * @since 0.0.2 - * @version 0.0.2 - * - * @return {void} - */ -window.dolicar.registrationcertificate.actualizeBrand = function( event ) { - - let token = $('input[name="token"]').val(); - - var form = document.getElementById('registrationcertificatefr_create')? document.getElementById('registrationcertificatefr_create') : document.getElementById('registrationcertificatefr_edit') - var formData = new FormData(form); - let productId = formData.get('fk_product'); - let querySeparator = window.saturne.toolbox.getQuerySeparator(document.URL) - - $.ajax({ - url: document.URL + querySeparator + 'subaction=getProductBrand&token='+token, - data: JSON.stringify({ - productId: productId, - }), - type: "POST", - processData: false, - contentType: false, - success: function ( resp ) { - $('#d1_vehicle_brand').attr('value', $(resp).find('.car-brand').val()) - $('#d1_vehicle_brand').prop("readonly", true) - }, - }); -}; - -/** - * Actualize productlot selector - * - * @since 0.0.2 - * @version 0.0.2 + * @version 1.2.0 * * @return {void} */ -window.dolicar.registrationcertificate.actualizeProductlot = function( event ) { - - let token = $('input[name="token"]').val(); - - var form = document.getElementById('registrationcertificatefr_create')? document.getElementById('registrationcertificatefr_create') : document.getElementById('registrationcertificatefr_edit') - var formData = new FormData(form); - let productId = formData.get('fk_product'); - let action = formData.get('action'); - - if (action == 'update') { - action = 'edit'; - } - - let querySeparator = window.saturne.toolbox.getQuerySeparator(document.URL) +window.dolicar.registrationcertificate.reloadFields = function() { + let token = window.saturne.toolbox.getToken(); + let querySeparator = window.saturne.toolbox.getQuerySeparator(document.URL); + let productID = $(this).val(); - window.saturne.loader.display($('.lot-content')); + window.saturne.loader.display($('.field_fk_lot')); + window.saturne.loader.display($('.field_d1_vehicle_brand')); - $.ajax({ - url: document.URL + querySeparator + 'action=' + action + '&fk_product=' + productId + '&token='+token, - type: "POST", - processData: false, - contentType: false, - success: function ( resp ) { - $('.lot-container').html($(resp).find('.lot-content')) - $('.wpeo-loader').removeClass('wpeo-loader'); - }, - }); + $.ajax({ + url: document.URL + querySeparator + '&fk_product=' + productID + '&token=' + token, + type: 'POST', + processData: false, + contentType: false, + success: function (resp) { + $('.field_fk_lot').replaceWith($(resp).find('.field_fk_lot')); + $('.field_d1_vehicle_brand').replaceWith($(resp).find('.field_d1_vehicle_brand')); + }, + error: function() {} + }); }; /** diff --git a/langs/en_US/dolicar.lang b/langs/en_US/dolicar.lang deleted file mode 100644 index 954a85b..0000000 --- a/langs/en_US/dolicar.lang +++ /dev/null @@ -1,133 +0,0 @@ -# Copyright (C) 2022 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 . - -# -# Generic -# - -# Module label 'ModuleDoliCarName' -ModuleDoliCarName = DoliCar -# Module description 'ModuleDoliCarDesc' -ModuleDoliCarDesc = DoliCar description - -# -# Admin page -# -DoliCarSetup = DoliCar setup -Settings = Settings -DoliCarSetupPage = DoliCar setup page -DOLICAR_MYPARAM1 = My param 1 -DOLICAR_MYPARAM1Tooltip = My param 1 tooltip -DOLICAR_MYPARAM2=My param 2 -DOLICAR_MYPARAM2Tooltip=My param 2 tooltip - - -# -# About page -# -About = About -DoliCarAbout = About DoliCar -DoliCarAboutPage = DoliCar about page - -# -# Sample page -# -MyPageName = My page name - -# -# Sample widget -# -MyWidget = My widget -MyWidgetDescription = My widget description - - -# -# RegistrationCertificateFr - Carte grise -# - -# Right - Droit -ReadRegistrationCertificateFr = Consulter la carte grise -CreateRegistrationCertificateFr = Créer/Modifier la carte grise -DeleteRegistrationCertificateFr = Supprimer la carte grise - -# Trigger - Déclencheur - -# Mod Numbering - Modèle de numérotation -DigiriskListingRisksPhotoDocumentNumberingModule = Modèle de numérotation des listing des risques avec photos de Digirisk -DigiriskListingRisksPhotoStandardModel = Renvoie le numéro sous la forme RLPn où n est un compteur séquentiel sans rupture et sans remise à 0. - - -# Data - Donnée -RegistrationCertificateFr = Carte grise -NewRegistrationCertificateFr = Nouvelle carte grise -ModifyRegistrationCertificateFr = Modifier la carte grise -ListRegistrationCertificateFr = Liste des cartes grises -RegistrationNumber = Numéro d'immatriculation -FirstRegistrationDate = Date de la première immatriculation -OwnerFullName = Nom et prénom du propriétaire -RegistrationAddress = Adresse du propriétaire -OwnerVehicle = Propriétaire du véhicule ? -OwnerNumber = Nombre de propriétaire -SecondOwnerName = Nom du second propriétaire -VehicleBrand = Marque du véhicule -VehicleType = Type, variante, version du véhicule -VehicleCNIT = Code National d’Identification du Type du véhicule -VehicleModel = Modèle du véhicule -VehicleSerialNumber = Numéro de série du véhicule -TechnicalPTAC = Masse en charge maximale techniquement admissible (en kg) -PTAC = Masse en charge maximale (en kg) -PTRA = Masse en charge maximale de l'ensemble (en kg) -VehicleWeight = Masse du véhicule (en kg) -VehicleEmptyWeight = Poids à vide (en kg) -ValidityPeriod = Période de validité -VehicleRegistrationDate = Date de d'immatriculation de la carte grise -VehicleCategory = Catégorie du véhicule -NationalType = Genre national -EuropeanBodyWork = Carrosserie - norme européenne -NationalBodyWork = Carrosserie - norme nationnale -TypeApprovalNumber = Numéro de réception par type -CylinderCapacity = Cylindrée (en cm3) -MaximumNetPower = Puissance nette maximale (en kW) -FuelType = Type de carburant ou source d'énergie -NationalAdministrativePower = Puissance administrative nationale ou «Chevaux fiscaux» -PowerToWeightRatio = Rapport puissance/masse (en kW/kg) -SeatingCapacity = Nombre de places assises -StationaryCapacity = Nombre de places debout autorisé -StationaryNoiseLevel = Niveau sonore à l’arrêt (en dB) -MotorSpeed = Vitesse de rotation du moteur (en min-1) -COEmission = Rejet de CO2 (en g/km) -EnvironmentalCategory = Classe environnementale -FirstTechnicallnspectionDate = Date du premier contrôle technique -RegionalTax = Taxe régionale -ProfessionalTax = Taxe professionnel -EcologicalTax = Taxe écologique -ManagementTax = Taxe de gestion -ForwardingExpensesTax = Taxe de frais d'acheminement -TotalPriceVehicleRegistration = Prix total de la carte grise -SpecificDetails1 = Mentions spécifiques 1 -SpecificDetails2 = Mentions spécifiques 2 -SpecificDetails3 = Mentions spécifiques 3 -SpecificDetails4 = Mentions spécifiques 4 - - -# -# Other -# - -# Data - Donnée -Vehicle = Véhicule -Mileage = Kilométrage -ProductLotMileageModifyTrigger = Modification du kilométrage - diff --git a/langs/en_US/index.php b/langs/en_US/index.php deleted file mode 100644 index cd6990e..0000000 --- a/langs/en_US/index.php +++ /dev/null @@ -1,2 +0,0 @@ - (par défaut 1000 km) - -# # RegistrationCertificateFr - Carte grise -# +ImmatriculationAPIConfig = Configuration de l'API immatriculationapi.com +RemainingRequests = Jetons de recherche de plaque d'immatriculation restants : %s +RegistrationCertificateFieldsConfig = Configuration des champs de la carte grise +Display = Afficher +ShowRegistrationCertificateFieldHelp = Afficher/Cacher ce champ sur la carte grise +HideObjectDetsDolicarDetails = Cacher le détail de Dolicar des lignes d'objets +HideObjectDetsDolicarDetailsDescription = Cette option permet de cacher/afficher le kilométrage, la plaque d'immatriculation et le modèle de véhicule sur les lignes des factures/propales/commandes -# Right - Droit -ReadRegistrationCertificateFr = Consulter la carte grise -CreateRegistrationCertificateFr = Créer/Modifier la carte grise -DeleteRegistrationCertificateFr = Supprimer la carte grise +# QuickCreation - Ajout rapide +QuickCreation = Ajout rapide +AutomaticContactCreation = Création automatique de contact à la création du tiers +ThirdpartyQuickCreation = Création rapide de tiers +ContactQuickCreation = Création rapide de contact +ProjectQuickCreation = Création rapide de projet -# Trigger - Déclencheur -# Mod Numbering - Modèle de numérotation -DigiriskListingRisksPhotoDocumentNumberingModule = Modèle de numérotation des listing des risques avec photos de Digirisk -DigiriskListingRisksPhotoStandardModel = Renvoie le numéro sous la forme RLPn où n est un compteur séquentiel sans rupture et sans remise à 0. +# +# RegistrationCertificateFr - Carte grise +# # Data - Donnée -RegistrationCertificateFr = Carte grise -Registrationcertificatefr = Carte grise -RegistrationCertificate = Carte grise -NewRegistrationCertificateFr = Nouvelle carte grise -ModifyRegistrationCertificateFr = Modifier la carte grise -ListRegistrationCertificateFr = Liste des cartes grises -RegistrationNumber = Numéro d'immatriculation (A) -FirstRegistrationDate = Date de la première immatriculation (B) -OwnerFullName = Nom et prénom du propriétaire (C.1) -RegistrationAddress = Adresse du propriétaire (C.3) -VehicleOwner = Propriétaire du véhicule ? (C.4a) -SecondOwnerNumber = Nombre de propriétaires (C.4.1) -SecondOwnerName = Nom du second propriétaire (C.4.1) -VehicleBrand = Marque du véhicule (D.1) -VehicleType = Type, variante, version du véhicule (D.2) -VehicleCNIT = Code National d’Identification du Type du véhicule (D.2.1) -VehicleModel = Modèle du véhicule (D.3) -VehicleSerialNumber = Numéro de série du véhicule (E) -TechnicalPTAC = Masse en charge maximale techniquement admissible (en kg) (F.1) -PTAC = Masse en charge maximale (en kg) (F.2) -PTRA = Masse en charge maximale de l'ensemble (en kg) (F.3) -VehicleWeight = Masse du véhicule (en kg) (G) -VehicleEmptyWeight = Poids à vide (en kg) (G.1) -ValidityPeriod = Période de validité (H) -VehicleRegistrationDate = Date de d'immatriculation de la carte grise (I) -VehicleCategory = Catégorie du véhicule (J) -NationalType = Genre national (J.1) -EuropeanBodyWork = Carrosserie - norme européenne (J.2) -NationalBodyWork = Carrosserie - norme nationnale (J.3) -TypeApprovalNumber = Numéro de réception par type (K) -CylinderCapacity = Cylindrée (en cm3) (P.1) -MaximumNetPower = Puissance nette maximale (en kW) (P.2) -FuelType = Type de carburant ou source d'énergie (P.3) -NationalAdministrativePower = Puissance administrative nationale ou «Chevaux fiscaux» (P.6) -PowerToWeightRatio = Rapport puissance/masse (en kW/kg) (Q) -SeatingCapacity = Nombre de places assises (S.1) -StandingCapacity = Nombre de places debout autorisé (S.2) -StationaryNoiseLevel = Niveau sonore à l’arrêt (en dB) (U.1) -MotorSpeed = Vitesse de rotation du moteur (en min-1) (U.2) -CO2Emission = Rejet de CO2 (en g/km) (V.7) -EnvironmentalCategory = Classe environnementale (V.9) -FirstTechnicalInspectionDate = Date du premier contrôle technique (X.1) -RegionalTax = Taxe régionale (Y.1) -ProfessionalTax = Taxe professionnelle (Y.2) -EcologicalTax = Taxe écologique (Y.3) -ManagementTax = Taxe de gestion (Y.4) -ForwardingExpensesTax = Taxe de frais d'acheminement (Y.5) +RegistrationCertificateFr = Carte grise +Registrationcertificatefr = Carte grise +RegistrationCertificatesFrMin = cartes grises +TheRegistrationcertificatefr = la carte grise +ListRegistrationcertificatefr = Liste des cartes grises +NewRegistrationcertificatefr = Nouvelle carte grise +ModifyRegistrationcertificatefr = Modifier la carte grise +FindLicencePlateInRepertory = Rechercher une plaque d'immatriculation + +# Fiels - Champs +RegistrationNumber = Numéro d'immatriculation (A) +FirstRegistrationDate = Date de la première immatriculation (B) +OwnerFullName = Nom et prénom du propriétaire (C.1) +RegistrationAddress = Adresse du propriétaire (C.3) +VehicleOwner = Propriétaire du véhicule ? (C.4a) +SecondOwnerNumber = Nombre de propriétaires (C.4.1) +SecondOwnerName = Nom du second propriétaire (C.4.1) +VehicleBrand = Marque du véhicule (D.1) +VehicleType = Type, variante, version du véhicule (D.2) +VehicleCNIT = Code National d’Identification du Type du véhicule (D.2.1) +VehicleModel = Modèle du véhicule (D.3) +VehicleSerialNumber = Numéro de série du véhicule (E) +TechnicalPTAC = Masse en charge maximale techniquement admissible (en kg) (F.1) +PTAC = Masse en charge maximale (en kg) (F.2) +PTRA = Masse en charge maximale de l'ensemble (en kg) (F.3) +VehicleWeight = Masse du véhicule (en kg) (G) +VehicleEmptyWeight = Poids à vide (en kg) (G.1) +ValidityPeriod = Période de validité (H) +VehicleRegistrationDate = Date de d'immatriculation de la carte grise (I) +VehicleCategory = Catégorie du véhicule (J) +NationalType = Genre national (J.1) +EuropeanBodyWork = Carrosserie - norme européenne (J.2) +NationalBodyWork = Carrosserie - norme nationnale (J.3) +TypeApprovalNumber = Numéro de réception par type (K) +CylinderCapacity = Cylindrée (en cm3) (P.1) +MaximumNetPower = Puissance nette maximale (en kW) (P.2) +FuelType = Type de carburant ou source d'énergie (P.3) +NationalAdministrativePower = Puissance administrative nationale ou «Chevaux fiscaux» (P.6) +PowerToWeightRatio = Rapport puissance/masse (en kW/kg) (Q) +SeatingCapacity = Nombre de places assises (S.1) +StandingCapacity = Nombre de places debout autorisé (S.2) +StationaryNoiseLevel = Niveau sonore à l’arrêt (en dB) (U.1) +MotorSpeed = Vitesse de rotation du moteur (en min-1) (U.2) +CO2Emission = Rejet de CO2 (en g/km) (V.7) +EnvironmentalCategory = Classe environnementale (V.9) +FirstTechnicalInspectionDate = Date du premier contrôle technique (X.1) +RegionalTax = Taxe régionale (Y.1) +ProfessionalTax = Taxe professionnelle (Y.2) +EcologicalTax = Taxe écologique (Y.3) +ManagementTax = Taxe de gestion (Y.4) +ForwardingExpensesTax = Taxe de frais d'acheminement (Y.5) TotalPriceVehicleRegistration = Prix total de la carte grise (Y.6) -SpecificDetails1 = Mentions spécifiques 1 (Z.1) -SpecificDetails2 = Mentions spécifiques 2 (Z.2) -SpecificDetails3 = Mentions spécifiques 3 (Z.3) -SpecificDetails4 = Mentions spécifiques 4 (Z.4) -RegistrationCertificateFrs = Cartes grises -ObjectsLinked = Objets liés -ObjectType = Type d'objet -Object = Objet -DefaultBrand = Marque par défaut -RegistrationCertificateShowFields = Cacher les champs de la carte grise -RegistrationCertificateShowFieldsDescription = Cette option permet de cacher/afficher une partie des champs de la carte grise -HideObjectDetsDolicarDetails = Cacher le détail de Dolicar des lignes d'objets -HideObjectDetsDolicarDetailsDescription = Cette option permet de cacher/afficher le kilométrage, la plaque d'immatriculation et le modèle de véhicule sur les lignes des factures/propales/commandes -LinkedProduct = Produit lié -LinkedProductBatch = Numéro de lot/série lié +SpecificDetails1 = Mentions spécifiques 1 (Z.1) +SpecificDetails2 = Mentions spécifiques 2 (Z.2) +SpecificDetails3 = Mentions spécifiques 3 (Z.3) +SpecificDetails4 = Mentions spécifiques 4 (Z.4) +LinkedProduct = Produit lié +DolicarBatch = Numéro de châssis + +# Extrafields - Attributs supplémentaires +VINNumber = Numéro VIN +LinkedProductBatch = Numéro de lot/série lié RegistrationCertificateMetadata = Données complémentaires de la carte grise -RegistrationCertificatesFrMin = cartes grises -TheRegistrationcertificatefr = la carte grise -FindLicencePlateInRepertory = Rechercher une plaque d'immatriculation -RegistrationCertificateFields = Champs de la carte grise -RegistrationCertificateFieldsConfig = Configuration des champs de la carte grise -ImmatriculationAPIConfig = Configuration de l'API immatriculationapi.com -APIUsername = Nom de l'utilisateur API -BadLicencePlateFormat = La plaque d'immatriculation n'est pas au bon format. Veuillez utiliser l'un des formats suivants :
XX-111-XX
XX111XX
-BadAPIUsername = Nom d'utilisateur pour l'API invalide. Vous pouvez configurer le nom d'utilisateur pour la connexion à l'API à l'adresse suivante : Configuration du nom d'utilisateur API + +# API - API +ZeroApiRequestsRemaining = Vous n'avez plus de jetons de recherche de plaque d'immatriculation. Pour en obtenir à nouveau, contactez votre administrateur. +LessThanHundredApiRequestsRemaining = Il vous reste moins de 100 jetons de recherche de plaque d'immatriculation. Pour en obtenir à nouveau, contactez votre administrateur. +LicencePlateWasAlreadyExisting = La plaque d'immatriculation existe déjà, vous avez été redirigé(e) sur sa page. BadAPIUsernameOrBadLicencePlateFormat = Mauvais nom d'utilisateur ou format de plaque d'immatriculation.
Vous pouvez configurer le nom d'utilisateur pour la connexion à l'API à l'adresse suivante : Configuration du nom d'utilisateur API
Veuillez utiliser l'un des formats suivants pour la plaque d'immatriculation :
XX-111-XX
XX111XX
-LicencePlateInformationsCharged = Les informations de la carte grise ont bien été récupérées -QuickCreation = Ajout rapide -QuickThirdPartyCreation = Ajout rapide de tiers -QuickThirdPartyCreations = ajouts rapides de tiers -QuickProjectCreation = Ajout rapide d'opportunité ou de projet -QuickProjectCreations = ajouts rapides d'opportunité ou de projet -QuickContactCreation = Ajout rapide de contact/adresse -QuickContactCreations = ajouts rapide de contact/adresse -QuickTaskCreations = ajouts rapides de tâche -QuickEventCreations = ajouts rapides d'événements +LicencePlateInformationsCharged = Les informations de la carte grise ont bien été récupérées +BadAPIUsername = Nom d'utilisateur pour l'API invalide. Vous pouvez configurer le nom d'utilisateur pour la connexion à l'API à l'adresse suivante : Configuration du nom d'utilisateur API + +# QuickCreation - Ajout rapide QuickRegistrationCertificateCreation = Ajout rapide de carte grise -LicencePlate = Plaque d'immatriculation -ShowRegistrationCertificateFieldHelp = Afficher/Cacher ce champ sur la page de création de la carte grise -LicencePlateWasAlreadyExisting = La plaque d'immatriculation existe déjà, vous avez été redirigé(e) sur sa page. -VINNumber = Numéro VIN -AddRegistrationCertificate = Créer carte grise -LinkDolicar_regcertfr = Activer le lien avec les cartes grises -LinkDolicar_regcertfrDescription = Permet la liaison entre les cartes grises et les modèles de contrôle -ZeroApiRequestsRemaining = Vous n'avez plus de jetons de recherche de plaque d'immatriculation. Pour en obtenir à nouveau, contactez votre administrateur. -LessThanHundredApiRequestsRemaining = Il vous reste moins de 100 jetons de recherche de plaque d'immatriculation. Pour en obtenir à nouveau, contactez votre administrateur. -RemainingRequests = Jetons de recherche de plaque d'immatriculation restants : %s +LicencePlate = Plaque d'immatriculation + +# DigiQuali +LinkDolicar_regcertfr = Activer le lien avec les cartes grises +LinkDolicar_regcertfrDescription = Permet la liaison entre les cartes grises et les modèles @@ -181,43 +172,17 @@ LicencePlateNotFoundInDB = La plaque d'immatriculation est introuvable dans # # Data - Donnée -Settings = Réglages -Brands = Marques -DefaultBrand = Marque par défaut -Vehicle = Véhicule -Mileage = Kilométrage -ProductLotMileageModifyTrigger = Modification du kilométrage -Car = Voiture -Truck = Poids lourd -Bicycle = Vélo -CommercialVehicle = Utilitaire -DolicarBatch = Numéro de châssis -DolicarWarehouse = Entrepôt de DoliCar -ClientVehicle = Véhicule client -DefaultVehicle = Véhicule par défaut -facture = Facture -commande = Commande -propal = Proposition commerciale -Propale = Proposition commerciale -ThirdParty = Tiers -Invoice = Facture -Order = Commande -Product = Produit -Display = Afficher -ProductBatch = Numéro de lot/série -AgendaModuleRequired = Pour assurer la traçabilité des actions dans Dolicar, assurez-vous que le module Agenda est bien activé -HowToSetupOtherModules = Pour plus de fonctionnalités sur Dolicar, vous pouvez activer de nombreux modules (Gestion des fournisseurs, des factures, etc.) sur ce lien : -ConfigMyModules = Configuration des modules -AvoidLogoProblems = Pour éviter tout problème lié aux logos dans les documents générés, veuillez vous référer à ces conseils de paramétrages : -LogoHelpLink = https://wiki.dolibarr.org/index.php?title=Premiers_paramétrages -HowToSetupIHM = Pour plus de fonctionnalités sur l'affichage de Dolibarr (Configuration de l'image de fond du Dolibarr, etc), vous pouvez vous rendre sur ce lien : -ConfigIHM = Configuration de l'affichage -DolicarSetup = Réglages de Dolicar -Settings = Réglages -LinkedObjects = Objets liés +LinkedObjects = Objets liés +ObjectType = Type d'objet +Object = Objet +Mileage = Kilométrage NoLinkedObjectsToPrint = Pas d'objets liés à afficher -QuickCreationConfiguration = Configuration de l'ajout rapide -AutomaticContactCreation = Création automatique de contact à la création du tiers -ThirdpartyQuickCreation = Création rapide de tiers -ContactQuickCreation = Création rapide de contact -ProjectQuickCreation = Création rapide de projet + + +AgendaModuleRequired = Pour assurer la traçabilité des actions dans DoliCar, assurez-vous que le module Agenda est bien activé +HowToSetupOtherModules = Pour plus de fonctionnalités sur DoliCar, vous pouvez activer de nombreux modules (Gestion des fournisseurs, des factures, etc.) sur ce lien : +ConfigMyModules = Configuration des modules +AvoidLogoProblems = Pour éviter tout problème lié aux logos dans les documents générés, veuillez vous référer à ces conseils de paramétrages : +LogoHelpLink = https://wiki.dolibarr.org/index.php?title=Premiers_paramétrages +HowToSetupIHM = Pour plus de fonctionnalités sur l'affichage de Dolibarr (Configuration de l'image de fond du Dolibarr, etc), vous pouvez vous rendre sur ce lien : +ConfigIHM = Configuration de l'affichage diff --git a/lib/dolicar.lib.php b/lib/dolicar.lib.php index fbc6781..0c616fb 100644 --- a/lib/dolicar.lib.php +++ b/lib/dolicar.lib.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ /** * \file dolicar/lib/dolicar.lib.php * \ingroup dolicar - * \brief Library files with common functions for DoliCar + * \brief Library files with common functions for Admin conf */ /** @@ -26,24 +26,29 @@ * * @return array */ -function dolicar_admin_prepare_head() +function dolicar_admin_prepare_head(): array { - global $langs, $conf; + // Global variables definitions + global $langs, $conf; - $langs->load("dolicar@dolicar"); + // Load translation files required by the page + saturne_load_langs(); - $h = 0; - $head = array(); + // Initialize values + $h = 0; + $head = []; - $head[$h][0] = dol_buildpath("/dolicar/admin/registrationcertificate.php", 1); - $head[$h][1] = '' . $langs->trans("RegistrationCertificate"); - $head[$h][2] = 'registrationcertificate'; - $h++; + $head[$h][0] = dol_buildpath('dolicar/admin/registrationcertificate.php', 1); + $head[$h][1] = $conf->browser->layout == 'classic' ? '' . $langs->trans('RegistrationCertificateFr') : ''; + $head[$h][2] = 'registrationcertificate'; + $h++; - $head[$h][0] = dol_buildpath("/dolicar/admin/quickcreation.php", 1); - $head[$h][1] = '' . $langs->trans("QuickCreation"); - $head[$h][2] = 'quickcreation'; - $h++; + if (isModEnabled('easycrm')) { + $head[$h][0] = dol_buildpath('dolicar/admin/quickcreation.php', 1); + $head[$h][1] = $conf->browser->layout == 'classic' ? '' . $langs->trans('QuickCreation') : ''; + $head[$h][2] = 'quickcreation'; + $h++; + } $head[$h][0] = dol_buildpath('dolicar/admin/publicinterface.php', 1); $head[$h][1] = $conf->browser->layout == 'classic' ? '' . $langs->trans('PublicInterface') : ''; @@ -55,19 +60,19 @@ function dolicar_admin_prepare_head() $head[$h][2] = 'pwa'; $h++; - $head[$h][0] = dol_buildpath("/dolicar/admin/setup.php", 1); - $head[$h][1] = '' . $langs->trans("ModuleSettings"); - $head[$h][2] = 'settings'; - $h++; + $head[$h][0] = dol_buildpath('dolicar/admin/setup.php', 1); + $head[$h][1] = $conf->browser->layout == 'classic' ? '' . $langs->trans('ModuleSettings') : ''; + $head[$h][2] = 'settings'; + $h++; - $head[$h][0] = dol_buildpath("/dolicar/admin/about.php", 1); - $head[$h][1] = '' . $langs->trans("About"); - $head[$h][2] = 'about'; - $h++; + $head[$h][0] = dol_buildpath('saturne/admin/about.php', 1) . '?module_name=DoliCar'; + $head[$h][1] = $conf->browser->layout == 'classic' ? '' . $langs->trans('About') : ''; + $head[$h][2] = 'about'; + $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'dolicar@dolicar'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'dolicar@dolicar'); - complete_head_from_modules($conf, $langs, null, $head, $h, 'dolicar@dolicar', 'remove'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'dolicar@dolicar', 'remove'); - return $head; + return $head; } diff --git a/lib/dolicar_functions.lib.php b/lib/dolicar_functions.lib.php index 5a7cd74..cfbc2ac 100644 --- a/lib/dolicar_functions.lib.php +++ b/lib/dolicar_functions.lib.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ -22,190 +22,66 @@ */ /** - * Prepare admin pages header + * Create default product lot * - * @return float|int + * @param int $productID Product ID + * @return int $productLotID 0 < if KO, Product lot ID created */ -function createDefaultLot($product_id) +function create_default_product_lot(int $productID): int { - global $db, $user, $conf, $langs; - - require_once __DIR__ . '/../../../product/stock/class/productlot.class.php'; - - $productlot = new Productlot($db); - $productlot->fk_product = $product_id; - $productlot->batch = dolicar_generate_random_id(); - - $lot_id = $productlot->create($user); - - if ($lot_id > 0) { - $product = new Product($db); - $product->fetch($product_id); - $product->correct_stock_batch($user, $conf->global->DOLICAR_DEFAULT_WAREHOUSE_ID, 1, 0, $langs->trans('ClientVehicle'),0,'','', $productlot->batch,'','dolicar_registrationcertificate',0); - return $lot_id; - } else { - return 0; - } - - -} - -/** - * Generate a random id - * - * @param int $car Length of string to generate key - * @return string - */ -function dolicar_generate_random_id($car = 16) -{ - $string = ""; - $chaine = "abcdefghijklmnopqrstuvwxyz123456789"; - mt_srand((double) microtime() * 1000000); - for ($i = 0; $i < $car; $i++) { - $string .= $chaine[mt_rand() % strlen($chaine)]; - } - return $string; + // Global variables definitions + global $db, $langs, $user; + + // Load Dolibarr libraries + require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php'; + require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; + + // Initialize technical objects + $productLot = new Productlot($db); + + $productLot->fk_product = $productID; + $productLot->batch = generate_random_id(); + + $productLotID = $productLot->create($user); + if ($productLotID > 0) { + $product = new Product($db); + $product->fetch($productID); + $product->correct_stock_batch($user, getDolGlobalInt('DOLICAR_DEFAULT_WAREHOUSE_ID'), 1, 0, $langs->transnoentities('ClientVehicle'),0,'','', $productLot->batch,'','dolicar_registrationcertificate',0); + return $productLotID; + } else { + return -1; + } } -function get_vehicle_brand($productId) { - global $conf, $db; - - $product = new Product($db); - $category = new Categorie($db); - $brand_name = ''; - - if (!empty($productId) && $productId > 0) { - $product->fetch($productId); - $categories = $product->getCategoriesCommon('product'); - - if (is_array($categories) && !empty($categories)) { - foreach($categories as $categoryId) { - $category->fetch($categoryId); - if ($category->fk_parent == $conf->global->DOLICAR_CAR_BRANDS_TAG) { - $brand_name = $category->label; - } - } - } - } - - return $brand_name; -} /** - * Return HTML code of the SELECT of list of all product_lots (for a third party or all). - * This also set the number of product_lotssfound into $this->num - * - * @since 9.0 Add afterSelectContactOptions hook + * Get vehicle brand name with product ID * - * @param int $socid Id ot third party or 0 for all or -1 for empty list - * @param array|int $selected Array of ID of pre-selected product_lots id - * @param string $htmlname Name of HTML field ('none' for a not editable field) - * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list - * @param string $exclude List of product_lotss id to exclude - * @param string $limitto Disable answers that are not id in this array list - * @param integer $showfunction Add function into label - * @param string $moreclass Add more class to class style - * @param bool $options_only Return options only (for ajax treatment) - * @param integer $showsoc Add company into label - * @param int $forcecombo Force to use combo box (so no ajax beautify effect) - * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/product_lotss.php',1), 'htmlname'=>'product_lotsid', 'params'=>array('add-customer-product_lots'=>'disabled'))) - * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container - * @param string $htmlid Html id to use instead of htmlname - * @param bool $multiple add [] in the name of element and add 'multiple' attribut - * @param integer $disableifempty Set tag 'disabled' on select if there is no choice - * @return int <0 if KO, Nb of product_lots in list if OK + * @param int $productID Product ID + * @return string $brandName Brand name */ -function dolicar_select_product_lots($productid = -1, $selected = '', $htmlname = 'fk_lot', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0, $exclude_already_add = '') +function get_vehicle_brand(int $productID): string { - global $conf, $langs, $hookmanager, $action, $db; - - saturne_load_langs(["companies"]); - - if (empty($htmlid)) $htmlid = $htmlname; - $num = 0; - - if ($selected === '') $selected = array(); - elseif ( ! is_array($selected)) $selected = array($selected); - $out = ''; - - if ( ! is_object($hookmanager)) { - include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($db); - } - - // We search third parties - $sql = "SELECT pl.rowid, pl.fk_product, pl.batch"; - $sql .= " FROM " . MAIN_DB_PREFIX . "product_lot as pl"; - $sql .= " LEFT OUTER JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid=pl.fk_product"; - $sql .= " WHERE pl.entity IN (" . getEntity('productlot') . ")"; - if ($productid > 0 || $productid == -1) $sql .= " AND pl.fk_product=" . $productid; - $sql .= " ORDER BY pl.batch ASC"; - - //dol_syslog(get_class($this)."::select_product_lotss", LOG_DEBUG); - $resql = $db->query($sql); - - if ($resql) { - $num = $db->num_rows($resql); - - if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only) { - include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT); - } - - if ($htmlname != 'none' && ! $options_only) { - $out .= ''; - } - - return $out; - } else { - dol_print_error($db); - return -1; - } + // Global variables definitions + global $db; + + // Initialize technical objects + $product = new Product($db); + $category = new Categorie($db); + + $brandName = ''; + + if (!empty($productID) && $productID > 0) { + $product->fetch($productID); + $categories = $product->getCategoriesCommon('product'); + if (is_array($categories) && !empty($categories)) { + foreach($categories as $categoryID) { + $category->fetch($categoryID); + if ($category->fk_parent == getDolGlobalInt('DOLICAR_CAR_BRANDS_TAG')) { + $brandName = $category->label; + } + } + } + } + + return $brandName; } diff --git a/lib/dolicar_registrationcertificatefr.lib.php b/lib/dolicar_registrationcertificatefr.lib.php index 3078040..fbb9905 100644 --- a/lib/dolicar_registrationcertificatefr.lib.php +++ b/lib/dolicar_registrationcertificatefr.lib.php @@ -1,5 +1,5 @@ * * 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 @@ -22,171 +22,50 @@ */ /** - * Prepare array of tabs for RegistrationCertificateFr + * Prepare registrationcertificatefr pages header * - * @param RegistrationCertificateFr $object RegistrationCertificateFr - * @return array Array of tabs + * @param RegistrationCertificateFr $object RegistrationCertificateFr + * @return array $head Array of tabs + * @throws Exception */ -function registrationcertificatefr_prepare_head(CommonObject $object): array +function registrationcertificatefr_prepare_head(RegistrationCertificateFr $object): array { - // Global variables definitions - global $conf, $db, $langs, $user; + // Global variables definitions + global $conf, $langs; - // Load translation files required by the page - saturne_load_langs(); + // Load translation files required by the page + saturne_load_langs(); - // Initialize values - $h = 0; - $head = []; - $objectType = $object->element; + // Initialize values + $h = 1; + $head = []; - $head[$h][0] = dol_buildpath('/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1) . '?id=' . $object->id; - $head[$h][1] = '' . $langs->trans('Card'); - $head[$h][2] = 'card'; - $h++; + $head[$h][0] = dol_buildpath('dolicar/view/registrationcertificatefr/registrationcertificatefr_linkedobjects.php', 1) . '?id=' . $object->id; + $head[$h][1] = $conf->browser->layout == 'classic' ? '' . $langs->trans('LinkedObjects') : ''; + $head[$h][2] = 'linkedobjects'; - $head[$h][0] = dol_buildpath('/dolicar/view/registrationcertificatefr/registrationcertificatefr_linkedobjects.php', 1) . '?id=' . $object->id; - $head[$h][1] = '' . $langs->trans('LinkedObjects'); - $head[$h][2] = 'linkedobjects'; - $h++; - - if ($user->rights->dolicar->$objectType->read) { - 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('/saturne/view/saturne_note.php', 1) . '?id=' . $object->id . '&module_name=DoliCar&object_type=' . $objectType; - $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->dolicar->dir_output . '/audit/' . dol_sanitizeFileName($object->ref); - $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $objectType, $object->id); - $head[$h][0] = dol_buildpath('/saturne/view/saturne_document.php', 1) . '?id=' . $object->id . '&module_name=DoliCar&object_type=' . $objectType; - $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('/saturne/view/saturne_agenda.php', 1) . '?id=' . $object->id . '&module_name=DoliCar&object_type=' . $objectType; - $head[$h][1] = '' . $langs->trans('Events'); - if (isModEnabled('agenda') && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { - $nbEvent = 0; - // Enable caching of session count actioncomm - require_once DOL_DOCUMENT_ROOT . '/core/lib/memory.lib.php'; - $cachekey = 'count_events_session_' . $object->id; - $dataretrieved = dol_getcache($cachekey); - if (!is_null($dataretrieved)) { - $nbEvent = $dataretrieved; - } else { - $sql = 'SELECT COUNT(id) as nb'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . 'actioncomm'; - $sql .= ' WHERE fk_element = ' . ((int)$object->id); - $sql .= " AND elementtype = '" . $objectType . '@dolicar' . "'"; - $resql = $db->query($sql); - if ($resql) { - $obj = $db->fetch_object($resql); - $nbEvent = $obj->nb; - } else { - dol_syslog('Failed to count actioncomm ' . $db->lasterror(), LOG_ERR); - } - dol_setcache($cachekey, $nbEvent, 120); // If setting cache fails, this is not a problem, so we do not test result. - } - $head[$h][1] .= '/'; - $head[$h][1] .= $langs->trans('Agenda'); - if ($nbEvent > 0) { - $head[$h][1] .= '' . $nbEvent . ''; - } - } - $head[$h][2] = 'agenda'; - $h++; - } - - complete_head_from_modules($conf, $langs, $object, $head, $h, $objectType . '@dolicar'); - - complete_head_from_modules($conf, $langs, $object, $head, $h, $objectType . '@dolicar', 'remove'); - - return $head; + return saturne_object_prepare_head($object, $head); } -function get_registration_certificate_fields() { - $registrationCertificateFields = [ - 'B_FIRST_REGISTRATION_DATE' => 'FirstRegistrationDate', - 'C1_OWNER_FULLNAME' => 'OwnerFullName', - 'C3_REGISTRATION_ADDRESS' => 'RegistrationAddress', - 'C4A_VEHICLE_OWNER' => 'VehicleOwner', - 'C41_SECOND_OWNER_NUMBER' => 'SecondOwnerNumber', - 'C41_SECOND_OWNER_NAME' => 'SecondOwnerName', - 'D1_VEHICLE_BRAND' => 'VehicleBrand', - 'D2_VEHICLE_TYPE' => 'VehicleType', - 'D21_VEHICLE_CNIT' => 'VehicleCNIT', - 'D3_VEHICLE_MODEL' => 'VehicleModel', - 'E_VEHICLE_SERIAL_NUMBER' => 'VehicleSerialNumber', - 'F1_TECHNICAL_PTAC' => 'TechnicalPTAC', - 'F2_PTAC' => 'PTAC', - 'F3_PTRA' => 'PTRA', - 'G_VEHICLE_WEIGHT' => 'VehicleWeight', - 'G1_VEHICLE_EMPTY_WEIGHT' => 'VehicleEmptyWeight', - 'H_VALIDITY_PERIOD' => 'ValidityPeriod', - 'I_VEHICLE_REGISTRATION_DATE' => 'VehicleRegistrationDate', - 'J_VEHICLE_CATEGORY' => 'VehicleCategory', - 'J1_NATIONAL_TYPE' => 'NationalType', - 'J2_EUROPEAN_BODYWORK' => 'EuropeanBodyWork', - 'J3_NATIONAL_BODYWORK' => 'NationalBodyWork', - 'K_TYPE_APPROVAL_NUMBER' => 'TypeApprovalNumber', - 'P1_CYLINDER_CAPACITY' => 'CylinderCapacity', - 'P2_MAXIMUM_NET_POWER' => 'MaximumNetPower', - 'P3_FUEL_TYPE' => 'FuelType', - 'P6_NATIONAL_ADMINISTRATIVE_POWER' => 'NationalAdministrativePower', - 'Q_POWER_TO_WEIGHT_RATIO' => 'PowerToWeightRatio', - 'S1_SEATING_CAPACITY' => 'SeatingCapacity', - 'S2_STANDING_CAPACITY' => 'StandingCapacity', - 'U1_STATIONARY_NOISE_LEVEL' => 'StationaryNoiseLevel', - 'U2_MOTOR_SPEED' => 'MotorSpeed', - 'V7_CO2_EMISSION' => 'CO2Emission', - 'V9_ENVIRONMENTAL_CATEGORY' => 'EnvironmentalCategory', - 'X1_FIRST_TECHNICAL_INSPECTION_DATE' => 'FirstTechnicalInspectionDate', - 'Y1_REGIONAL_TAX' => 'RegionalTax', - 'Y2_PROFESSIONAL_TAX' => 'ProfessionalTax', - 'Y3_ECOLOGICAL_TAX' => 'EcologicalTax', - 'Y4_MANAGEMENT_TAX' => 'ManagementTax', - 'Y5_FORWARDING_EXPENSES_TAX' => 'ForwardingExpensesTax', - 'Y6_TOTAL_PRICE_VEHICLE_REGISTRATION' => 'TotalPriceVehicleRegistration', - 'Z1_SPECIFIC_DETAILS' => 'SpecificDetails1', - 'Z2_SPECIFIC_DETAILS' => 'SpecificDetails2', - 'Z3_SPECIFIC_DETAILS' => 'SpecificDetails3', - 'Z4_SPECIFIC_DETAILS' => 'SpecificDetails4', - ]; - return $registrationCertificateFields; -} - -function normalize_registration_number($registrationNumber) +/** + * Normalize with regex registration number field + * + * @param string $registrationNumber Registration number + * @return string|int 0 < if KO, registration number default value or formatted + */ +function normalize_registration_number(string $registrationNumber) { - if (dol_strlen($registrationNumber) < 1) { - return 0; - } - - if (preg_match('/^[A-Z]{2}[0-9]{3}[A-Z]{2}$/', $registrationNumber)) { - $registrationNumberLetters = preg_split('/[0-9]{3}/',$registrationNumber); - $registrationNumberNumbers = preg_split('/[A-Z]{2}/',$registrationNumber); - - $registrationNumberFormatted = $registrationNumberLetters[0] . '-' . $registrationNumberNumbers[1] . '-' . $registrationNumberLetters[1]; - return $registrationNumberFormatted; - } else { - return $registrationNumber; - } + if (dol_strlen($registrationNumber) > 0) { + if (preg_match('/^[A-Z]{2}[0-9]{3}[A-Z]{2}$/', $registrationNumber)) { + $registrationNumberLetters = preg_split('/[0-9]{3}/', $registrationNumber); + $registrationNumberNumbers = preg_split('/[A-Z]{2}/', $registrationNumber); + + return $registrationNumberLetters[0] . '-' . $registrationNumberNumbers[1] . '-' . $registrationNumberLetters[1]; + } else { + return $registrationNumber; + } + } else { + return -1; + } } diff --git a/sql/data.sql b/sql/data.sql deleted file mode 100644 index e69de29..0000000 diff --git a/sql/llx_dolicar_registrationcertificatefr.key.sql b/sql/llx_dolicar_registrationcertificatefr.key.sql index ced5d1e..b9851df 100644 --- a/sql/llx_dolicar_registrationcertificatefr.key.sql +++ b/sql/llx_dolicar_registrationcertificatefr.key.sql @@ -1,4 +1,4 @@ --- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2022-2024 EVARISK -- -- 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 @@ -13,19 +13,12 @@ -- 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_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_rowid (rowid); ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_ref (ref); -ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_fk_soc (fk_soc); ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_status (status); -ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_fk_project (fk_project); +ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_fk_product (fk_product); ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_fk_lot (fk_lot); -ALTER TABLE llx_dolicar_registrationcertificatefr ADD UNIQUE uk_registrationcertificate_ref (ref, entity); - --- END MODULEBUILDER INDEXES - ---ALTER TABLE llx_dolicar_registrationcertificatefr ADD UNIQUE INDEX uk_dolicar_registrationcertificatefr_fieldxy(fieldx, fieldy); - ---ALTER TABLE llx_dolicar_registrationcertificatefr ADD CONSTRAINT llx_dolicar_registrationcertificatefr_fk_field FOREIGN KEY (fk_field) REFERENCES llx_dolicar_myotherobject(rowid); - +ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_fk_soc (fk_soc); +ALTER TABLE llx_dolicar_registrationcertificatefr ADD INDEX idx_dolicar_registrationcertificatefr_fk_project (fk_project); +ALTER TABLE llx_dolicar_registrationcertificatefr ADD UNIQUE INDEX uk_registrationcertificate_ref (ref, entity); +ALTER TABLE llx_dolicar_registrationcertificatefr ADD CONSTRAINT llx_dolicar_registrationcertificatefr_fk_user_creat FOREIGN KEY (fk_user_creat) REFERENCES llx_user(rowid); diff --git a/sql/llx_dolicar_registrationcertificatefr.sql b/sql/llx_dolicar_registrationcertificatefr.sql index b74087a..cdd2916 100644 --- a/sql/llx_dolicar_registrationcertificatefr.sql +++ b/sql/llx_dolicar_registrationcertificatefr.sql @@ -1,4 +1,4 @@ --- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2022-2024 EVARISK -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by @@ -15,67 +15,65 @@ CREATE TABLE llx_dolicar_registrationcertificatefr( - -- BEGIN MODULEBUILDER FIELDS - rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, - ref varchar(128) NOT NULL, - fk_soc integer, - date_creation datetime NOT NULL, - tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - fk_user_creat integer NOT NULL, - fk_user_modif integer, - entity integer DEFAULT 1, - import_key varchar(14), - status integer NOT NULL DEFAULT 1, - ref_ext varchar(128), - a_registration_number varchar(128) NOT NULL, - b_first_registration_date datetime, - c1_owner_fullname varchar(255), - c3_registration_address text, - c4a_vehicle_owner boolean, - c41_second_owner_number integer, - c41_second_owner_name varchar(128), - d1_vehicle_brand varchar(128), - d2_vehicle_type varchar(128), - d21_vehicle_cnit varchar(128), - d3_vehicle_model varchar(128), - e_vehicle_serial_number varchar(128), - f1_technical_ptac integer, - f2_ptac integer, - f3_ptra integer, - g_vehicle_weight integer, - g1_vehicle_empty_weight integer, - h_validity_period varchar(128), - i_vehicle_registration_date datetime, - j_vehicle_category varchar(128), - j1_national_type varchar(128), - j2_european_bodywork varchar(128), - j3_national_bodywork varchar(128), - k_type_approval_number varchar(128), - p1_cylinder_capacity integer, - p2_maximum_net_power integer, - p3_fuel_type varchar(128), - p6_national_administrative_power integer, - q_power_to_weight_ratio integer, - s1_seating_capacity integer, - s2_standing_capacity integer, - u1_stationary_noise_level integer, - u2_motor_speed integer, - v7_co2_emission integer, - v9_environmental_category varchar(128), - x1_first_technical_inspection_date datetime, - y1_regional_tax double(24,8), - y2_professional_tax double(24,8), - y3_ecological_tax double(24,8), - y4_management_tax double(24,8), - y5_forwarding_expenses_tax double(24,8), - y6_total_price_vehicle_registration double(24,8), - z1_specific_details text, - z2_specific_details text, - z3_specific_details text, - z4_specific_details text, - fk_product integer, - fk_project integer, - fk_lot integer, - json longtext - -- END MODULEBUILDER FIELDS + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + ref varchar(128) NOT NULL, + ref_ext varchar(128), + entity integer DEFAULT 1 NOT NULL, + date_creation datetime NOT NULL, + tms timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + import_key varchar(14), + status integer NOT NULL DEFAULT 1, + a_registration_number varchar(128) NOT NULL, + b_first_registration_date datetime, + c1_owner_fullname varchar(255), + c3_registration_address text, + c4a_vehicle_owner boolean, + c41_second_owner_number integer, + c41_second_owner_name varchar(128), + d1_vehicle_brand varchar(128), + d2_vehicle_type varchar(128), + d21_vehicle_cnit varchar(128), + d3_vehicle_model varchar(128), + e_vehicle_serial_number varchar(128), + f1_technical_ptac integer, + f2_ptac integer, + f3_ptra integer, + g_vehicle_weight integer, + g1_vehicle_empty_weight integer, + h_validity_period varchar(128), + i_vehicle_registration_date datetime, + j_vehicle_category varchar(128), + j1_national_type varchar(128), + j2_european_bodywork varchar(128), + j3_national_bodywork varchar(128), + k_type_approval_number varchar(128), + p1_cylinder_capacity integer, + p2_maximum_net_power integer, + p3_fuel_type varchar(128), + p6_national_administrative_power integer, + q_power_to_weight_ratio integer, + s1_seating_capacity integer, + s2_standing_capacity integer, + u1_stationary_noise_level integer, + u2_motor_speed integer, + v7_co2_emission integer, + v9_environmental_category varchar(128), + x1_first_technical_inspection_date datetime, + y1_regional_tax double(24,8), + y2_professional_tax double(24,8), + y3_ecological_tax double(24,8), + y4_management_tax double(24,8), + y5_forwarding_expenses_tax double(24,8), + y6_total_price_vehicle_registration double(24,8), + z1_specific_details text, + z2_specific_details text, + z3_specific_details text, + z4_specific_details text, + json longtext, + fk_product integer, + fk_lot integer, + fk_soc integer, + fk_project integer, + fk_user_creat integer NOT NULL, + fk_user_modif integer ) ENGINE=innodb; diff --git a/sql/llx_dolicar_registrationcertificatefr_extrafields.key.sql b/sql/llx_dolicar_registrationcertificatefr_extrafields.key.sql index a592347..a5fac16 100644 --- a/sql/llx_dolicar_registrationcertificatefr_extrafields.key.sql +++ b/sql/llx_dolicar_registrationcertificatefr_extrafields.key.sql @@ -1,8 +1,8 @@ --- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2022-2024 EVARISK -- --- This program is free software; you can redistribute it and/or modify +-- 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 +-- 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, @@ -11,9 +11,7 @@ -- 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/. +-- along with this program. If not, see https://www.gnu.org/licenses/. - --- BEGIN MODULEBUILDER INDEXES +ALTER TABLE llx_dolicar_registrationcertificatefr_extrafields ADD INDEX idx_registrationcertificatefr_rowid (rowid); ALTER TABLE llx_dolicar_registrationcertificatefr_extrafields ADD INDEX idx_registrationcertificatefr_fk_object(fk_object); --- END MODULEBUILDER INDEXES diff --git a/sql/llx_dolicar_registrationcertificatefr_extrafields.sql b/sql/llx_dolicar_registrationcertificatefr_extrafields.sql index 58e8961..3ababfb 100644 --- a/sql/llx_dolicar_registrationcertificatefr_extrafields.sql +++ b/sql/llx_dolicar_registrationcertificatefr_extrafields.sql @@ -1,8 +1,8 @@ --- Copyright (C) ---Put here your own copyright and developer email--- +-- Copyright (C) 2022-2024 EVARISK -- --- This program is free software; you can redistribute it and/or modify +-- 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 +-- 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, @@ -11,13 +11,12 @@ -- 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/. +-- along with this program. If not, see https://www.gnu.org/licenses/. -create table llx_dolicar_registrationcertificatefr_extrafields -( - rowid integer AUTO_INCREMENT PRIMARY KEY, - tms timestamp, - fk_object integer NOT NULL, - import_key varchar(14) -- import key +create table llx_dolicar_registrationcertificatefr_extrafields( + rowid integer AUTO_INCREMENT PRIMARY KEY, + tms timestamp, + fk_object integer NOT NULL, + import_key varchar(14) ) ENGINE=innodb; diff --git a/sql/update.sql b/sql/update.sql index d0d29ef..a02d0d4 100644 --- a/sql/update.sql +++ b/sql/update.sql @@ -1,3 +1,18 @@ +-- Copyright (C) 2022-2024 EVARISK +-- +-- 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/. + ALTER TABLE `llx_dolicar_registrationcertificatefr` ADD `fk_product` integer NOT NULL AFTER `z4_specific_details`; ALTER TABLE `llx_dolicar_registrationcertificatefr` DROP `d3_vehicle_model`; ALTER TABLE `llx_dolicar_registrationcertificatefr` ADD `d3_vehicle_model` varchar(128) NULL AFTER `d21_vehicle_cnit`; diff --git a/test/index.php b/test/index.php deleted file mode 100644 index cd6990e..0000000 --- a/test/index.php +++ /dev/null @@ -1,2 +0,0 @@ - - * Copyright (C) 2022 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 test/phpunit/DoliCarFunctionalTest.php - * \ingroup dolicar - * \brief Example Selenium test. - * - * Put detailed description here. - */ - -namespace test\functional; - -use PHPUnit_Extensions_Selenium2TestCase_WebDriverException; - -/** - * Class DoliCarFunctionalTest - * - * Requires chromedriver for Google Chrome - * Requires geckodriver for Mozilla Firefox - * - * @fixme Firefox (Geckodriver/Marionette) support - * @todo Opera linux support - * @todo Windows support (IE, Google Chrome, Mozilla Firefox, Safari) - * @todo OSX support (Safari, Google Chrome, Mozilla Firefox) - * - * @package Testdolicar - */ -class DoliCarFunctionalTest extends \PHPUnit_Extensions_Selenium2TestCase -{ - // TODO: move to a global configuration file? - /** @var string Base URL of the webserver under test */ - protected static $base_url = 'http://dev.zenfusion.fr'; - /** - * @var string Dolibarr admin username - * @see authenticate - */ - protected static $dol_admin_user = 'admin'; - /** - * @var string Dolibarr admin password - * @see authenticate - */ - protected static $dol_admin_pass = 'admin'; - /** @var int Dolibarr module ID */ - private static $module_id = 500000; // TODO: autodetect? - - /** @var array Browsers to test with */ - public static $browsers = array( - array( - 'browser' => 'Google Chrome on Linux', - 'browserName' => 'chrome', - 'sessionStrategy' => 'shared', - 'desiredCapabilities' => array() - ), - // Geckodriver does not keep the session at the moment?! - // XPath selectors also don't seem to work - //array( - // 'browser' => 'Mozilla Firefox on Linux', - // 'browserName' => 'firefox', - // 'sessionStrategy' => 'shared', - // 'desiredCapabilities' => array( - // 'marionette' => true, - // ), - //) - ); - - /** - * Helper function to select links by href - * - * @param string $value Href - * @return mixed Helper string - */ - protected function byHref($value) - { - $anchor = null; - $anchors = $this->elements($this->using('tag name')->value('a')); - foreach ($anchors as $anchor) { - if (strstr($anchor->attribute('href'), $value)) { - break; - } - } - return $anchor; - } - - /** - * Global test setup - * @return void - */ - public static function setUpBeforeClass() - { - } - - /** - * Unit test setup - * @return void - */ - public function setUp() - { - $this->setSeleniumServerRequestsTimeout(3600); - $this->setBrowserUrl(self::$base_url); - } - - /** - * Verify pre conditions - * @return void - */ - protected function assertPreConditions() - { - } - - /** - * Handle Dolibarr authentication - * @return void - */ - private function authenticate() - { - try { - if ($this->byId('login')) { - $login = $this->byId('username'); - $login->clear(); - $login->value('admin'); - $password = $this->byId('password'); - $password->clear(); - $password->value('admin'); - $this->byId('login')->submit(); - } - } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) { - // Login does not exist. Assume we are already authenticated - } - } - - /** - * Test enabling developer mode - * @return bool - */ - public function testEnableDeveloperMode() - { - $this->url('/admin/const.php'); - $this->authenticate(); - $main_features_level_path = '//input[@value="MAIN_FEATURES_LEVEL"]/following::input[@type="text"]'; - $main_features_level = $this->byXPath($main_features_level_path); - $main_features_level->clear(); - $main_features_level->value('2'); - $this->byName('update')->click(); - // Page reloaded, we need a new XPath - $main_features_level = $this->byXPath($main_features_level_path); - return $this->assertEquals('2', $main_features_level->value(), "MAIN_FEATURES_LEVEL value is 2"); - } - - /** - * Test enabling the module - * - * @depends testEnableDeveloperMode - * @return bool - */ - public function testModuleEnabled() - { - $this->url('/admin/modules.php'); - $this->authenticate(); - $module_status_image_path = '//a[contains(@href, "'.self::$module_id.'")]/img'; - $module_status_image = $this->byXPath($module_status_image_path); - if (strstr($module_status_image->attribute('src'), 'switch_off.png')) { - // Enable the module - $this->byHref('modDoliCar')->click(); - } else { - // Disable the module - $this->byHref('modDoliCar')->click(); - // Reenable the module - $this->byHref('modDoliCar')->click(); - } - // Page reloaded, we need a new Xpath - $module_status_image = $this->byXPath($module_status_image_path); - return $this->assertContains('switch_on.png', $module_status_image->attribute('src'), "Module enabled"); - } - - /** - * Test access to the configuration page - * - * @depends testModuleEnabled - * @return bool - */ - public function testConfigurationPage() - { - $this->url('/custom/dolicar/admin/setup.php'); - $this->authenticate(); - return $this->assertContains('dolicar/admin/setup.php', $this->url(), 'Configuration page'); - } - - /** - * Test access to the about page - * - * @depends testConfigurationPage - * @return bool - */ - public function testAboutPage() - { - $this->url('/custom/dolicar/admin/about.php'); - $this->authenticate(); - return $this->assertContains('dolicar/admin/about.php', $this->url(), 'About page'); - } - - /** - * Test about page is rendering Markdown - * - * @depends testAboutPage - * @return bool - */ - public function testAboutPageRendersMarkdownReadme() - { - $this->url('/custom/dolicar/admin/about.php'); - $this->authenticate(); - return $this->assertEquals( - 'Dolibarr Module Template (aka My Module)', - $this->byTag('h1')->text(), - "Readme title" - ); - } - - /** - * Test box is properly declared - * - * @depends testModuleEnabled - * @return bool - */ - public function testBoxDeclared() - { - $this->url('/admin/boxes.php'); - $this->authenticate(); - return $this->assertContains('dolicarwidget1', $this->source(), "Box enabled"); - } - - /** - * Test trigger is properly enabled - * - * @depends testModuleEnabled - * @return bool - */ - public function testTriggerDeclared() - { - $this->url('/admin/triggers.php'); - $this->authenticate(); - return $this->assertContains( - 'interface_99_modDoliCar_DoliCarTriggers.class.php', - $this->byTag('body')->text(), - "Trigger declared" - ); - } - - /** - * Test trigger is properly declared - * - * @depends testTriggerDeclared - * @return bool - */ - public function testTriggerEnabled() - { - $this->url('/admin/triggers.php'); - $this->authenticate(); - return $this->assertContains( - 'tick.png', - $this->byXPath('//td[text()="interface_99_modDoliCar_MyTrigger.class.php"]/following::img')->attribute('src'), - "Trigger enabled" - ); - } - - /** - * Verify post conditions - * @return void - */ - protected function assertPostConditions() - { - } - - /** - * Unit test teardown - * @return void - */ - public function tearDown() - { - } - - /** - * Global test teardown - * @return void - */ - public static function tearDownAfterClass() - { - } -} diff --git a/test/phpunit/index.php b/test/phpunit/index.php deleted file mode 100644 index cd6990e..0000000 --- a/test/phpunit/index.php +++ /dev/null @@ -1,2 +0,0 @@ - +/* Copyright (C) 2023-2024 EVARISK * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,37 +16,37 @@ */ /** - * \file view/quickcreation.php - * \ingroup dolicar - * \brief Page to quick creation project/task + * \file view/quickcreation.php + * \ingroup dolicar + * \brief Page to quick creation registrationcertificatefr/thirdparty/contact/project/task */ -// Load EasyCRM environment +// Load DoliCar environment if (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; + require_once __DIR__ . '/../dolicar.main.inc.php'; } elseif (file_exists('../../dolicar.main.inc.php')) { - require_once __DIR__ . '/../../dolicar.main.inc.php'; + require_once __DIR__ . '/../../dolicar.main.inc.php'; } else { - die('Include of dolicar main fails'); + die('Include of dolicar main fails'); } -// Libraries +// Load Dolibarr libraries if (isModEnabled('project')) { - require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; - - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; - require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php'; + require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php'; } if (isModEnabled('societe')) { - require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; + require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; } if (isModEnabled('fckeditor')) { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; } if (isModEnabled('categorie')) { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; } +// Load DoliCar libraries require_once __DIR__ . '/../../class/registrationcertificatefr.class.php'; // Global variables definitions @@ -65,24 +65,24 @@ $object = new RegistrationCertificateFr($db); if (isModEnabled('project')) { - $project = new Project($db); - $task = new Task($db); + $project = new Project($db); + $task = new Task($db); } if (isModEnabled('categorie')) { - $category = new Categorie($db); + $category = new Categorie($db); } if (isModEnabled('societe')) { - $thirdparty = new Societe($db); - $contact = new Contact($db); + $thirdparty = new Societe($db); + $contact = new Contact($db); } // Initialize view objects $form = new Form($db); if (isModEnabled('project')) { - $formproject = new FormProjets($db); + $formproject = new FormProjets($db); } if (isModEnabled('societe')) { - $formcompany = new FormCompany($db); + $formcompany = new FormCompany($db); } $hookmanager->initHooks(['dolicar_quickcreation']); // Note that conf->hooks_modules contains array @@ -90,29 +90,29 @@ $date_start = dol_mktime(0, 0, 0, GETPOST('projectstartmonth', 'int'), GETPOST('projectstartday', 'int'), GETPOST('projectstartyear', 'int')); // Security check - Protection if external user -$permissiontoread = $user->rights->dolicar->read && isModEnabled('easycrm'); +$permissionToRead = $user->rights->dolicar->read && isModEnabled('easycrm'); $permissiontoaddproject = $user->rights->projet->creer; $permissiontoaddthirdparty = $user->rights->societe->creer; $permissiontoaddcontact = $user->rights->societe->contact->creer; -saturne_check_access($permissiontoread); +saturne_check_access($permissionToRead); /* * Actions */ $parameters = []; -$reshook = $hookmanager->executeHooks('doActions', $parameters, $project, $action); // Note that $action and $project may have been modified by some hooks -if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +$resHook = $hookmanager->executeHooks('doActions', $parameters, $project, $action); // Note that $action and $project may have been modified by some hooks +if ($resHook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); } -if (empty($reshook)) { +if (empty($resHook)) { $error = 0; - if ($cancel) { - header('Location: ' . dol_buildpath('/dolicar/dolicarindex.php', 1)); - exit; - } + if ($cancel) { + header('Location: ' . dol_buildpath('dolicar/dolicarindex.php', 1)); + exit; + } if ($action == 'add') { if (!$error) { @@ -283,25 +283,24 @@ * View */ -$title = $langs->trans('QuickCreation'); -$help_url = 'FR:Module_EasyCRM'; +$title = $langs->trans('QuickCreation'); +$helpUrl = 'FR:Module_DoliCar'; -saturne_header(0, '', $title, $help_url); +saturne_header(0, '', $title, $helpUrl); if (empty($permissiontoaddthirdparty) && empty($permissiontoaddcontact) && empty($permissiontoaddproject)) { - accessforbidden($langs->trans('NotEnoughPermissions'), 0); - exit; + accessforbidden($langs->trans('NotEnoughPermissions'), 0); + exit; } print '
'; print ''; print ''; if ($backtopage) { - print ''; + print ''; } -//Ajouter le code carte grise -print load_fiche_titre($langs->trans("QuickRegistrationCertificateCreation"), '', 'object_'.$object->picto); +print load_fiche_titre($langs->trans('QuickRegistrationCertificateCreation'), '', 'object_' . $object->picto); print '
'; print ''; @@ -311,24 +310,21 @@ print ''; print ''; -print ''; -print ''; -print ''; +print ''; print '
'; print ''; -print '
'; -print '
'; print '
'; +print '
'; -if ($conf->global->DOLICAR_THIRDPARTY_QUICK_CREATION) { - require_once __DIR__ . '/../../../easycrm/core/tpl/easycrm_thirdparty_quickcreation.tpl.php'; +if (getDolGlobalInt('DOLICAR_THIRDPARTY_QUICK_CREATION')) { + require_once __DIR__ . '/../../../easycrm/core/tpl/easycrm_thirdparty_quickcreation.tpl.php'; } -if ($conf->global->DOLICAR_CONTACT_QUICK_CREATION) { - require_once __DIR__ . '/../../../easycrm/core/tpl/easycrm_contact_quickcreation.tpl.php'; +if (getDolGlobalInt('DOLICAR_CONTACT_QUICK_CREATION')) { + require_once __DIR__ . '/../../../easycrm/core/tpl/easycrm_contact_quickcreation.tpl.php'; } -if ($conf->global->DOLICAR_PROJECT_QUICK_CREATION) { - require_once __DIR__ . '/../../../easycrm/core/tpl/easycrm_project_quickcreation.tpl.php'; +if (getDolGlobalInt('DOLICAR_PROJECT_QUICK_CREATION')) { + require_once __DIR__ . '/../../../easycrm/core/tpl/easycrm_project_quickcreation.tpl.php'; } print $form->buttonsSaveCancel('Create'); diff --git a/view/registrationcertificatefr/registrationcertificatefr_card.php b/view/registrationcertificatefr/registrationcertificatefr_card.php index 0b7d407..38f184a 100644 --- a/view/registrationcertificatefr/registrationcertificatefr_card.php +++ b/view/registrationcertificatefr/registrationcertificatefr_card.php @@ -1,6 +1,5 @@ - * Copyright (C) ---Put here your own copyright and developer email--- +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ -17,20 +16,21 @@ */ /** - * \file registrationcertificatefr_card.php - * \ingroup dolicar - * \brief Page to create/edit/view registrationcertificatefr + * \file registrationcertificatefr_card.php + * \ingroup dolicar + * \brief Page to create/edit/view registrationcertificatefr */ // Load DoliCar environment if (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; + require_once __DIR__ . '/../dolicar.main.inc.php'; } elseif (file_exists('../../dolicar.main.inc.php')) { - require_once __DIR__ . '/../../dolicar.main.inc.php'; + require_once __DIR__ . '/../../dolicar.main.inc.php'; } else { - die('Include of dolicar main fails'); + die('Include of dolicar main fails'); } +// Load Dolibarr libraries 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'; @@ -38,25 +38,25 @@ require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +// Load DoliCar libraries require_once __DIR__ . '/../../class/registrationcertificatefr.class.php'; require_once __DIR__ . '/../../lib/dolicar_registrationcertificatefr.lib.php'; -global $conf, $langs, $user, $db, $hookmanager; +// Global variables definitions +global $conf, $db, $hookmanager, $langs, $user; // Load translation files required by the page -saturne_load_langs(['other', 'propal', 'interventions']); +saturne_load_langs(['propal', 'interventions']); // Get parameters $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); $subaction = GETPOST('subaction', 'aZ09'); -$confirm = GETPOST('confirm', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'registrationcertificatefrcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); -$lineid = GETPOST('lineid', 'int'); // Initialize technical objects $object = new RegistrationCertificateFr($db); @@ -65,8 +65,10 @@ $category = new Categorie($db); $extrafields = new ExtraFields($db); -$diroutputmassaction = $conf->dolicar->dir_output.'/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('registrationcertificatefrcard', 'globalcard')); // Note that conf->hooks_modules contains array +// Initialize view objects +$form = new Form($db); + +$hookmanager->initHooks(['registrationcertificatefrcard', 'globalcard']); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); @@ -74,396 +76,282 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Initialize array of search criterias -$search_all = GETPOST("search_all", 'alpha'); -$search = array(); +$searchAll = GETPOST('search_all', 'alpha'); +$search = []; foreach ($object->fields as $key => $val) { - if (GETPOST('search_'.$key, 'alpha')) { - $search[$key] = GETPOST('search_'.$key, 'alpha'); - } + if (GETPOST('search_' . $key, 'alpha')) { + $search[$key] = GETPOST('search_' . $key, 'alpha'); + } } if (empty($action) && empty($id) && empty($ref)) { - $action = 'view'; + $action = 'view'; } // Load object -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. +require_once DOL_DOCUMENT_ROOT . '/core/actions_fetchobject.inc.php'; // Must be included, not include_once -$permissiontoread = $user->rights->dolicar->registrationcertificatefr->read; +// Security check - Protection if external user +$permissionToRead = $user->rights->dolicar->registrationcertificatefr->read; $permissiontoadd = $user->rights->dolicar->registrationcertificatefr->write; $permissiontodelete = $user->rights->dolicar->registrationcertificatefr->delete; - -// Security check - Protection if external user -saturne_check_access($permissiontoread); - -$upload_dir = $conf->dolicar->multidir_output[isset($object->entity) ? $object->entity : 1].'/registrationcertificatefr'; +saturne_check_access($permissionToRead); /* * Actions */ -$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'); +$parameters = []; +$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('/dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php', 1); - - if (empty($backtopage) || ($cancel && empty($id))) { - if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create' && $action != 'getRegistrationCertificateData') || $cancel)) { - $backtopage = $backurlforlist; - } else { - $backtopage = dol_buildpath('/dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1).'?id='.((!empty($id) && $id > 0) ? $id : '__ID__' . '&a_registration_number=' . GETPOST('a_registration_number')); - } - } - } - - if ($subaction == 'getProductBrand') { - $data = json_decode(file_get_contents('php://input'), true); - - $productId = $data['productId']; - - $brand_name = get_vehicle_brand($productId); - } - - if ($action == 'add') { - $registrationNumber = strtoupper(GETPOST('a_registration_number')); - } +if (empty($resHook)) { + $error = 0; - if ($action == 'getRegistrationCertificateData') { - require_once __DIR__ . '/../../core/tpl/dolicar_registrationcertificatefr_immatriculation_api_fetch_action.tpl.php'; - } + $backurlforlist = dol_buildpath('dolicar/view/registrationcertificatefr/registrationcertificatefr_list.php', 1); + if (empty($backtopage) || ($cancel && empty($id))) { + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create' && $action != 'getRegistrationCertificateData') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('dolicar/view/registrationcertificatefr/registrationcertificatefr_card.php', 1) . '?id=' . ((!empty($id) && $id > 0) ? $id : '__ID__'); + } + } + } - $triggermodname = 'DOLICAR_REGISTRATIONCERTIFICATEFR_MODIFY'; // Name of trigger action code to execute when we modify record + if ($action == 'getRegistrationCertificateData') { + require_once __DIR__ . '/../../core/tpl/dolicar_registrationcertificatefr_immatriculation_api_fetch_action.tpl.php'; + } - // 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'; + // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen + require_once DOL_DOCUMENT_ROOT . '/core/actions_addupdatedelete.inc.php'; - if ($action == 'set_thirdparty' && $permissiontoadd) { - $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, $triggermodname); - } - if ($action == 'classin' && $permissiontoadd) { - $object->setProject(GETPOST('projectid', 'int')); - } + // Actions set_thirdparty, set_project + require_once __DIR__ . '/../../../saturne/core/tpl/actions/banner_actions.tpl.php'; } /* * View - * - * Put here all code to build page */ -$form = new Form($db); -$formfile = new FormFile($db); -$formproject = new FormProjets($db); +$title = $langs->trans(ucfirst($object->element)); +$helpUrl = 'FR:Module_DoliCar'; -$title = $langs->trans("RegistrationCertificateFr"); -$help_url = ''; -saturne_header( 0, '', $help_url); +saturne_header( 0, '', $title, $helpUrl); // Part to create if ($action == 'create') { - if (empty($permissiontoadd)) { - accessforbidden($langs->trans('NotEnoughPermissions'), 0, 1); - exit; - } + if (empty($permissiontoadd)) { + accessforbidden($langs->trans('NotEnoughPermissions'), 0); + exit; + } - print load_fiche_titre($langs->trans("NewRegistrationCertificateFr"), '', 'object_'.$object->picto); + print load_fiche_titre($langs->trans('New' . ucfirst($object->element)), '', 'object_' . $object->picto); - print '
'; - print ''; + print ''; print ''; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'; - print $langs->trans('FindLicencePlateInRepertory'); - print ''; - print ''; - print '
'; - print '
'; - print ''; - print '
'; - print ''; - print '
'; - print '
'; - - print '
'; - print ''; - print ''; - if ($backtopage) { - print ''; - } - if ($backtopageforcancel) { - print ''; - } - - print ''; - - print dol_get_fiche_head(array(), ''); - - // Set some default values - //if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue'; - - print ''."\n"; - // Common attributes - unset($object->fields['fk_lot']); - unset($object->fields['fk_product']); - unset($object->fields['a_registration_number']); - - //Registration Number - print ''; - - //Fk_product - $productPost = GETPOST('fk_product') ?: $conf->global->DOLICAR_DEFAULT_VEHICLE; - print ''; - - //Fk_lot - $productLotPost = GETPOST('fk_lot') ?: 0; - print'
' . $langs->trans('RegistrationNumber') . ''; - print ''; - print '
' . $langs->trans('LinkedProduct') . ''; - $form->select_produits($productPost, 'fk_product', '', 0, 1, -1, 2, '', '', '', '', 'SelectProductsOrServices', 0, 'maxwidth500 widthcentpercentminusxx', 1); - print ''; - print '
'; - print $langs->trans('DolicarBatch'); - print ''; - print ''; - - $productLots = saturne_fetch_all_object_type('ProductLot', '', '', 0, 0, $productPost > 0 ? ['customsql' => ' fk_product = ' . $productPost] : []); - $productLotsData = []; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'; + print $langs->trans('FindLicencePlateInRepertory'); + print ''; + print ''; + print '
'; + print '
'; + print ''; + print '
'; + print ''; + print '
'; + print '
'; + + print '
'; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(); + + print ''; + + $_POST['fk_product'] = getDolGlobalInt('DOLICAR_DEFAULT_VEHICLE'); + $object->fields['d1_vehicle_brand']['default'] = get_vehicle_brand(GETPOST('fk_product')); + + // Fk_lot + print''; - print $form::selectarray('fk_lot', $productLotsData, $productLotPost, $langs->transnoentities('SelectProductLots'), '', '', '', '', '', '','', 'maxwidth500 widthcentpercentminusx'); + // Common attributes + require_once DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; - print ''; - print ''; - print ''; + // Other attributes + require_once DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; - include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; + print '
'; + print $langs->trans('DolicarBatch'); + print ''; + $productLotsData = []; + $productLots = saturne_fetch_all_object_type('ProductLot', '', '', 0, 0, ['customsql' => 't.fk_product = ' . GETPOST('fk_product')]); if (is_array($productLots) && !empty($productLots)) { foreach ($productLots as $productLotSingle) { $productLotsData[$productLotSingle->id] = $productLotSingle->batch; } } + print img_picto('', 'lot', 'class="pictofixedwidth"') . $form::selectarray('fk_lot', $productLotsData, GETPOST('fk_lot'), $langs->transnoentities('SelectProductLots'), '', '', '', '', '', '','', 'maxwidth500 widthcentpercentminusx'); + print ''; + print '
'; - // Other attributes - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; + print dol_get_fiche_end(); - print '
'."\n"; + print $form->buttonsSaveCancel('Create'); - print dol_get_fiche_end(); + print ''; ?> - print $form->buttonsSaveCancel("Create"); + - - - '; - - //dol_set_focus('input[name="ref"]'); + $targetRow.after($rowToMove); + + trans("RegistrationCertificateFr"), '', 'object_'.$object->picto); - - print '
'; - print ''; - print ''; - print ''; - if ($backtopage) { - print ''; - } - if ($backtopageforcancel) { - print ''; - } - - print ''; - - print dol_get_fiche_head(); - - print ''."\n"; - - // Common attributes - unset($object->fields['ref']); - unset($object->fields['fk_lot']); - unset($object->fields['fk_product']); - unset($object->fields['a_registration_number']); - - //Registration Number - print ''; - - //Fk_product - $productPost = GETPOST('fk_product') ?: $object->fk_product ; - print ''; - - //Fk_lot - $productLotPost = GETPOST('fk_lot') ?: $object->fk_lot; - print'
' . $langs->trans('RegistrationNumber') . ''; - print ''; - print '
' . $langs->trans('LinkedProduct') . ''; - $form->select_produits($productPost, 'fk_product', '', 0, 1, -1, 2, '', '', '', '', 'SelectProductsOrServices', 0, 'maxwidth500 widthcentpercentminusxx', 1); - print ''; - print '
'; - print $langs->trans('DolicarBatch'); - print ''; - print ''; - - $productLots = saturne_fetch_all_object_type('ProductLot', '', '', 0, 0, $productPost > 0 ? ['customsql' => ' fk_product = ' . $productPost] : []); - $productLotsData = []; + print load_fiche_titre($langs->trans('Modify' . ucfirst($object->element)), '', 'object_' . $object->picto); + + print ''; + print ''; + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(); + + print ''; + + // Fk_lot + print''; - print $form::selectarray('fk_lot', $productLotsData, $productLotPost, $langs->transnoentities('SelectProductLots'), '', '', '', '', '', '','', 'maxwidth500 widthcentpercentminusx'); - print ''; - print ''; - print ''; + // Common attributes + require_once DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; - // Common attributes - include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; + // Other attributes + require_once DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; - // Other attributes - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; + print '
'; + print $langs->trans('DolicarBatch'); + print ''; + $productLotsData = []; + $productLots = saturne_fetch_all_object_type('ProductLot', '', '', 0, 0, ['customsql' => 't.fk_product = ' . GETPOST('fk_product') > 0 ? GETPOST('fk_product') : $object->fk_product]); if (is_array($productLots) && !empty($productLots)) { foreach ($productLots as $productLotSingle) { $productLotsData[$productLotSingle->id] = $productLotSingle->batch; } } + print img_picto('', 'lot', 'class="pictofixedwidth"') . $form::selectarray('fk_lot', $productLotsData, GETPOST('fk_lot') > 0 ? GETPOST('fk_lot') : $object->fk_lot, $langs->transnoentities('SelectProductLots'), '', '', '', '', '', '','', 'maxwidth500 widthcentpercentminusx'); + print ''; + print '
'; - ?> - - '; + print $form->buttonsSaveCancel(); - print dol_get_fiche_end(); + print ''; ?> - print $form->buttonsSaveCancel(); + + id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { - $res = $object->fetch_optionals(); - - print saturne_get_fiche_head($object, 'card', $langs->trans("RegistrationCertificateFr")); - - $formconfirm = ''; - - // Confirmation to delete - if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteRegistrationCertificateFr'), $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); - } - - // Confirmation of action xxxx - if ($action == 'xxx') { - $formquestion = array(); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); - } - - // 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 - // ------------------------------------------------------------ - - saturne_banner_tab($object); - - print '
'; - print '
'; - print '
'; - print ''."\n"; - - // Common attributes - include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; - // Other attributes. Fields from hook formObjectOptions and Extrafields. - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - - ?> - - '; - print ''; - print ''; - - print '
'; - - print dol_get_fiche_end(); - - // 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)) { - $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('Modify'); - print dolGetButtonAction($displayButton, '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&token='.newToken(), '', $permissiontoadd); - - $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('NewPropal'); - print dolGetButtonAction($displayButton, '', 'default', dol_buildpath('/comm/propal/card.php?action=create&socid=' . $object->fk_soc . '&options_registrationcertificatefr=' . $object->id, 3), '', $permissiontoadd); - - $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('NewInvoice'); - print dolGetButtonAction($displayButton, '', 'default', dol_buildpath('/compta/facture/card.php?action=create&socid=' . $object->fk_soc . '&options_registrationcertificatefr=' . $object->id, 3), '', $permissiontoadd); - - $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('NewIntervention'); - print dolGetButtonAction($displayButton, '', 'default', dol_buildpath('/fichinter/card.php?action=create&socid=' . $object->fk_soc, 3), '', $permissiontoadd); - } - print '
'."\n"; - } + saturne_get_fiche_head($object, 'card', $title); + saturne_banner_tab($object); + + $formConfirm = ''; + + // Call Hook formConfirm + $parameters = ['formConfirm' => $formConfirm]; + $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; + + print '
'; + print '
'; + print '
'; + + unset($object->fields['fk_soc']); // Hide field already shown in banner + unset($object->fields['fk_project']); // Hide field already shown in banner + + // Common attributes + require_once DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + + // Other attributes. Fields from hook formObjectOptions and Extrafields + require_once DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
'; + print '
'; + print '
'; + + print '
'; + + print dol_get_fiche_end(); + + // Buttons for actions + if ($action != 'presend') { + print '
'; + $parameters = []; + $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)) { + $displayButton = $conf->browser->layout == 'classic' ? '' . $langs->trans('Modify') : ''; + print dolGetButtonAction($displayButton, '', 'default', $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&action=edit&token=' . newToken(), '', $permissiontoadd); + + $displayButton = $conf->browser->layout == 'classic' ? '' . $langs->trans('NewPropal') : ''; + print dolGetButtonAction($displayButton, '', 'default', dol_buildpath('comm/propal/card.php?action=create&socid=' . $object->fk_soc . '&options_registrationcertificatefr=' . $object->id, 3), '', $permissiontoadd); + + $displayButton = $conf->browser->layout == 'classic' ? '' . ' ' . $langs->trans('NewInvoice') : ''; + print dolGetButtonAction($displayButton, '', 'default', dol_buildpath('compta/facture/card.php?action=create&socid=' . $object->fk_soc . '&options_registrationcertificatefr=' . $object->id, 3), '', $permissiontoadd); + + $displayButton = $conf->browser->layout == 'classic' ? '' . ' ' . $langs->trans('NewIntervention') : ''; + print dolGetButtonAction($displayButton, '', 'default', dol_buildpath('fichinter/card.php?action=create&socid=' . $object->fk_soc, 3), '', $permissiontoadd); + } + print '
'; + } } // End of page diff --git a/view/registrationcertificatefr/registrationcertificatefr_linkedobjects.php b/view/registrationcertificatefr/registrationcertificatefr_linkedobjects.php index ebfbc66..413621f 100644 --- a/view/registrationcertificatefr/registrationcertificatefr_linkedobjects.php +++ b/view/registrationcertificatefr/registrationcertificatefr_linkedobjects.php @@ -1,6 +1,5 @@ - * Copyright (C) ---Put here your own copyright and developer email--- +/* Copyright (C) 2022-2024 EVARISK * * 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 @@ -17,103 +16,64 @@ */ /** - * \file registrationcertificatefr_card.php - * \ingroup dolicar - * \brief Page to create/edit/view registrationcertificatefr + * \file registrationcertificatefr_linkedobjects.php + * \ingroup dolicar + * \brief Page to view registrationcertificatefr linked objects */ // Load DoliCar environment if (file_exists('../dolicar.main.inc.php')) { - require_once __DIR__ . '/../dolicar.main.inc.php'; + require_once __DIR__ . '/../dolicar.main.inc.php'; } elseif (file_exists('../../dolicar.main.inc.php')) { - require_once __DIR__ . '/../../dolicar.main.inc.php'; + require_once __DIR__ . '/../../dolicar.main.inc.php'; } else { - die('Include of dolicar main fails'); + die('Include of dolicar main fails'); } -require_once DOL_DOCUMENT_ROOT . '/product/stock/class/productlot.class.php'; -require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - -require_once __DIR__ . '/../../class/registrationcertificatefr.class.php'; +// Load DoliCar libraries require_once __DIR__ . '/../../lib/dolicar_registrationcertificatefr.lib.php'; +require_once __DIR__ . '/../../class/registrationcertificatefr.class.php'; -global $conf, $langs, $user, $db, $hookmanager; +// Global variables definitions +global $db, $langs, $user; // Load translation files required by the page -saturne_load_langs(['other']); +saturne_load_langs(); // Get parameters -$id = GETPOST('id', 'int'); -$ref = GETPOST('ref', 'alpha'); -$action = GETPOST('action', 'aZ09'); -$subaction = GETPOST('subaction', 'aZ09'); -$confirm = GETPOST('confirm', 'alpha'); -$cancel = GETPOST('cancel', 'aZ09'); -$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'registrationcertificatefrcard'; // To manage different context of search -$backtopage = GETPOST('backtopage', 'alpha'); -$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); -$lineid = GETPOST('lineid', 'int'); +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); // Initialize technical objects -$object = new RegistrationCertificateFr($db); -$product = new Product($db); -$productLot = new Productlot($db); -$category = new Categorie($db); -$extrafields = new ExtraFields($db); - -$diroutputmassaction = $conf->dolicar->dir_output.'/temp/massgeneration/'.$user->id; -$hookmanager->initHooks(array('registrationcertificatefrcard', '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 = 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'; -} +$object = new RegistrationCertificateFr($db); // Load object -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. - -$permissiontoread = $user->rights->dolicar->registrationcertificatefr->read; -$permissiontoadd = $user->rights->dolicar->registrationcertificatefr->write; -$permissiontodelete = $user->rights->dolicar->registrationcertificatefr->delete; +require_once DOL_DOCUMENT_ROOT . '/core/actions_fetchobject.inc.php'; // Must be included, not include_once // Security check - Protection if external user -saturne_check_access($permissiontoread); - -$upload_dir = $conf->dolicar->multidir_output[isset($object->entity) ? $object->entity : 1].'/registrationcertificatefr'; - -/* - * Actions - */ +$permissionToRead = $user->rights->dolicar->registrationcertificatefr->read; +saturne_check_access($permissionToRead); /* * View - * - * Put here all code to build page */ -$title = $langs->trans("RegistrationCertificateFrLinkedObjects"); -$help_url = ''; -saturne_header( 0, '', $help_url); +$title = $langs->trans('LinkedObjects') . ' - ' . $langs->trans(ucfirst($object->element)); +$helpUrl = 'FR:Module_DoliCar'; -$res = $object->fetch_optionals(); +saturne_header( 0, '', $title, $helpUrl); -print saturne_get_fiche_head($object, 'linkedobjects', $langs->trans("RegistrationCertificateFr")); +if ($id > 0 || !empty($ref)) { + saturne_get_fiche_head($object, 'linkedobjects', $title); + saturne_banner_tab($object); -saturne_banner_tab($object); + print '
'; + require_once __DIR__ . '/../../core/tpl/registrationcertificatefr_linked_objects.tpl.php'; + print '
'; -require_once __DIR__ . '/../../core/tpl/accountancy_linked_objects.tpl.php'; + print dol_get_fiche_end(); +} -print $outputline; +// End of page +llxFooter(); +$db->close();