';
+ // Bouton
+ print '
';
print ' ';
- print ' ';
- print ' ';
+ print ' ';
+ print ' ';
print '
';
- print '';
+ print '';
- print '
';
+ print '
';
}
// End of page
diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php
index fdf0f5aed1f..9288c2e2f1b 100644
--- a/htdocs/admin/system/dolibarr.php
+++ b/htdocs/admin/system/dolibarr.php
@@ -367,8 +367,7 @@ foreach ($configfileparameters as $key => $value)
print "
";
if ($newkey == 'dolibarr_main_db_pass') print preg_replace('/./i', '*', ${$newkey});
elseif ($newkey == 'dolibarr_main_url_root' && preg_match('/__auto__/', ${$newkey})) print ${$newkey}.' => '.constant('DOL_MAIN_URL_ROOT');
- elseif ($newkey == 'dolibarr_main_document_root_alt')
- {
+ elseif ($newkey == 'dolibarr_main_document_root_alt') {
$tmparray = explode(',', ${$newkey});
$i = 0;
foreach ($tmparray as $value2)
@@ -382,8 +381,7 @@ foreach ($configfileparameters as $key => $value)
}
++$i;
}
- } elseif ($newkey == 'dolibarr_main_instance_unique_id')
- {
+ } elseif ($newkey == 'dolibarr_main_instance_unique_id') {
//print $conf->file->instance_unique_id;
global $dolibarr_main_cookie_cryptkey;
$valuetoshow = ${$newkey} ? ${$newkey} : $dolibarr_main_cookie_cryptkey; // Use $dolibarr_main_instance_unique_id first then $dolibarr_main_cookie_cryptkey
@@ -392,6 +390,13 @@ foreach ($configfileparameters as $key => $value)
print img_warning("EditConfigFileToAddEntry", 'dolibarr_main_instance_unique_id');
}
print ' ('.$langs->trans("HashForPing").'='.md5('dolibarr'.$valuetoshow).') ';
+ } elseif ($newkey == 'dolibarr_main_prod') {
+ print ${$newkey};
+
+ $valuetoshow = ${$newkey};
+ if (empty($valuetoshow)) {
+ print img_warning($langs->trans('SwitchThisForABetterSecurity'));
+ }
} else {
print ${$newkey};
}
diff --git a/htdocs/admin/system/modules.php b/htdocs/admin/system/modules.php
index 1e5de3b9a46..c909084f1d6 100644
--- a/htdocs/admin/system/modules.php
+++ b/htdocs/admin/system/modules.php
@@ -25,68 +25,93 @@
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+if (!$user->admin) {
+ accessforbidden();
+}
+
// Load translation files required by the page
$langs->loadLangs(array("install", "other", "admin"));
-if (!$user->admin)
- accessforbidden();
+$optioncss = GETPOST('optioncss', 'alpha');
+$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'moduleoverview';
+$search_name = GETPOST("search_name", 'alpha');
+$search_id = GETPOST("search_id", 'alpha');
+$search_version = GETPOST("search_version", 'alpha');
+$search_permission = GETPOST("search_permission", 'alpha');
+
+$sortfield = GETPOST("sortfield", 'alpha');
+$sortorder = GETPOST("sortorder", 'alpha');
+
+if (!$sortfield) $sortfield = "id";
+if (!$sortorder) $sortorder = "asc";
+
+// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks
+$hookmanager->initHooks(array('moduleoverview'));
+$form = new Form($db);
+$object = new stdClass();
+
+// Definition of fields for lists
+$arrayfields = array(
+ 'name'=>array('label'=>$langs->trans("Modules"), 'checked'=>1, 'position'=>10),
+ 'version'=>array('label'=>$langs->trans("Version"), 'checked'=>1, 'position'=>20),
+ 'id'=>array('label'=>$langs->trans("IdModule"), 'checked'=>1, 'position'=>30),
+ 'permission'=>array('label'=>$langs->trans("IdPermissions"), 'checked'=>1, 'position'=>40)
+);
+
+$arrayfields = dol_sort_array($arrayfields, 'position');
/*
- * View
+ * Actions
*/
-llxHeader();
+$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');
-print load_fiche_titre($langs->trans("AvailableModules"), '', 'title_setup');
+if (empty($reshook)) {
+ // Selection of new fields
+ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+}
-print ''.$langs->trans("ToActivateModule").' ';
-print " \n";
+// Load list of modules
+$moduleList = array();
$modules = array();
-$modules_names = array();
$modules_files = array();
$modules_fullpath = array();
$modulesdir = dolGetModulesDirs();
+$rights_ids = array();
-// Load list of modules
-$i = 0;
-foreach ($modulesdir as $dir)
-{
+foreach ($modulesdir as $dir) {
$handle = @opendir(dol_osencode($dir));
- if (is_resource($handle))
- {
- while (($file = readdir($handle)) !== false)
- {
- if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php')
- {
+ if (is_resource($handle)) {
+ while (($file = readdir($handle)) !== false) {
+ if (is_readable($dir.$file) && substr($file, 0, 3) == 'mod' && substr($file, dol_strlen($file) - 10) == '.class.php') {
$modName = substr($file, 0, dol_strlen($file) - 10);
- if ($modName)
- {
+ if ($modName) {
//print 'xx'.$dir.$file.' ';
- if (in_array($file, $modules_files))
- {
+ if (in_array($file, $modules_files)) {
// File duplicate
print "Warning duplicate file found : ".$file." (Found ".$dir.$file.", already found ".$modules_fullpath[$file].") ";
- } else {
+ }
+ else {
// File to load
$res = include_once $dir.$file;
- if (class_exists($modName))
- {
+ if (class_exists($modName)) {
try {
$objMod = new $modName($db);
$modules[$objMod->numero] = $objMod;
- $modules_names[$objMod->numero] = $objMod->name;
$modules_files[$objMod->numero] = $file;
$modules_fullpath[$file] = $dir.$file;
- $picto[$objMod->numero] = (isset($objMod->picto) && $objMod->picto) ? $objMod->picto : 'generic';
- } catch (Exception $e)
- {
+ }
+ catch (Exception $e) {
dol_syslog("Failed to load ".$dir.$file." ".$e->getMessage(), LOG_ERR);
}
- } else {
+ }
+ else {
print "Warning bad descriptor file : ".$dir.$file." (Class ".$modName." not found into file) ";
}
}
@@ -97,60 +122,280 @@ foreach ($modulesdir as $dir)
}
}
-print '';
-print '
';
-print '';
-print ''.$langs->trans("Modules").' ';
-print ''.$langs->trans("Version").' ';
-print ''.$langs->trans("IdModule").' ';
-print ''.$langs->trans("IdPermissions").' ';
-print ' ';
-$var = false;
-$sortorder = $modules_names;
-ksort($sortorder);
-$rights_ids = array();
-foreach ($sortorder as $numero=>$name)
-{
- $idperms = "";
- // Module
- print '';
- $alt = $name.' - '.$modules_files[$numero];
- if (!empty($picto[$numero]))
- {
- if (preg_match('/^\//', $picto[$numero])) print img_picto($alt, $picto[$numero], 'width="14px"', 1);
- else print img_object($alt, $picto[$numero], 'width="14px"');
- } else {
- print img_object($alt, $picto[$numero], 'width="14px"');
+// create pre-filtered list for modules
+foreach ($modules as $key=>$module) {
+ $newModule = new stdClass();
+
+ $newModule->name = $module->getName();
+ $newModule->version = $module->getVersion();
+ $newModule->id = $key;
+
+ $alt = $module->name.' - '.$modules_files[$key];
+
+ if (!empty($module->picto)) {
+ if (preg_match('/^\//', $module->picto)) $newModule->picto = img_picto($alt, $module->picto, 'width="14px"', 1);
+ else $newModule->picto = img_object($alt, $module->picto, 'width="14px"');
}
- print ' '.$modules[$numero]->getName();
- print " ";
- // Version
- print ''.$modules[$numero]->getVersion().' ';
- // Id
- print ''.$numero.' ';
- // Permissions
- if ($modules[$numero]->rights)
- {
- foreach ($modules[$numero]->rights as $rights)
- {
- $idperms .= ($idperms ? ", " : "").$rights[0];
+ else {
+ $newModule->picto = img_object($alt, 'generic', 'width="14px"');
+ }
+
+ $permission = array();
+ if ($module->rights) {
+ foreach ($module->rights as $rights) {
+ if (empty($rights[0])) {
+ continue;
+ }
+
+ $permission[] = $rights[0];
+
array_push($rights_ids, $rights[0]);
}
}
- print ''.($idperms ? $idperms : " ").' ';
- print " \n";
+
+ $newModule->permission = $permission;
+
+ // pre-filter list
+ if ($search_name && !stristr($newModule->name, $search_name)) continue;
+ if ($search_version && !stristr($newModule->version, $search_version)) continue;
+ if ($search_id && !stristr($newModule->id, $search_id)) continue;
+
+ if ($search_permission) {
+ $found = false;
+
+ foreach ($newModule->permission as $permission) {
+ if (stristr($permission, $search_permission)) {
+ $found = true;
+ break;
+ }
+ }
+
+ if (!$found) continue;
+ }
+
+ $moduleList[] = $newModule;
}
+
+
+
+/*
+ * View
+ */
+
+llxHeader();
+
+print '';
print ' ';
+
sort($rights_ids);
$old = '';
-foreach ($rights_ids as $right_id)
-{
- if ($old == $right_id) print "Warning duplicate id on permission : ".$right_id." ";
+
+foreach ($rights_ids as $right_id) {
+ if ($old == $right_id) {
+ print "Warning duplicate id on permission : ".$right_id." ";
+ }
+
$old = $right_id;
}
// End of page
llxFooter();
$db->close();
+
+
+ /**
+ * Compare two modules by their ID for a ascending order
+ *
+ * @param stdClass $a First module
+ * @param stdClass $b Second module
+ * @return int Compare result (-1, 0, 1)
+ */
+function compareIdAsc(stdClass $a, stdClass $b)
+{
+ if ($a->id == $b->id) return 0;
+
+ return $a->id > $b->id ? -1 : 1;
+}
+
+ /**
+ * Compare two modules by their ID for a descending order
+ *
+ * @param stdClass $a First module
+ * @param stdClass $b Second module
+ * @return int Compare result (-1, 0, 1)
+ */
+function compareIdDesc(stdClass $a, stdClass $b)
+{
+ if ($a->id == $b->id) return 0;
+
+ return $b->id > $a->id ? -1 : 1;
+}
+
+ /**
+ * Compare two modules by their ID for a ascending order
+ *
+ * @param stdClass $a First module
+ * @param stdClass $b Second module
+ * @return int Compare result (-1, 0, 1)
+ */
+function comparePermissionIdsAsc(stdClass $a, stdClass $b)
+{
+ if (empty($a->permission) && empty($b->permission)) return compareIdAsc($a, $b);
+
+ if (empty($a->permission)) return 1;
+ if (empty($b->permission)) return -1;
+
+ if ($a->permission[0] == $b->permission[0]) return 0;
+
+ return $a->permission[0] > $b->permission[0] ? -1 : 1;
+}
+
+ /**
+ * Compare two modules by their permissions for a descending order
+ *
+ * @param stdClass $a First module
+ * @param stdClass $b Second module
+ * @return int Compare result (-1, 0, 1)
+ */
+function comparePermissionIdsDesc(stdClass $a, stdClass $b)
+{
+ if (empty($a->permission) && empty($b->permission)) return compareIdDesc($a, $b);
+
+ if (empty($a->permission)) return -1;
+ if (empty($b->permission)) return 1;
+
+ if ($a->permission[0] == $b->permission[0]) return 0;
+
+ return $a->permission[0] > $b->permission[0] ? 1 : -1;
+}
diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php
index 311531a52de..671bacee080 100644
--- a/htdocs/admin/workflow.php
+++ b/htdocs/admin/workflow.php
@@ -1,8 +1,8 @@
- * Copyright (C) 2004 Eric Seigne
- * Copyright (C) 2005-2016 Laurent Destailleur
- * Copyright (C) 2005-2012 Regis Houssin
+/* Copyright (C) 2004 Rodolphe Quiedeville
+ * Copyright (C) 2004 Eric Seigne
+ * Copyright (C) 2005-2016 Laurent Destailleur
+ * Copyright (C) 2005-2012 Regis Houssin
*
* 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,19 +19,20 @@
*/
/**
- * \file htdocs/admin/workflow.php
- * \ingroup company
- * \brief Workflows setup page
+ * \file htdocs/admin/workflow.php
+ * \ingroup company
+ * \brief Workflows setup page
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
-// Load translation files required by the page
-$langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposal", "receptions"));
-
+// security check
if (!$user->admin) accessforbidden();
+// Load translation files required by the page
+$langs->loadLangs(array("admin", "workflow", "propal", "workflow", "orders", "supplier_proposal", "receptions", "errors"));
+
$action = GETPOST('action', 'alpha');
@@ -39,157 +40,199 @@ $action = GETPOST('action', 'alpha');
* Actions
*/
-if (preg_match('/set(.*)/', $action, $reg))
-{
- if (!dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0)
- {
- dol_print_error($db);
- }
+if (preg_match('/set(.*)/', $action, $reg)) {
+ if (!dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0) {
+ dol_print_error($db);
+ }
}
-if (preg_match('/del(.*)/', $action, $reg))
-{
- if (!dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0)
- {
- dol_print_error($db);
- }
+if (preg_match('/del(.*)/', $action, $reg)) {
+ if (!dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0) {
+ dol_print_error($db);
+ }
}
+// List of workflow we can enable
+clearstatcache();
+
+$workflowcodes = array(
+ // Automatic creation
+ 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array(
+ 'family'=>'create',
+ 'position'=>10,
+ 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->commande->enabled)),
+ 'picto'=>'order'
+ ),
+ 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array(
+ 'family'=>'create',
+ 'position'=>20,
+ 'enabled'=>(!empty($conf->commande->enabled) && !empty($conf->facture->enabled)),
+ 'picto'=>'bill'
+ ),
+
+ 'separator1'=>array('family'=>'separator', 'position'=>25),
+
+ // Automatic classification of proposal
+ 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array(
+ 'family'=>'classify_proposal',
+ 'position'=>30,
+ 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->commande->enabled)),
+ 'picto'=>'propal',
+ 'warning'=>''
+ ),
+ 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array(
+ 'family'=>'classify_proposal',
+ 'position'=>31,
+ 'enabled'=>(!empty($conf->propal->enabled) && !empty($conf->facture->enabled)),
+ 'picto'=>'propal',
+ 'warning'=>''
+ ),
+
+ // Automatic classification of order
+ 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array(
+ 'family'=>'classify_order',
+ 'position'=>40,
+ 'enabled'=>(!empty($conf->expedition->enabled) && !empty($conf->commande->enabled)),
+ 'picto'=>'order'
+ ),
+ 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array(
+ 'family'=>'classify_order',
+ 'position'=>41,
+ 'enabled'=>(!empty($conf->facture->enabled) && !empty($conf->commande->enabled)),
+ 'picto'=>'order',
+ 'warning'=>''
+ ), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card.
+
+ 'separator2'=>array('family'=>'separator', 'position'=>50),
+
+ // Automatic classification supplier proposal
+ 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array(
+ 'family'=>'classify_supplier_proposal',
+ 'position'=>60,
+ 'enabled'=>(!empty($conf->supplier_proposal->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))),
+ 'picto'=>'propal',
+ 'warning'=>''
+ ),
+
+ // Automatic classification supplier order
+ 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array(
+ 'family'=>'classify_supplier_order',
+ 'position'=>62,
+ 'enabled'=>(!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)),
+ 'picto'=>'order',
+ 'warning'=>''
+ ),
+
+ // Automatic classification reception
+ 'WORKFLOW_BILL_ON_RECEPTION'=>array(
+ 'family'=>'classify_reception',
+ 'position'=>64,
+ 'enabled'=>(!empty($conf->reception->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))),
+ 'picto'=>'bill'
+ ),
+);
+
+if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) {
+ foreach ($conf->modules_parts['workflow'] as $workflow) {
+ $workflowcodes = array_merge($workflowcodes, $workflow);
+ }
+}
+
+// remove not available workflows (based on activated modules and global defined keys)
+$workflowcodes = array_filter($workflowcodes, function ($var) {
+ return $var['enabled']; });
/*
- * View
+ * View
*/
-llxHeader('', $langs->trans("WorkflowSetup"), '');
+llxHeader('', $langs->trans("WorkflowSetup"), "EN:Module_Workflow_En|FR:Module_Workflow|ES:Módulo_Workflow");
$linkback = ''.$langs->trans("BackToModuleList").' ';
print load_fiche_titre($langs->trans("WorkflowSetup"), $linkback, 'title_setup');
-print ''.$langs->trans("WorkflowDesc").' ';
-print " ";
+print ''.$langs->trans("WorkflowDesc").' ';
+print ' ';
+print ' ';
-// List of workflow we can enable
+// current module setup don't support any automatic workflow of this module
+if (count($workflowcodes) < 1) {
+ print $langs->trans("ThereIsNoWorkflowToModify");
-clearstatcache();
-
-$workflowcodes = array(
- // Automatic creation
- 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array('family'=>'create', 'position'=>10, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'),
- 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array('family'=>'create', 'position'=>20, 'enabled'=>'! empty($conf->commande->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'bill'),
- 'separator1'=>array('family'=>'separator', 'position'=>25),
- // Automatic classification of proposal
- 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>30, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'propal', 'warning'=>''),
- 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify_proposal', 'position'=>31, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'propal', 'warning'=>''),
- 'separator2'=>array('family'=>'separator', 'position'=>35),
- // Automatic classification of order
- 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array('family'=>'classify_order', 'position'=>40, 'enabled'=>'! empty($conf->expedition->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'),
- 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array('family'=>'classify_order', 'position'=>41, 'enabled'=>'! empty($conf->facture->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order', 'warning'=>''), // For this option, if module invoice is disabled, it does not exists, so "Classify billed" for order must be done manually from order card.
- 'separator3'=>array('family'=>'separator', 'position'=>50),
- // Automatic classification supplier proposal
- 'WORKFLOW_ORDER_CLASSIFY_BILLED_SUPPLIER_PROPOSAL'=>array('family'=>'classify_supplier_proposal', 'position'=>60, 'enabled'=>'! empty($conf->supplier_proposal->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))', 'picto'=>'propal', 'warning'=>''),
- 'separator4'=>array('family'=>'separator', 'position'=>61),
- // Automatic classification supplier order
- 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array('family'=>'classify_supplier_order', 'position'=>62, 'enabled'=>'!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)', 'picto'=>'order', 'warning'=>''),
- 'separator5'=>array('family'=>'separator', 'position'=>63),
- // Automatic classification reception
- 'WORKFLOW_BILL_ON_RECEPTION'=>array('family'=>'classify_reception', 'position'=>64, 'enabled'=>'! empty($conf->reception->enabled) && (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))', 'picto'=>'bill'),
- 'separator6'=>array('family'=>'separator', 'position'=>90),
- // Automatic classification of intervention
- 'WORKFLOW_TICKET_CLOSE_INTERVENTION'=>array('family'=>'classify_intervention', 'position'=>100, 'enabled'=>'! empty($conf->ticket->enabled) && !empty($conf->ficheinter->enabled)', 'picto'=>'intervention'),
-);
-
-if (!empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow']))
-{
- foreach ($conf->modules_parts['workflow'] as $workflow)
- {
- $workflowcodes = array_merge($workflowcodes, $workflow);
- }
+ llxFooter();
+ $db->close();
+ return;
}
// Sort on position
$workflowcodes = dol_sort_array($workflowcodes, 'position');
-$nbqualified = 0;
+print '';
+
$oldfamily = '';
-print ''."\n";
-
-foreach ($workflowcodes as $key => $params)
-{
- $picto = $params['picto'];
- $enabled = $params['enabled'];
- $family = $params['family'];
-
- if ($family == 'separator')
- {
- print '
';
- print ''."\n";
+foreach ($workflowcodes as $key => $params) {
+ if ($params['family'] == 'separator') {
+ print '
';
+ print ' ';
+ print '';
continue;
}
- if (!verifCond($enabled)) continue;
-
- $nbqualified++;
-
-
- if ($oldfamily != $family)
- {
- print ''."\n";
- print ' ';
- $reg = array();
- if ($family == 'create') {
- print $langs->trans("AutomaticCreation");
- } elseif (preg_match('/classify_(.*)/', $family, $reg))
- {
- print $langs->trans("AutomaticClassification");
- if ($reg[1] == 'proposal') print ' - '.$langs->trans('Proposal');
- if ($reg[1] == 'order') print ' - '.$langs->trans('Order');
- if ($reg[1] == 'supplier_proposal') print ' - '.$langs->trans('SupplierProposal');
- if ($reg[1] == 'supplier_order') print ' - '.$langs->trans('SupplierOrder');
- if ($reg[1] == 'reception') print ' - '.$langs->trans('Reception');
- if ($reg[1] == 'intervention') print ' - '.$langs->trans('Intervention');
+ if ($oldfamily != $params['family']) {
+ if ($params['family'] == 'create') {
+ $header = $langs->trans("AutomaticCreation");
+ } elseif (preg_match('/classify_(.*)/', $params['family'], $reg)) {
+ $header = $langs->trans("AutomaticClassification");
+ if ($reg[1] == 'proposal') $header .= ' - '.$langs->trans('Proposal');
+ if ($reg[1] == 'order') $header .= ' - '.$langs->trans('Order');
+ if ($reg[1] == 'supplier_proposal') $header .= ' - '.$langs->trans('SupplierProposal');
+ if ($reg[1] == 'supplier_order') $header .= ' - '.$langs->trans('SupplierOrder');
+ if ($reg[1] == 'reception') $header .= ' - '.$langs->trans('Reception');
} else {
- print $langs->trans("Description");
+ $header = $langs->trans("Description");
}
- print ' ';
- print ' '.$langs->trans("Status").' ';
- print " \n";
- $oldfamily = $family;
- }
- print "\n";
- print "".img_object('', $picto, 'class="paddingright"').$langs->trans('desc'.$key);
- if (!empty($params['warning']))
- {
- $langs->load("errors");
- print ' '.img_warning($langs->transnoentitiesnoconv($params['warning']));
- }
- print " \n";
- print '';
- if (!empty($conf->use_javascript_ajax))
- {
- print ajax_constantonoff($key);
- } else {
- if (!empty($conf->global->$key))
- {
- print '';
- print img_picto($langs->trans("Activated"), 'switch_on');
- print ' ';
- } else {
- print '';
- print img_picto($langs->trans("Disabled"), 'switch_off');
- print ' ';
- }
- }
- print ' ';
- print ' ';
+ print '';
+ print ''.$header.' ';
+ print ''.$langs->trans("Status").' ';
+ print ' ';
+
+ $oldfamily = $params['family'];
+ }
+
+ print '';
+ print '';
+ print img_object('', $params['picto']);
+ print ' '.$langs->trans('desc'.$key);
+
+ if (!empty($params['warning'])) {
+ print ' '.img_warning($langs->transnoentitiesnoconv($params['warning']));
+ }
+
+ print ' ';
+
+ print '';
+
+ if (!empty($conf->use_javascript_ajax)) {
+ print ajax_constantonoff($key);
+ } else {
+ if (!empty($conf->global->$key)) {
+ print '';
+ print img_picto($langs->trans("Activated"), 'switch_on');
+ print ' ';
+ } else {
+ print '';
+ print img_picto($langs->trans("Disabled"), 'switch_off');
+ print ' ';
+ }
+ }
+
+ print ' ';
+ print ' ';
}
-if ($nbqualified == 0)
-{
- print ''.$langs->trans("ThereIsNoWorkflowToModify");
-}
print '
';
// End of page
diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php
index 83bd00555d6..554edbb892e 100644
--- a/htdocs/api/class/api.class.php
+++ b/htdocs/api/class/api.class.php
@@ -32,7 +32,7 @@ class DolibarrApi
/**
* @var DoliDb $db Database object
*/
- protected static $db;
+ protected $db;
/**
* @var Restler $r Restler object
diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php
index 69fef80fd6b..9605f46f219 100644
--- a/htdocs/api/class/api_documents.class.php
+++ b/htdocs/api/class/api_documents.class.php
@@ -196,7 +196,7 @@ class Documents extends DolibarrApi
throw new RestException(404, 'Invoice not found');
}
- $templateused = $doctemplate ? $doctemplate : $this->invoice->modelpdf;
+ $templateused = $doctemplate ? $doctemplate : $this->invoice->model_pdf;
$result = $this->invoice->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
if ($result <= 0) {
throw new RestException(500, 'Error generating document');
@@ -210,7 +210,7 @@ class Documents extends DolibarrApi
if (!$result) {
throw new RestException(404, 'Order not found');
}
- $templateused = $doctemplate ? $doctemplate : $this->order->modelpdf;
+ $templateused = $doctemplate ? $doctemplate : $this->order->model_pdf;
$result = $this->order->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
if ($result <= 0) {
throw new RestException(500, 'Error generating document');
@@ -224,7 +224,7 @@ class Documents extends DolibarrApi
if (!$result) {
throw new RestException(404, 'Proposal not found');
}
- $templateused = $doctemplate ? $doctemplate : $this->propal->modelpdf;
+ $templateused = $doctemplate ? $doctemplate : $this->propal->model_pdf;
$result = $this->propal->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
if ($result <= 0) {
throw new RestException(500, 'Error generating document');
diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php
index 5dade088fd0..58b8954762c 100644
--- a/htdocs/api/class/api_setup.class.php
+++ b/htdocs/api/class/api_setup.class.php
@@ -1413,7 +1413,7 @@ class Setup extends DolibarrApi
* @url GET conf/{constantname}
*
* @throws RestException 403 Forbidden
- * @throws RestException 500 Error Bad or unknown value for constantname
+ * @throws RestException 404 Error Bad or unknown value for constantname
*/
public function getConf($constantname)
{
@@ -1425,7 +1425,7 @@ class Setup extends DolibarrApi
}
if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) {
- throw new RestException(500, 'Error Bad or unknown value for constantname');
+ throw new RestException(404, 'Error Bad or unknown value for constantname');
}
if (preg_match('/(_pass|_pw|password|secret|_key|key$)/i', $constantname)) {
throw new RestException(403, 'Forbidden');
diff --git a/htdocs/asset/card.php b/htdocs/asset/card.php
index 8606751ba85..8a6cb9b5e94 100644
--- a/htdocs/asset/card.php
+++ b/htdocs/asset/card.php
@@ -346,7 +346,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
$genallowed = $user->rights->asset->read; // If you can read, you can build the PDF to read content
$delallowed = $user->rights->asset->create; // If you can create/edit, you can remove a file on card
- print $formfile->showdocuments('asset', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
+ print $formfile->showdocuments('asset', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
*/
// Show links to link elements
diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php
index 44311f1a580..7bb252394c3 100644
--- a/htdocs/blockedlog/class/blockedlog.class.php
+++ b/htdocs/blockedlog/class/blockedlog.class.php
@@ -368,7 +368,7 @@ class BlockedLog
$this->object_data = new stdClass();
// Add fields to exclude
$arrayoffieldstoexclude = array(
- 'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id',
+ 'table_element', 'fields', 'ref_previous', 'ref_next', 'origin', 'origin_id', 'oldcopy', 'picto', 'error', 'errors', 'model_pdf', 'modelpdf', 'last_main_doc', 'civility_id', 'contact', 'contact_id',
'table_element_line', 'ismultientitymanaged', 'isextrafieldmanaged',
'linkedObjectsIds',
'linkedObjects',
@@ -476,7 +476,7 @@ class BlockedLog
$this->object_data->ref = $object->ref;
$this->object_data->date = $datepayment;
$this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code');
- $this->object_data->payment_num = ($object->num_paiement ? $object->num_paiement : $object->num_payment);
+ $this->object_data->payment_num = $object->num_payment;
//$this->object_data->fk_account = $object->fk_account;
$this->object_data->note = $object->note;
//var_dump($this->object_data);exit;
diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php
index 079fcb608ab..1230a0e3269 100644
--- a/htdocs/bom/bom_card.php
+++ b/htdocs/bom/bom_card.php
@@ -707,7 +707,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
$genallowed = $user->rights->bom->read; // If you can read, you can build the PDF to read content
$delallowed = $user->rights->bom->write; // If you can create/edit, you can remove a file on card
- print $formfile->showdocuments('bom', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang);
+ print $formfile->showdocuments('bom', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang);
// Show links to link elements
$linktoelem = $form->showLinkToObjectBlock($object, null, array('bom'));
diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php
index d180c00426f..bd67f311d19 100644
--- a/htdocs/bom/class/bom.class.php
+++ b/htdocs/bom/class/bom.class.php
@@ -745,7 +745,7 @@ class BOM extends CommonObject
$result = '';
- $label = ''.$langs->trans("BillOfMaterials").' ';
+ $label = img_picto('', $this->picto).' '.$langs->trans("BillOfMaterials").' ';
$label .= ' ';
$label .= ''.$langs->trans('Ref').': '.$this->ref;
if (isset($this->status)) {
@@ -934,8 +934,8 @@ class BOM extends CommonObject
if (!dol_strlen($modele)) {
$modele = 'standard';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->BOM_ADDON_PDF)) {
$modele = $conf->global->BOM_ADDON_PDF;
}
diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php
index 3253d6d5d3e..6b8e9af94f1 100644
--- a/htdocs/cashdesk/validation_verif.php
+++ b/htdocs/cashdesk/validation_verif.php
@@ -294,9 +294,8 @@ switch ($action)
// Add the payment
$payment = new Paiement($db);
$payment->datepaye = $now;
- $payment->bank_account = $conf_fkaccount;
$payment->amounts[$invoice->id] = $obj_facturation->amountWithTax();
- $payment->note = $langs->trans("Payment").' '.$langs->trans("Invoice").' '.$obj_facturation->numInvoice();
+ $payment->note_public = $langs->trans("Payment").' '.$langs->trans("Invoice").' '.$obj_facturation->numInvoice();
$payment->paiementid = $invoice->mode_reglement_id;
$payment->num_paiement = '';
$payment->num_payment = '';
diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php
index a181586815f..d24bf74e99f 100644
--- a/htdocs/comm/action/card.php
+++ b/htdocs/comm/action/card.php
@@ -1043,7 +1043,7 @@ if ($action == 'create')
}*/
print '';
- // Realised by
+ // Done by
if (!empty($conf->global->AGENDA_ENABLE_DONEBY))
{
print ''.$langs->trans("ActionDoneBy").' ';
diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php
index 5514172182e..dc82c0cfaa4 100644
--- a/htdocs/comm/action/class/actioncomm.class.php
+++ b/htdocs/comm/action/class/actioncomm.class.php
@@ -33,9 +33,6 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php';
-
-
-
/**
* Class to manage agenda events (actions)
*/
@@ -498,7 +495,7 @@ class ActionComm extends CommonObject
$sql .= ((isset($this->socid) && $this->socid > 0) ? $this->socid : "null").", ";
$sql .= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project : "null").", ";
$sql .= " '".$this->db->escape($this->note_private)."', ";
- $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned
+ $sql .= ((isset($this->contact_id) && $this->contact_id > 0) ? $this->contact_id : "null").", "; // deprecated, use ->socpeopleassigned
$sql .= (isset($user->id) && $user->id > 0 ? $user->id : "null").", ";
$sql .= ($userownerid > 0 ? $userownerid : "null").", ";
$sql .= ($userdoneid > 0 ? $userdoneid : "null").", ";
@@ -632,173 +629,173 @@ class ActionComm extends CommonObject
//$this->fetch_userassigned();
$this->fetchResources();
- $this->id = 0;
+ $this->id = 0;
- // Create clone
+ // Create clone
$this->context['createfromclone'] = 'createfromclone';
$result = $this->create($fuser);
- if ($result < 0) $error++;
+ if ($result < 0) $error++;
- if (!$error)
- {
- // Hook of thirdparty module
- if (is_object($hookmanager))
- {
- $parameters = array('objFrom'=>$objFrom);
- $action = '';
- $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
- if ($reshook < 0) $error++;
- }
+ if (!$error)
+ {
+ // Hook of thirdparty module
+ if (is_object($hookmanager))
+ {
+ $parameters = array('objFrom'=>$objFrom);
+ $action = '';
+ $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook < 0) $error++;
+ }
- // Call trigger
- $result = $this->call_trigger('ACTION_CLONE', $fuser);
- if ($result < 0) { $error++; }
- // End call triggers
- }
+ // Call trigger
+ $result = $this->call_trigger('ACTION_CLONE', $fuser);
+ if ($result < 0) { $error++; }
+ // End call triggers
+ }
- unset($this->context['createfromclone']);
+ unset($this->context['createfromclone']);
- // End
- if (!$error)
- {
- $this->db->commit();
- return $this->id;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ // End
+ if (!$error)
+ {
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Load object from database
- *
- * @param int $id Id of action to get
- * @param string $ref Ref of action to get
- * @param string $ref_ext Ref ext to get
+ /**
+ * Load object from database
+ *
+ * @param int $id Id of action to get
+ * @param string $ref Ref of action to get
+ * @param string $ref_ext Ref ext to get
* @param string $email_msgid Email msgid
- * @return int <0 if KO, >0 if OK
- */
- public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
- {
- global $langs;
+ * @return int <0 if KO, >0 if OK
+ */
+ public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '')
+ {
+ global $langs;
- $sql = "SELECT a.id,";
- $sql .= " a.id as ref,";
- $sql .= " a.entity,";
- $sql .= " a.ref_ext,";
- $sql .= " a.datep,";
- $sql .= " a.datep2,";
- $sql .= " a.durationp,"; // deprecated
- $sql .= " a.datec,";
- $sql .= " a.tms as datem,";
- $sql .= " a.code, a.label, a.note,";
- $sql .= " a.fk_soc,";
- $sql .= " a.fk_project,";
- $sql .= " a.fk_user_author, a.fk_user_mod,";
- $sql .= " a.fk_user_action, a.fk_user_done,";
- $sql .= " a.fk_contact, a.percent as percentage,";
- $sql .= " a.fk_element as elementid, a.elementtype,";
- $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,";
- $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,";
- $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,";
- $sql .= " s.nom as socname,";
- $sql .= " u.firstname, u.lastname as lastname";
- $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
- $sql .= " WHERE ";
- if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id
- elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'";
- elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'";
- else $sql .= " a.id = ".((int) $id);
+ $sql = "SELECT a.id,";
+ $sql .= " a.id as ref,";
+ $sql .= " a.entity,";
+ $sql .= " a.ref_ext,";
+ $sql .= " a.datep,";
+ $sql .= " a.datep2,";
+ $sql .= " a.durationp,"; // deprecated
+ $sql .= " a.datec,";
+ $sql .= " a.tms as datem,";
+ $sql .= " a.code, a.label, a.note,";
+ $sql .= " a.fk_soc,";
+ $sql .= " a.fk_project,";
+ $sql .= " a.fk_user_author, a.fk_user_mod,";
+ $sql .= " a.fk_user_action, a.fk_user_done,";
+ $sql .= " a.fk_contact, a.percent as percentage,";
+ $sql .= " a.fk_element as elementid, a.elementtype,";
+ $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,";
+ $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,";
+ $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,";
+ $sql .= " s.nom as socname,";
+ $sql .= " u.firstname, u.lastname as lastname";
+ $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a ";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id ";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc";
+ $sql .= " WHERE ";
+ if ($ref) $sql .= " a.id = ".((int) $ref); // No field ref, we use id
+ elseif ($ref_ext) $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'";
+ elseif ($email_msgid) $sql .= " a.email_msgid = '".$this->db->escape($email_msgid)."'";
+ else $sql .= " a.id = ".((int) $id);
- dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $num = $this->db->num_rows($resql);
- if ($num)
- {
- $obj = $this->db->fetch_object($resql);
+ dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $num = $this->db->num_rows($resql);
+ if ($num)
+ {
+ $obj = $this->db->fetch_object($resql);
- $this->id = $obj->id;
+ $this->id = $obj->id;
$this->entity = $obj->entity;
- $this->ref = $obj->ref;
- $this->ref_ext = $obj->ref_ext;
+ $this->ref = $obj->ref;
+ $this->ref_ext = $obj->ref_ext;
- // Properties of parent table llx_c_actioncomm
- $this->type_id = $obj->type_id;
- $this->type_code = $obj->type_code;
- $this->type_color = $obj->type_color;
- $this->type_picto = $obj->type_picto;
- $transcode = $langs->trans("Action".$obj->type_code);
- $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label);
- $transcode = $langs->trans("Action".$obj->type_code.'Short');
- $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : '');
+ // Properties of parent table llx_c_actioncomm
+ $this->type_id = $obj->type_id;
+ $this->type_code = $obj->type_code;
+ $this->type_color = $obj->type_color;
+ $this->type_picto = $obj->type_picto;
+ $transcode = $langs->trans("Action".$obj->type_code);
+ $this->type = (($transcode != "Action".$obj->type_code) ? $transcode : $obj->type_label);
+ $transcode = $langs->trans("Action".$obj->type_code.'Short');
+ $this->type_short = (($transcode != "Action".$obj->type_code.'Short') ? $transcode : '');
$this->code = $obj->code;
- $this->label = $obj->label;
- $this->datep = $this->db->jdate($obj->datep);
- $this->datef = $this->db->jdate($obj->datep2);
+ $this->label = $obj->label;
+ $this->datep = $this->db->jdate($obj->datep);
+ $this->datef = $this->db->jdate($obj->datep2);
- $this->datec = $this->db->jdate($obj->datec);
- $this->datem = $this->db->jdate($obj->datem);
+ $this->datec = $this->db->jdate($obj->datec);
+ $this->datem = $this->db->jdate($obj->datem);
- $this->note = $obj->note; // deprecated
- $this->note_private = $obj->note;
- $this->percentage = $obj->percentage;
+ $this->note = $obj->note; // deprecated
+ $this->note_private = $obj->note;
+ $this->percentage = $obj->percentage;
- $this->authorid = $obj->fk_user_author;
- $this->usermodid = $obj->fk_user_mod;
+ $this->authorid = $obj->fk_user_author;
+ $this->usermodid = $obj->fk_user_mod;
- if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning
- $this->author->id = $obj->fk_user_author; // deprecated
- $this->author->firstname = $obj->firstname; // deprecated
- $this->author->lastname = $obj->lastname; // deprecated
- if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning
- $this->usermod->id = $obj->fk_user_mod; // deprecated
+ if (!is_object($this->author)) $this->author = new stdClass(); // To avoid warning
+ $this->author->id = $obj->fk_user_author; // deprecated
+ $this->author->firstname = $obj->firstname; // deprecated
+ $this->author->lastname = $obj->lastname; // deprecated
+ if (!is_object($this->usermod)) $this->usermod = new stdClass(); // To avoid warning
+ $this->usermod->id = $obj->fk_user_mod; // deprecated
- $this->userownerid = $obj->fk_user_action;
- $this->userdoneid = $obj->fk_user_done;
- $this->priority = $obj->priority;
- $this->fulldayevent = $obj->fulldayevent;
- $this->location = $obj->location;
- $this->transparency = $obj->transparency;
+ $this->userownerid = $obj->fk_user_action;
+ $this->userdoneid = $obj->fk_user_done;
+ $this->priority = $obj->priority;
+ $this->fulldayevent = $obj->fulldayevent;
+ $this->location = $obj->location;
+ $this->transparency = $obj->transparency;
- $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working
- $this->contact_id = $obj->fk_contact; // To have fetch_contact method working
- $this->fk_project = $obj->fk_project; // To have fetch_projet method working
+ $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working
+ $this->contact_id = $obj->fk_contact; // To have fetch_contact method working
+ $this->fk_project = $obj->fk_project; // To have fetch_projet method working
- //$this->societe->id = $obj->fk_soc; // deprecated
- //$this->contact->id = $obj->fk_contact; // deprecated
+ //$this->societe->id = $obj->fk_soc; // deprecated
+ //$this->contact->id = $obj->fk_contact; // deprecated
- $this->fk_element = $obj->elementid;
- $this->elementid = $obj->elementid;
- $this->elementtype = $obj->elementtype;
+ $this->fk_element = $obj->elementid;
+ $this->elementid = $obj->elementid;
+ $this->elementtype = $obj->elementtype;
- $this->fetchResources();
- }
- $this->db->free($resql);
- } else {
- $this->error = $this->db->lasterror();
- return -1;
- }
+ $this->fetchResources();
+ }
+ $this->db->free($resql);
+ } else {
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
- return $num;
- }
+ return $num;
+ }
- /**
- * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event
- *
- * @return int <0 if KO, >0 if OK
- */
- public function fetchResources()
- {
- $this->userassigned = array();
- $this->socpeopleassigned = array();
+ /**
+ * Initialize $this->userassigned & this->socpeopleassigned array with list of id of user and contact assigned to event
+ *
+ * @return int <0 if KO, >0 if OK
+ */
+ public function fetchResources()
+ {
+ $this->userassigned = array();
+ $this->socpeopleassigned = array();
- $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
+ $sql = 'SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency';
$sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm_resources';
$sql .= ' WHERE fk_actioncomm = '.$this->id;
$sql .= " AND element_type IN ('user', 'socpeople')";
@@ -1390,7 +1387,7 @@ class ActionComm extends CommonObject
if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL');
}
- $tooltip = ''.$langs->trans('Action').' ';
+ $tooltip = img_picto('', $this->picto).' '.$langs->trans('Action').' ';
if (!empty($this->ref))
$tooltip .= ''.$langs->trans('Ref').': '.$this->ref;
if (!empty($label))
@@ -1937,168 +1934,168 @@ class ActionComm extends CommonObject
return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
}
- /**
- * Is the action delayed?
- *
- * @return bool
- */
- public function hasDelay()
- {
- global $conf;
+ /**
+ * Is the action delayed?
+ *
+ * @return bool
+ */
+ public function hasDelay()
+ {
+ global $conf;
- $now = dol_now();
+ $now = dol_now();
- return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
- }
+ return $this->datep && ($this->datep < ($now - $conf->agenda->warning_delay));
+ }
- /**
- * Send reminders by emails
- * CAN BE A CRON TASK
- *
- * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
- */
- public function sendEmailsReminder()
- {
- global $conf, $langs, $user;
+ /**
+ * Send reminders by emails
+ * CAN BE A CRON TASK
+ *
+ * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
+ */
+ public function sendEmailsReminder()
+ {
+ global $conf, $langs, $user;
- $error = 0;
- $this->output = '';
+ $error = 0;
+ $this->output = '';
$this->error = '';
$nbMailSend = 0;
$errorsMsg = array();
- if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible.
+ if (empty($conf->agenda->enabled)) // Should not happen. If module disabled, cron job should not be visible.
{
$langs->load("agenda");
$this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
return 0;
}
if (empty($conf->global->AGENDA_REMINDER_EMAIL))
- {
- $langs->load("agenda");
- $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
- return 0;
- }
+ {
+ $langs->load("agenda");
+ $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Agenda"));
+ return 0;
+ }
- $now = dol_now();
+ $now = dol_now();
- dol_syslog(__METHOD__, LOG_DEBUG);
+ dol_syslog(__METHOD__, LOG_DEBUG);
- $this->db->begin();
+ $this->db->begin();
- //Select all action comm reminder
- $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
+ //Select all action comm reminder
+ $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
$sql .= " WHERE typeremind = 'email' AND status = 0";
$sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'";
$sql .= $this->db->order("dateremind", "ASC");
- $resql = $this->db->query($sql);
+ $resql = $this->db->query($sql);
- if ($resql) {
- $formmail = new FormMail($this->db);
- $actionCommReminder = new ActionCommReminder($this->db);
+ if ($resql) {
+ $formmail = new FormMail($this->db);
+ $actionCommReminder = new ActionCommReminder($this->db);
- while ($obj = $this->db->fetch_object($resql)){
- $res = $actionCommReminder->fetch($obj->id);
- if ($res < 0) {
- $error++;
- $errorsMsg[] = "Failed to load invoice ActionComm Reminder";
- }
+ while ($obj = $this->db->fetch_object($resql)) {
+ $res = $actionCommReminder->fetch($obj->id);
+ if ($res < 0) {
+ $error++;
+ $errorsMsg[] = "Failed to load invoice ActionComm Reminder";
+ }
- if (!$error)
- {
- //Select email template
- $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1);
+ if (!$error)
+ {
+ //Select email template
+ $arraymessage = $formmail->getEMailTemplate($this->db, 'actioncomm_send', $user, $langs, (!empty($actionCommReminder->fk_email_template)) ? $actionCommReminder->fk_email_template : -1, 1);
- // Load event
- $res = $this->fetch($actionCommReminder->fk_actioncomm);
- if ($res > 0)
- {
- // PREPARE EMAIL
+ // Load event
+ $res = $this->fetch($actionCommReminder->fk_actioncomm);
+ if ($res > 0)
+ {
+ // PREPARE EMAIL
- // Make substitution in email content
- $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this);
+ // Make substitution in email content
+ $substitutionarray = getCommonSubstitutionArray($langs, 0, '', $this);
- complete_substitutions_array($substitutionarray, $langs, $this);
+ complete_substitutions_array($substitutionarray, $langs, $this);
- // Content
- $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray);
+ // Content
+ $sendContent = make_substitutions($langs->trans($arraymessage->content), $substitutionarray);
- //Topic
- $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder'));
+ //Topic
+ $sendTopic = (!empty($arraymessage->topic)) ? $arraymessage->topic : html_entity_decode($langs->trans('EventReminder'));
- // Recipient
- $recipient = new User($this->db);
- $res = $recipient->fetch($actionCommReminder->fk_user);
- if ($res > 0 && !empty($recipient->email)) $to = $recipient->email;
- else {
- $errorsMsg[] = "Failed to load recipient";
- $error++;
- }
+ // Recipient
+ $recipient = new User($this->db);
+ $res = $recipient->fetch($actionCommReminder->fk_user);
+ if ($res > 0 && !empty($recipient->email)) $to = $recipient->email;
+ else {
+ $errorsMsg[] = "Failed to load recipient";
+ $error++;
+ }
- // Sender
- $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
- if (empty($from)) {
- $errorsMsg[] = "Failed to load recipient";
- $error++;
- }
+ // Sender
+ $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
+ if (empty($from)) {
+ $errorsMsg[] = "Failed to load recipient";
+ $error++;
+ }
- // Errors Recipient
- $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
+ // Errors Recipient
+ $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
- // Mail Creation
- $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
+ // Mail Creation
+ $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
- // Sending Mail
- if ($cMailFile->sendfile())
- {
- $actionCommReminder->status = $actionCommReminder::STATUS_DONE;
- $res = $actionCommReminder->update($user);
- if ($res < 0)
- {
- $errorsMsg[] = "Failed to update status of ActionComm Reminder";
- $error++;
- break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first.
- } else {
- $nbMailSend++;
- }
- } else {
- $errorsMsg[] = $cMailFile->error.' : '.$to;
- $error++;
- }
- } else {
- $error++;
- }
- }
- }
- } else {
- $error++;
- }
+ // Sending Mail
+ if ($cMailFile->sendfile())
+ {
+ $actionCommReminder->status = $actionCommReminder::STATUS_DONE;
+ $res = $actionCommReminder->update($user);
+ if ($res < 0)
+ {
+ $errorsMsg[] = "Failed to update status of ActionComm Reminder";
+ $error++;
+ break; // This is to avoid to have this error on all the selected email. If we fails here for one record, it may fails for others. We must solve first.
+ } else {
+ $nbMailSend++;
+ }
+ } else {
+ $errorsMsg[] = $cMailFile->error.' : '.$to;
+ $error++;
+ }
+ } else {
+ $error++;
+ }
+ }
+ }
+ } else {
+ $error++;
+ }
- if (!$error)
- {
- // Delete also very old past events (we do not keep more than 1 month record in past)
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
+ if (!$error)
+ {
+ // Delete also very old past events (we do not keep more than 1 month record in past)
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
$sql .= " WHERE dateremind < '".$this->db->idate($now - (3600 * 24 * 32))."'";
- $resql = $this->db->query($sql);
+ $resql = $this->db->query($sql);
- if (!$resql) {
- $errorsMsg[] = 'Failed to delete old reminders';
- //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind.
- }
- }
+ if (!$resql) {
+ $errorsMsg[] = 'Failed to delete old reminders';
+ //$error++; // If this fails, we must not rollback other SQL requests already done. Never mind.
+ }
+ }
- if (!$error) {
- $this->output = 'Nb of emails sent : '.$nbMailSend;
- $this->db->commit();
- return 0;
- }
- else {
- $this->db->rollback();
- $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error;
- return $error;
- }
- }
+ if (!$error) {
+ $this->output = 'Nb of emails sent : '.$nbMailSend;
+ $this->db->commit();
+ return 0;
+ }
+ else {
+ $this->db->rollback();
+ $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error;
+ return $error;
+ }
+ }
/**
* Udpate the percent value of a event with the given id
diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php
index 64c24c9c8e8..135f91c56f4 100644
--- a/htdocs/comm/action/index.php
+++ b/htdocs/comm/action/index.php
@@ -150,7 +150,7 @@ if (GETPOST("viewlist", 'alpha') || $action == 'show_list')
$param .= '&'.$key.'='.urlencode($val);
}
}
- if (! preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list';
+ if (!preg_match('/action=/', $param)) $param .= ($param ? '&' : '').'action=show_list';
//print $param;
header("Location: ".DOL_URL_ROOT.'/comm/action/list.php?'.$param);
exit;
@@ -398,6 +398,8 @@ if ($action == 'show_month') $tabactive = 'cardmonth';
if ($action == 'show_week') $tabactive = 'cardweek';
if ($action == 'show_day') $tabactive = 'cardday';
if ($action == 'show_list') $tabactive = 'cardlist';
+if ($action == 'show_pertuser') $tabactive = 'cardperuser';
+if ($action == 'show_pertype') $tabactive = 'cardpertype';
$paramnoaction = preg_replace('/action=[a-z_]+/', '', $param);
@@ -636,518 +638,518 @@ dol_syslog("comm/action/index.php", LOG_DEBUG);
$resql = $db->query($sql);
if ($resql)
{
- $num = $db->num_rows($resql);
+ $num = $db->num_rows($resql);
- $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import)
- $i = 0;
- while ($i < $num && $i < $MAXONSAMEPAGE)
- {
- $obj = $db->fetch_object($resql);
+ $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import)
+ $i = 0;
+ while ($i < $num && $i < $MAXONSAMEPAGE)
+ {
+ $obj = $db->fetch_object($resql);
- // Discard auto action if option is on
- if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO')
- {
- $i++;
- continue;
- }
+ // Discard auto action if option is on
+ if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO')
+ {
+ $i++;
+ continue;
+ }
- // Create a new object action
- $event = new ActionComm($db);
+ // Create a new object action
+ $event = new ActionComm($db);
- $event->id = $obj->id;
- $event->ref = $event->id;
+ $event->id = $obj->id;
+ $event->ref = $event->id;
- $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin
- $event->datef = $db->jdate($obj->datep2);
+ $event->datep = $db->jdate($obj->datep); // datep and datef are GMT date. Example: 1970-01-01 01:00:00, jdate will return 0 if TZ of PHP server is Europe/Berlin
+ $event->datef = $db->jdate($obj->datep2);
//var_dump($obj->datep);
- //var_dump($event->datep);
+ //var_dump($event->datep);
- $event->type_code = $obj->type_code;
- $event->type_label = $obj->type_label;
- $event->type_color = $obj->type_color;
+ $event->type_code = $obj->type_code;
+ $event->type_label = $obj->type_label;
+ $event->type_color = $obj->type_color;
- $event->libelle = $obj->label; // deprecated
- $event->label = $obj->label;
- $event->percentage = $obj->percent;
- $event->authorid = $obj->fk_user_author; // user id of creator
- $event->userownerid = $obj->fk_user_action; // user id of owner
- $event->fetch_userassigned(); // This load $event->userassigned
- $event->priority = $obj->priority;
- $event->fulldayevent = $obj->fulldayevent;
- $event->location = $obj->location;
- $event->transparency = $obj->transparency;
- $event->fk_element = $obj->fk_element;
- $event->elementtype = $obj->elementtype;
+ $event->libelle = $obj->label; // deprecated
+ $event->label = $obj->label;
+ $event->percentage = $obj->percent;
+ $event->authorid = $obj->fk_user_author; // user id of creator
+ $event->userownerid = $obj->fk_user_action; // user id of owner
+ $event->fetch_userassigned(); // This load $event->userassigned
+ $event->priority = $obj->priority;
+ $event->fulldayevent = $obj->fulldayevent;
+ $event->location = $obj->location;
+ $event->transparency = $obj->transparency;
+ $event->fk_element = $obj->fk_element;
+ $event->elementtype = $obj->elementtype;
- $event->fk_project = $obj->fk_project;
+ $event->fk_project = $obj->fk_project;
- $event->thirdparty_id = $obj->fk_soc;
- $event->contact_id = $obj->fk_contact;
+ $event->thirdparty_id = $obj->fk_soc;
+ $event->contact_id = $obj->fk_contact;
- // Defined date_start_in_calendar and date_end_in_calendar property
- // They are date start and end of action but modified to not be outside calendar view.
- $event->date_start_in_calendar = $event->datep;
- if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef;
- else $event->date_end_in_calendar = $event->datep;
- // Define ponctual property
- if ($event->date_start_in_calendar == $event->date_end_in_calendar)
- {
- $event->ponctuel = 1;
- }
+ // Defined date_start_in_calendar and date_end_in_calendar property
+ // They are date start and end of action but modified to not be outside calendar view.
+ $event->date_start_in_calendar = $event->datep;
+ if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef;
+ else $event->date_end_in_calendar = $event->datep;
+ // Define ponctual property
+ if ($event->date_start_in_calendar == $event->date_end_in_calendar)
+ {
+ $event->ponctuel = 1;
+ }
- // Check values
- if ($event->date_end_in_calendar < $firstdaytoshow ||
- $event->date_start_in_calendar >= $lastdaytoshow)
- {
- // This record is out of visible range
- } else {
- if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow;
- if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1);
+ // Check values
+ if ($event->date_end_in_calendar < $firstdaytoshow ||
+ $event->date_start_in_calendar >= $lastdaytoshow)
+ {
+ // This record is out of visible range
+ } else {
+ if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow;
+ if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1);
- // Add an entry in actionarray for each day
- $daycursor = $event->date_start_in_calendar;
- $annee = date('Y', $daycursor);
- $mois = date('m', $daycursor);
- $jour = date('d', $daycursor);
+ // Add an entry in actionarray for each day
+ $daycursor = $event->date_start_in_calendar;
+ $annee = date('Y', $daycursor);
+ $mois = date('m', $daycursor);
+ $jour = date('d', $daycursor);
- // Loop on each day covered by action to prepare an index to show on calendar
- $loop = true; $j = 0;
- $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
- do {
- //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.' ';
+ // Loop on each day covered by action to prepare an index to show on calendar
+ $loop = true; $j = 0;
+ $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
+ do {
+ //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.' ';
- $eventarray[$daykey][] = $event;
- $j++;
+ $eventarray[$daykey][] = $event;
+ $j++;
- $daykey += 60 * 60 * 24;
- if ($daykey > $event->date_end_in_calendar) $loop = false;
- } while ($loop);
+ $daykey += 60 * 60 * 24;
+ if ($daykey > $event->date_end_in_calendar) $loop = false;
+ } while ($loop);
- //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef);
- //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array ';
- }
- $i++;
- }
+ //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef);
+ //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array ';
+ }
+ $i++;
+ }
} else {
- dol_print_error($db);
+ dol_print_error($db);
}
// Complete $eventarray with birthdates
if ($showbirthday)
{
- // Add events in array
- $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday';
- $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp';
- $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))';
- $sql .= " AND sp.entity IN (".getEntity('socpeople').")";
- if ($action == 'show_day')
- {
- $sql .= ' AND MONTH(birthday) = '.$month;
- $sql .= ' AND DAY(birthday) = '.$day;
- } else {
- $sql .= ' AND MONTH(birthday) = '.$month;
- }
- $sql .= ' ORDER BY birthday';
+ // Add events in array
+ $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp';
+ $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))';
+ $sql .= " AND sp.entity IN (".getEntity('socpeople').")";
+ if ($action == 'show_day')
+ {
+ $sql .= ' AND MONTH(birthday) = '.$month;
+ $sql .= ' AND DAY(birthday) = '.$day;
+ } else {
+ $sql .= ' AND MONTH(birthday) = '.$month;
+ }
+ $sql .= ' ORDER BY birthday';
- dol_syslog("comm/action/index.php", LOG_DEBUG);
- $resql = $db->query($sql);
- if ($resql)
- {
- $num = $db->num_rows($resql);
- $i = 0;
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
- $event = new ActionComm($db);
+ dol_syslog("comm/action/index.php", LOG_DEBUG);
+ $resql = $db->query($sql);
+ if ($resql)
+ {
+ $num = $db->num_rows($resql);
+ $i = 0;
+ while ($i < $num)
+ {
+ $obj = $db->fetch_object($resql);
+ $event = new ActionComm($db);
- $event->id = $obj->rowid; // We put contact id in action id for birthdays events
- $event->ref = $event->id;
+ $event->id = $obj->rowid; // We put contact id in action id for birthdays events
+ $event->ref = $event->id;
- $datebirth = dol_stringtotime($obj->birthday, 1);
- //print 'ee'.$obj->birthday.'-'.$datebirth;
- $datearray = dol_getdate($datebirth, true);
- $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output
- $event->datef = $event->datep;
- $event->type_code = 'BIRTHDAY';
- $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname);
- $event->percentage = 100;
- $event->fulldayevent = 1;
+ $datebirth = dol_stringtotime($obj->birthday, 1);
+ //print 'ee'.$obj->birthday.'-'.$datebirth;
+ $datearray = dol_getdate($datebirth, true);
+ $event->datep = dol_mktime(0, 0, 0, $datearray['mon'], $datearray['mday'], $year, true); // For full day events, date are also GMT but they wont but converted during output
+ $event->datef = $event->datep;
+ $event->type_code = 'BIRTHDAY';
+ $event->label = $langs->trans("Birthday").' '.dolGetFirstLastname($obj->firstname, $obj->lastname);
+ $event->percentage = 100;
+ $event->fulldayevent = 1;
- $event->date_start_in_calendar = $event->datep;
- $event->date_end_in_calendar = $event->datef;
- $event->ponctuel = 0;
+ $event->date_start_in_calendar = $event->datep;
+ $event->date_end_in_calendar = $event->datef;
+ $event->ponctuel = 0;
- // Add an entry in actionarray for each day
- $daycursor = $event->date_start_in_calendar;
- $annee = date('Y', $daycursor);
- $mois = date('m', $daycursor);
- $jour = date('d', $daycursor);
+ // Add an entry in actionarray for each day
+ $daycursor = $event->date_start_in_calendar;
+ $annee = date('Y', $daycursor);
+ $mois = date('m', $daycursor);
+ $jour = date('d', $daycursor);
- $loop = true;
- $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
- do {
- $eventarray[$daykey][] = $event;
- $daykey += 60 * 60 * 24;
- if ($daykey > $event->date_end_in_calendar) $loop = false;
- } while ($loop);
- $i++;
- }
- } else {
- dol_print_error($db);
- }
+ $loop = true;
+ $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
+ do {
+ $eventarray[$daykey][] = $event;
+ $daykey += 60 * 60 * 24;
+ if ($daykey > $event->date_end_in_calendar) $loop = false;
+ } while ($loop);
+ $i++;
+ }
+ } else {
+ dol_print_error($db);
+ }
}
if ($conf->global->AGENDA_SHOW_HOLIDAYS)
{
- $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status";
- $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
- $sql .= " WHERE u.rowid = x.fk_user";
- $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user)
- $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
+ $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.statut, x.rowid, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.statut as status";
+ $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u";
+ $sql .= " WHERE u.rowid = x.fk_user";
+ $sql .= " AND u.statut = '1'"; // Show only active users (0 = inactive user, 1 = active user)
+ $sql .= " AND (x.statut = '2' OR x.statut = '3')"; // Show only public leaves (2 = leave wait for approval, 3 = leave approved)
- if ($action == 'show_day')
- {
- // Request only leaves for the current selected day
- $sql .= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin";
- } elseif ($action == 'show_week')
- {
- // TODO: Add filter to reduce database request
- } elseif ($action == 'show_month')
- {
- // TODO: Add filter to reduce database request
- }
+ if ($action == 'show_day')
+ {
+ // Request only leaves for the current selected day
+ $sql .= " AND '".$year."-".$month."-".$day."' BETWEEN x.date_debut AND x.date_fin";
+ } elseif ($action == 'show_week')
+ {
+ // TODO: Add filter to reduce database request
+ } elseif ($action == 'show_month')
+ {
+ // TODO: Add filter to reduce database request
+ }
- $resql = $db->query($sql);
- if ($resql)
- {
- $num = $db->num_rows($resql);
- $i = 0;
+ $resql = $db->query($sql);
+ if ($resql)
+ {
+ $num = $db->num_rows($resql);
+ $i = 0;
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
+ while ($i < $num)
+ {
+ $obj = $db->fetch_object($resql);
- $dateStartArray = dol_getdate(dol_stringtotime($obj->date_start, 1), true);
- $dateEndArray = dol_getdate(dol_stringtotime($obj->date_end, 1), true);
+ $dateStartArray = dol_getdate(dol_stringtotime($obj->date_start, 1), true);
+ $dateEndArray = dol_getdate(dol_stringtotime($obj->date_end, 1), true);
- $event = new ActionComm($db);
+ $event = new ActionComm($db);
- // Need the id of the leave object for link to it
- $event->id = $obj->rowid;
- $event->ref = $event->id;
+ // Need the id of the leave object for link to it
+ $event->id = $obj->rowid;
+ $event->ref = $event->id;
- $event->type_code = 'HOLIDAY';
- $event->datep = dol_mktime(0, 0, 0, $dateStartArray['mon'], $dateStartArray['mday'], $dateStartArray['year'], true);
- $event->datef = dol_mktime(0, 0, 0, $dateEndArray['mon'], $dateEndArray['mday'], $dateEndArray['year'], true);
- $event->date_start_in_calendar = $event->datep;
- $event->date_end_in_calendar = $event->datef;
+ $event->type_code = 'HOLIDAY';
+ $event->datep = dol_mktime(0, 0, 0, $dateStartArray['mon'], $dateStartArray['mday'], $dateStartArray['year'], true);
+ $event->datef = dol_mktime(0, 0, 0, $dateEndArray['mon'], $dateEndArray['mday'], $dateEndArray['year'], true);
+ $event->date_start_in_calendar = $event->datep;
+ $event->date_end_in_calendar = $event->datef;
- if ($obj->status == 3)
- {
- // Show no symbol for leave with state "leave approved"
- $event->percentage = -1;
- } elseif ($obj->status == 2)
- {
- // Show TO-DO symbol for leave with state "leave wait for approval"
- $event->percentage = 0;
- }
+ if ($obj->status == 3)
+ {
+ // Show no symbol for leave with state "leave approved"
+ $event->percentage = -1;
+ } elseif ($obj->status == 2)
+ {
+ // Show TO-DO symbol for leave with state "leave wait for approval"
+ $event->percentage = 0;
+ }
- if ($obj->halfday == 1)
- {
- $event->label = $obj->lastname.' ('.$langs->trans("Morning").')';
- } elseif ($obj->halfday == -1)
- {
- $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')';
- } else {
- $event->label = $obj->lastname;
- }
+ if ($obj->halfday == 1)
+ {
+ $event->label = $obj->lastname.' ('.$langs->trans("Morning").')';
+ } elseif ($obj->halfday == -1)
+ {
+ $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')';
+ } else {
+ $event->label = $obj->lastname;
+ }
- $annee = date('Y', $event->date_start_in_calendar);
- $mois = date('m', $event->date_start_in_calendar);
- $jour = date('d', $event->date_start_in_calendar);
- $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
+ $annee = date('Y', $event->date_start_in_calendar);
+ $mois = date('m', $event->date_start_in_calendar);
+ $jour = date('d', $event->date_start_in_calendar);
+ $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
- do {
- $eventarray[$daykey][] = $event;
+ do {
+ $eventarray[$daykey][] = $event;
- $daykey += 60 * 60 * 24;
- } while ($daykey <= $event->date_end_in_calendar);
+ $daykey += 60 * 60 * 24;
+ } while ($daykey <= $event->date_end_in_calendar);
- $i++;
- }
- }
+ $i++;
+ }
+ }
}
// Complete $eventarray with external import Ical
if (count($listofextcals))
{
- require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php';
- foreach ($listofextcals as $extcal)
- {
- $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics
- $namecal = $extcal['name'];
- $offsettz = $extcal['offsettz'];
- $colorcal = $extcal['color'];
- $buggedfile = $extcal['buggedfile'];
- //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile;
- $ical = new ICal();
- $ical->parse($url);
+ require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php';
+ foreach ($listofextcals as $extcal)
+ {
+ $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics
+ $namecal = $extcal['name'];
+ $offsettz = $extcal['offsettz'];
+ $colorcal = $extcal['color'];
+ $buggedfile = $extcal['buggedfile'];
+ //print "url=".$url." namecal=".$namecal." colorcal=".$colorcal." buggedfile=".$buggedfile;
+ $ical = new ICal();
+ $ical->parse($url);
- // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ...
- //var_dump($ical->cal); exit;
- $icalevents = array();
- if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT']
- if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY']
+ // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ...
+ //var_dump($ical->cal); exit;
+ $icalevents = array();
+ if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT']
+ if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY']
- if (count($icalevents) > 0)
- {
- // Duplicate all repeatable events into new entries
- $moreicalevents = array();
- foreach ($icalevents as $icalevent)
- {
- if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event
- {
- //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow;
- //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1);
- if ($icalevent['DTSTART;VALUE=DATE']) //fullday event
- {
- $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1);
- $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day
- } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime']))
- {
- $datecurstart = $icalevent['DTSTART']['unixtime'];
- $datecurend = $icalevent['DTEND']['unixtime'];
- if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart)
- {
- //var_dump($ical->cal);
- $tmpcurstart = $datecurstart;
- $tmpcurend = $datecurend;
- $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART'];
- $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART'];
- //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']);
- // Edit datecurstart and datecurend
- if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36;
- else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36;
- if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36;
- else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36;
- }
- // datecurstart and datecurend are now GMT date
- //var_dump($datecurstart); var_dump($datecurend); exit;
- } else {
- // Not a recongized record
- dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR);
- continue;
- }
- //print 'xx'.$datecurstart;exit;
+ if (count($icalevents) > 0)
+ {
+ // Duplicate all repeatable events into new entries
+ $moreicalevents = array();
+ foreach ($icalevents as $icalevent)
+ {
+ if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event
+ {
+ //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow;
+ //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1);
+ if ($icalevent['DTSTART;VALUE=DATE']) //fullday event
+ {
+ $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1);
+ $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day
+ } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime']))
+ {
+ $datecurstart = $icalevent['DTSTART']['unixtime'];
+ $datecurend = $icalevent['DTEND']['unixtime'];
+ if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart)
+ {
+ //var_dump($ical->cal);
+ $tmpcurstart = $datecurstart;
+ $tmpcurend = $datecurend;
+ $tmpdaylightstart = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['DAYLIGHT']['DTSTART'];
+ $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART'];
+ //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']);
+ // Edit datecurstart and datecurend
+ if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36;
+ else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36;
+ if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36;
+ else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36;
+ }
+ // datecurstart and datecurend are now GMT date
+ //var_dump($datecurstart); var_dump($datecurend); exit;
+ } else {
+ // Not a recongized record
+ dol_syslog("Found a not recognized repeatable record with unknown date start", LOG_ERR);
+ continue;
+ }
+ //print 'xx'.$datecurstart;exit;
- $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']);
- $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1);
- $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT'];
- if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show
- if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show
+ $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']);
+ $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1);
+ $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT'];
+ if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show
+ if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show
- $numofevent = 0;
- while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat)))
- {
- if ($datecurend >= $firstdaytoshow) // We add event
- {
- $newevent = $icalevent;
- unset($newevent['RRULE']);
- if ($icalevent['DTSTART;VALUE=DATE'])
- {
- $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d');
- $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d');
- } else {
- $newevent['DTSTART'] = $datecurstart;
- $newevent['DTEND'] = $datecurend;
- }
- $moreicalevents[] = $newevent;
- }
- // Jump on next occurence
- $numofevent++;
- $savdatecurstart = $datecurstart;
- if ($icalevent['RRULE']['FREQ'] == 'DAILY')
- {
- $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd');
- $datecurend = dol_time_plus_duree($datecurend, $interval, 'd');
- }
- if ($icalevent['RRULE']['FREQ'] == 'WEEKLY')
- {
- $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w');
- $datecurend = dol_time_plus_duree($datecurend, $interval, 'w');
- } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY')
- {
- $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm');
- $datecurend = dol_time_plus_duree($datecurend, $interval, 'm');
- } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY')
- {
- $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y');
- $datecurend = dol_time_plus_duree($datecurend, $interval, 'y');
- }
- // Test to avoid infinite loop ($datecurstart must increase)
- if ($savdatecurstart >= $datecurstart)
- {
- dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR);
- $datecurstart += 3600 * 24 * 7;
- $datecurend += 3600 * 24 * 7;
- }
- }
- }
- }
- $icalevents = array_merge($icalevents, $moreicalevents);
+ $numofevent = 0;
+ while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat)))
+ {
+ if ($datecurend >= $firstdaytoshow) // We add event
+ {
+ $newevent = $icalevent;
+ unset($newevent['RRULE']);
+ if ($icalevent['DTSTART;VALUE=DATE'])
+ {
+ $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d');
+ $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d');
+ } else {
+ $newevent['DTSTART'] = $datecurstart;
+ $newevent['DTEND'] = $datecurend;
+ }
+ $moreicalevents[] = $newevent;
+ }
+ // Jump on next occurence
+ $numofevent++;
+ $savdatecurstart = $datecurstart;
+ if ($icalevent['RRULE']['FREQ'] == 'DAILY')
+ {
+ $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd');
+ $datecurend = dol_time_plus_duree($datecurend, $interval, 'd');
+ }
+ if ($icalevent['RRULE']['FREQ'] == 'WEEKLY')
+ {
+ $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w');
+ $datecurend = dol_time_plus_duree($datecurend, $interval, 'w');
+ } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY')
+ {
+ $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm');
+ $datecurend = dol_time_plus_duree($datecurend, $interval, 'm');
+ } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY')
+ {
+ $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y');
+ $datecurend = dol_time_plus_duree($datecurend, $interval, 'y');
+ }
+ // Test to avoid infinite loop ($datecurstart must increase)
+ if ($savdatecurstart >= $datecurstart)
+ {
+ dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR);
+ $datecurstart += 3600 * 24 * 7;
+ $datecurend += 3600 * 24 * 7;
+ }
+ }
+ }
+ }
+ $icalevents = array_merge($icalevents, $moreicalevents);
- // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray
- foreach ($icalevents as $icalevent)
- {
- //var_dump($icalevent);
+ // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray
+ foreach ($icalevents as $icalevent)
+ {
+ //var_dump($icalevent);
- //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).' ';exit;
- if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule.
+ //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).' ';exit;
+ if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule.
- // Create a new object action
- $event = new ActionComm($db);
- $addevent = false;
- if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event
- {
- // For full day events, date are also GMT but they wont but converted using tz during output
- $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1);
- $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day
- //print 'x'.$datestart.'-'.$dateend;exit;
- //print dol_print_date($dateend,'dayhour','gmt');
- $event->fulldayevent = 1;
- $addevent = true;
- } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch)
- {
- $datestart = $icalevent['DTSTART'];
- $dateend = $icalevent['DTEND'];
+ // Create a new object action
+ $event = new ActionComm($db);
+ $addevent = false;
+ if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event
+ {
+ // For full day events, date are also GMT but they wont but converted using tz during output
+ $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1);
+ $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day
+ //print 'x'.$datestart.'-'.$dateend;exit;
+ //print dol_print_date($dateend,'dayhour','gmt');
+ $event->fulldayevent = 1;
+ $addevent = true;
+ } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch)
+ {
+ $datestart = $icalevent['DTSTART'];
+ $dateend = $icalevent['DTEND'];
- $datestart += +($offsettz * 3600);
- $dateend += +($offsettz * 3600);
+ $datestart += +($offsettz * 3600);
+ $dateend += +($offsettz * 3600);
- $addevent = true;
- //var_dump($offsettz);
- //var_dump(dol_print_date($datestart, 'dayhour', 'gmt'));
- } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind)
- {
- $datestart = $icalevent['DTSTART']['unixtime'];
- $dateend = $icalevent['DTEND']['unixtime'];
+ $addevent = true;
+ //var_dump($offsettz);
+ //var_dump(dol_print_date($datestart, 'dayhour', 'gmt'));
+ } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind)
+ {
+ $datestart = $icalevent['DTSTART']['unixtime'];
+ $dateend = $icalevent['DTEND']['unixtime'];
- $datestart += +($offsettz * 3600);
- $dateend += +($offsettz * 3600);
+ $datestart += +($offsettz * 3600);
+ $dateend += +($offsettz * 3600);
- // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight'
- if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2
- {
- // TODO
- }
- // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind)
- if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer
- {
- $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID']));
- $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID']));
- $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs);
- $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze);
+ // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight'
+ if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2
+ {
+ // TODO
+ }
+ // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind)
+ if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer
+ {
+ $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID']));
+ $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID']));
+ $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs);
+ $localdte = new DateTime(dol_print_date($dateend, 'dayrfc', 'gmt'), $localtze);
$tmps = -1 * $localtzs->getOffset($localdts);
$tmpe = -1 * $localtze->getOffset($localdte);
$datestart += $tmps;
$dateend += $tmpe;
//var_dump($datestart);
- }
- $addevent = true;
- }
+ }
+ $addevent = true;
+ }
- if ($addevent)
- {
- $event->id = $icalevent['UID'];
- $event->ref = $event->id;
+ if ($addevent)
+ {
+ $event->id = $icalevent['UID'];
+ $event->ref = $event->id;
- $userId = $userstatic->findUserIdByEmail($namecal);
- if (!empty($userId) && $userId > 0)
- {
- $event->userassigned[$userId] = $userId;
- $event->percentage = -1;
- }
- else {
- $event->type_code = "ICALEVENT";
- }
+ $userId = $userstatic->findUserIdByEmail($namecal);
+ if (!empty($userId) && $userId > 0)
+ {
+ $event->userassigned[$userId] = $userId;
+ $event->percentage = -1;
+ }
+ else {
+ $event->type_code = "ICALEVENT";
+ }
- $event->icalname = $namecal;
- $event->icalcolor = $colorcal;
- $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output.
- $event->datep = $datestart + $usertime;
- $event->datef = $dateend + $usertime;
+ $event->icalname = $namecal;
+ $event->icalcolor = $colorcal;
+ $usertime = 0; // We dont modify date because we want to have date into memory datep and datef stored as GMT date. Compensation will be done during output.
+ $event->datep = $datestart + $usertime;
+ $event->datef = $dateend + $usertime;
- if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY'];
- elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1);
- else $event->label = $langs->trans("ExtSiteNoLabel");
+ if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY'];
+ elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1);
+ else $event->label = $langs->trans("ExtSiteNoLabel");
- // Priority (see https://www.kanzaki.com/docs/ical/priority.html)
- // LOW = 0 to 4
- // MEDIUM = 5
- // HIGH = 6 to 9
- if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY'];
+ // Priority (see https://www.kanzaki.com/docs/ical/priority.html)
+ // LOW = 0 to 4
+ // MEDIUM = 5
+ // HIGH = 6 to 9
+ if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY'];
- // Transparency (see https://www.kanzaki.com/docs/ical/transp.html)
- if ($icalevent['TRANSP'])
- {
- if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free
- if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy
+ // Transparency (see https://www.kanzaki.com/docs/ical/transp.html)
+ if ($icalevent['TRANSP'])
+ {
+ if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free
+ if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy
- // TODO: MS outlook states
- // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free
- // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:OPAQUE => Work another place
- // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE => With reservations
- // X-MICROSOFT-CDO-BUSYSTATUS:BUSY + TRANSP:OPAQUE => Busy
- // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site
- }
+ // TODO: MS outlook states
+ // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free
+ // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:OPAQUE => Work another place
+ // X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE + TRANSP:OPAQUE => With reservations
+ // X-MICROSOFT-CDO-BUSYSTATUS:BUSY + TRANSP:OPAQUE => Busy
+ // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site
+ }
- if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION'];
+ if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION'];
- $event->date_start_in_calendar = $event->datep;
+ $event->date_start_in_calendar = $event->datep;
- if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef;
- else $event->date_end_in_calendar = $event->datep;
+ if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef;
+ else $event->date_end_in_calendar = $event->datep;
- // Define ponctual property
- if ($event->date_start_in_calendar == $event->date_end_in_calendar)
- {
- $event->ponctuel = 1;
- //print 'x'.$datestart.'-'.$dateend;exit;
- }
+ // Define ponctual property
+ if ($event->date_start_in_calendar == $event->date_end_in_calendar)
+ {
+ $event->ponctuel = 1;
+ //print 'x'.$datestart.'-'.$dateend;exit;
+ }
- // Add event into $eventarray if date range are ok.
- if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow)
- {
- //print 'x'.$datestart.'-'.$dateend;exit;
- //print 'x'.$datestart.'-'.$dateend;exit;
- //print 'x'.$datestart.'-'.$dateend;exit;
- // This record is out of visible range
- } else {
- if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow;
- if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1);
+ // Add event into $eventarray if date range are ok.
+ if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow)
+ {
+ //print 'x'.$datestart.'-'.$dateend;exit;
+ //print 'x'.$datestart.'-'.$dateend;exit;
+ //print 'x'.$datestart.'-'.$dateend;exit;
+ // This record is out of visible range
+ } else {
+ if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow;
+ if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1);
- // Add an entry in actionarray for each day
- $daycursor = $event->date_start_in_calendar;
- $annee = date('Y', $daycursor);
- $mois = date('m', $daycursor);
- $jour = date('d', $daycursor);
+ // Add an entry in actionarray for each day
+ $daycursor = $event->date_start_in_calendar;
+ $annee = date('Y', $daycursor);
+ $mois = date('m', $daycursor);
+ $jour = date('d', $daycursor);
- // Loop on each day covered by action to prepare an index to show on calendar
- $loop = true; $j = 0;
- // daykey must be date that represent day box in calendar so must be a user time
- $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
- $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0);
- do {
- //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' ';
- $eventarray[$daykey][] = $event;
- $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day
- if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false;
- } while ($loop);
- }
- }
- }
- }
- }
+ // Loop on each day covered by action to prepare an index to show on calendar
+ $loop = true; $j = 0;
+ // daykey must be date that represent day box in calendar so must be a user time
+ $daykey = dol_mktime(0, 0, 0, $mois, $jour, $annee);
+ $daykeygmt = dol_mktime(0, 0, 0, $mois, $jour, $annee, true, 0);
+ do {
+ //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' ';
+ $eventarray[$daykey][] = $event;
+ $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day
+ if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false;
+ } while ($loop);
+ }
+ }
+ }
+ }
+ }
}
@@ -1192,48 +1194,48 @@ print $s;
if (empty($action) || $action == 'show_month') // View by month
{
- $newparam = $param; // newparam is for birthday links
- $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done
- $newparam = preg_replace('/action=show_month&?/i', '', $newparam);
- $newparam = preg_replace('/action=show_week&?/i', '', $newparam);
- $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter
- $newparam .= '&viewcal=1';
+ $newparam = $param; // newparam is for birthday links
+ $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done
+ $newparam = preg_replace('/action=show_month&?/i', '', $newparam);
+ $newparam = preg_replace('/action=show_week&?/i', '', $newparam);
+ $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/viewcal=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter
+ $newparam .= '&viewcal=1';
- print '';
- print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
- print '
';
+ print '';
+ print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
+ print '
';
- print '';
- print '
';
- print ' ';
+ print '';
+ print '
';
+ print ' ';
// Column title of weeks numbers
echo ' # ';
- $i = 0;
- while ($i < 7)
- {
- print ' ';
- $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7);
- if (!empty($conf->dol_optimize_smallscreen))
- {
- $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin');
- print $langs->trans($labelshort[$numdayinweek]);
- } else print $langs->trans("Day".$numdayinweek);
- print ' '."\n";
- $i++;
- }
- echo ' '."\n";
+ $i = 0;
+ while ($i < 7)
+ {
+ print ' ';
+ $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7);
+ if (!empty($conf->dol_optimize_smallscreen))
+ {
+ $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin');
+ print $langs->trans($labelshort[$numdayinweek]);
+ } else print $langs->trans("Day".$numdayinweek);
+ print ' '."\n";
+ $i++;
+ }
+ echo ' '."\n";
- $todayarray = dol_getdate($now, 'fast');
- $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']);
+ $todayarray = dol_getdate($now, 'fast');
+ $todaytms = dol_mktime(0, 0, 0, $todayarray['mon'], $todayarray['mday'], $todayarray['year']);
- // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month)
- //var_dump($eventarray);
- for ($iter_week = 0; $iter_week < 6; $iter_week++) {
- echo " \n";
+ // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month)
+ //var_dump($eventarray);
+ for ($iter_week = 0; $iter_week < 6; $iter_week++) {
+ echo " \n";
// Get date of the current day, format 'yyyy-mm-dd'
if ($tmpday <= 0) // If number of the current day is in previous month
{
@@ -1252,130 +1254,130 @@ if (empty($action) || $action == 'show_month') // View by month
// Show the week number, and define column width
echo ' '.$numweek0.' ';
- for ($iter_day = 0; $iter_day < 7; $iter_day++) {
- if ($tmpday <= 0) {
- /* Show days before the beginning of the current month (previous month) */
- $style = 'cal_other_month cal_past';
- if ($iter_day == 6) $style .= ' cal_other_month_right';
- echo ' ';
- show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
- echo " \n";
- } elseif ($tmpday <= $max_day_in_month) {
- /* Show days of the current month */
- $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year);
- $style = 'cal_current_month';
- if ($iter_day == 6) $style .= ' cal_current_month_right';
- $today = 0;
- if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1;
- if ($today) $style = 'cal_today';
- if ($curtime < $todaytms) $style .= ' cal_past';
+ for ($iter_day = 0; $iter_day < 7; $iter_day++) {
+ if ($tmpday <= 0) {
+ /* Show days before the beginning of the current month (previous month) */
+ $style = 'cal_other_month cal_past';
+ if ($iter_day == 6) $style .= ' cal_other_month_right';
+ echo ' ';
+ show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
+ echo " \n";
+ } elseif ($tmpday <= $max_day_in_month) {
+ /* Show days of the current month */
+ $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year);
+ $style = 'cal_current_month';
+ if ($iter_day == 6) $style .= ' cal_current_month_right';
+ $today = 0;
+ if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1;
+ if ($today) $style = 'cal_today';
+ if ($curtime < $todaytms) $style .= ' cal_past';
//var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style);
- echo ' ';
- show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
- echo " \n";
- } else {
- /* Show days after the current month (next month) */
- $style = 'cal_other_month';
- if ($iter_day == 6) $style .= ' cal_other_month_right';
- echo ' ';
- show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
- echo " \n";
- }
- $tmpday++;
- }
- echo " \n";
- }
- print "
\n";
+ echo '
';
+ show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
+ echo " \n";
+ } else {
+ /* Show days after the current month (next month) */
+ $style = 'cal_other_month';
+ if ($iter_day == 6) $style .= ' cal_other_month_right';
+ echo '
';
+ show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam);
+ echo " \n";
+ }
+ $tmpday++;
+ }
+ echo "
\n";
+ }
+ print "
\n";
print '
';
print ' ';
print ' ';
print ' ';
} elseif ($action == 'show_week') {
- // View by week
- $newparam = $param; // newparam is for birthday links
- $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done
- $newparam = preg_replace('/action=show_month&?/i', '', $newparam);
- $newparam = preg_replace('/action=show_week&?/i', '', $newparam);
- $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam);
- $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter
- $newparam .= '&viewweek=1';
+ // View by week
+ $newparam = $param; // newparam is for birthday links
+ $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done
+ $newparam = preg_replace('/action=show_month&?/i', '', $newparam);
+ $newparam = preg_replace('/action=show_week&?/i', '', $newparam);
+ $newparam = preg_replace('/day=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/month=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/year=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/viewweek=[0-9]+&?/i', '', $newparam);
+ $newparam = preg_replace('/showbirthday_=/i', 'showbirthday=', $newparam); // Restore correct parameter
+ $newparam .= '&viewweek=1';
- print '';
- print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
- print '
';
+ print '';
+ print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
+ print '
';
- print '';
- print '
';
- print ' ';
- $i = 0;
- while ($i < 7) {
- echo ' '.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))." \n";
- $i++;
- }
- echo " \n";
+ print '';
+ print '
';
+ print ' ';
+ $i = 0;
+ while ($i < 7) {
+ echo ' '.$langs->trans("Day".(($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7))." \n";
+ $i++;
+ }
+ echo " \n";
- echo " \n";
+ echo " \n";
- for ($iter_day = 0; $iter_day < 7; $iter_day++) {
- // Show days of the current week
+ for ($iter_day = 0; $iter_day < 7; $iter_day++) {
+ // Show days of the current week
$curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd');
$tmparray = dol_getdate($curtime, true);
$tmpday = $tmparray['mday'];
$tmpmonth = $tmparray['mon'];
$tmpyear = $tmparray['year'];
- $style = 'cal_current_month';
- if ($iter_day == 6) $style .= ' cal_other_month_right';
- $today = 0;
- $todayarray = dol_getdate($now, 'fast');
- if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1;
- if ($today) $style = 'cal_today';
+ $style = 'cal_current_month';
+ if ($iter_day == 6) $style .= ' cal_other_month_right';
+ $today = 0;
+ $todayarray = dol_getdate($now, 'fast');
+ if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1;
+ if ($today) $style = 'cal_today';
- echo ' ';
- show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300);
- echo " \n";
- }
- echo " \n";
+ echo ' ';
+ show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300);
+ echo " \n";
+ }
+ echo " \n";
- print "
\n";
+ print "
\n";
print '
';
- echo ' ';
- echo ' ';
- echo ' ';
+ echo ' ';
+ echo ' ';
+ echo ' ';
} else // View by day
{
- $newparam = $param; // newparam is for birthday links
- $newparam = preg_replace('/action=show_month&?/i', '', $newparam);
- $newparam = preg_replace('/action=show_week&?/i', '', $newparam);
- $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam);
- $newparam .= '&viewday=1';
- // Code to show just one day
- $style = 'cal_current_month cal_current_month_oneday';
- $today = 0;
- $todayarray = dol_getdate($now, 'fast');
- if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1;
- //if ($today) $style='cal_today';
+ $newparam = $param; // newparam is for birthday links
+ $newparam = preg_replace('/action=show_month&?/i', '', $newparam);
+ $newparam = preg_replace('/action=show_week&?/i', '', $newparam);
+ $newparam = preg_replace('/viewday=[0-9]+&?/i', '', $newparam);
+ $newparam .= '&viewday=1';
+ // Code to show just one day
+ $style = 'cal_current_month cal_current_month_oneday';
+ $today = 0;
+ $todayarray = dol_getdate($now, 'fast');
+ if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1;
+ //if ($today) $style='cal_today';
- $timestamp = dol_mktime(12, 0, 0, $month, $day, $year);
- $arraytimestamp = dol_getdate($timestamp);
+ $timestamp = dol_mktime(12, 0, 0, $month, $day, $year);
+ $arraytimestamp = dol_getdate($timestamp);
- print '';
- print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
- print '
';
+ print '';
+ print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid);
+ print '
';
- print '';
- echo '
';
+ print '';
+ echo '
';
- echo ' ';
- echo ' '.$langs->trans("Day".$arraytimestamp['wday'])." \n";
- echo " \n";
+ echo ' ';
+ echo ' '.$langs->trans("Day".$arraytimestamp['wday'])." \n";
+ echo " \n";
- /*
+ /*
echo ' ';
echo '
';
echo '
';
@@ -1460,401 +1462,401 @@ $db->close();
*/
function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint = 0, $maxnbofchar = 16, $newparam = '', $showinfo = 0, $minheight = 60, $nonew = 0)
{
- global $user, $conf, $langs;
- global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form
- global $theme_datacolor;
- global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused;
+ global $user, $conf, $langs;
+ global $action, $filter, $filtert, $status, $actioncode, $usergroup; // Filters used into search form
+ global $theme_datacolor;
+ global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused;
- $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day);
+ $dateint = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day);
- print "\n";
+ print "\n";
- // Line with title of day
- $curtime = dol_mktime(0, 0, 0, $month, $day, $year);
- print '
'."\n";
+ // Line with title of day
+ $curtime = dol_mktime(0, 0, 0, $month, $day, $year);
+ print '
'."\n";
- if ($nonew <= 0)
- {
- print '
';
- if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create)
- {
- $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year;
+ if ($nonew <= 0)
+ {
+ print '
'."\n";
- }
+ //$param='month='.$monthshown.'&year='.$year;
+ $hourminsec = '100000';
+ print '
';
+ print img_picto($langs->trans("NewAction"), 'edit_add.png');
+ print ' ';
+ }
+ print '
'."\n";
+ }
- if ($nonew < 0)
- {
- print '
';
- return;
- }
+ if ($nonew < 0)
+ {
+ print '
';
+ return;
+ }
- // Line with td contains all div of each events
- print '
';
- print '
';
+ // Line with td contains all div of each events
+ print '
';
+ print '
';
- //$curtime = dol_mktime (0, 0, 0, $month, $day, $year);
- $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array();
- $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day);
+ //$curtime = dol_mktime (0, 0, 0, $month, $day, $year);
+ $i = 0; $numother = 0; $numbirthday = 0; $numical = 0; $numicals = array();
+ $ymd = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $day);
- $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0
- $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ...
+ $colorindexused[$user->id] = 0; // Color index for current user (user->id) is always 0
+ $nextindextouse = is_array($colorindexused) ?count($colorindexused) : 0; // At first run this is 0, so fist user has 0, next 1, ...
//var_dump($colorindexused);
- foreach ($eventarray as $daykey => $notused)
- {
- $annee = date('Y', $daykey);
- $mois = date('m', $daykey);
- $jour = date('d', $daykey);
- if ($day == $jour && $month == $mois && $year == $annee)
- {
- foreach ($eventarray[$daykey] as $index => $event)
- {
- if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA))
- {
- $keysofuserassigned = array_keys($event->userassigned);
- $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar);
+ foreach ($eventarray as $daykey => $notused)
+ {
+ $annee = date('Y', $daykey);
+ $mois = date('m', $daykey);
+ $jour = date('d', $daykey);
+ if ($day == $jour && $month == $mois && $year == $annee)
+ {
+ foreach ($eventarray[$daykey] as $index => $event)
+ {
+ if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA))
+ {
+ $keysofuserassigned = array_keys($event->userassigned);
+ $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar);
- // Define $color (Hex string like '0088FF') and $cssclass of event
- $color = -1; $cssclass = ''; $colorindex = -1;
- if (in_array($user->id, $keysofuserassigned))
- {
- $cssclass = 'family_mytasks';
+ // Define $color (Hex string like '0088FF') and $cssclass of event
+ $color = -1; $cssclass = ''; $colorindex = -1;
+ if (in_array($user->id, $keysofuserassigned))
+ {
+ $cssclass = 'family_mytasks';
- if (empty($cacheusers[$event->userownerid]))
- {
- $newuser = new User($db);
- $newuser->fetch($event->userownerid);
- $cacheusers[$event->userownerid] = $newuser;
- }
- //var_dump($cacheusers[$event->userownerid]->color);
+ if (empty($cacheusers[$event->userownerid]))
+ {
+ $newuser = new User($db);
+ $newuser->fetch($event->userownerid);
+ $cacheusers[$event->userownerid] = $newuser;
+ }
+ //var_dump($cacheusers[$event->userownerid]->color);
- // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event)
- if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color;
- } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file
- {
- $numical++;
- if (!empty($event->icalname)) {
- if (!isset($numicals[dol_string_nospecial($event->icalname)])) {
- $numicals[dol_string_nospecial($event->icalname)] = 0;
- }
- $numicals[dol_string_nospecial($event->icalname)]++;
- }
+ // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event)
+ if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color;
+ } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file
+ {
+ $numical++;
+ if (!empty($event->icalname)) {
+ if (!isset($numicals[dol_string_nospecial($event->icalname)])) {
+ $numicals[dol_string_nospecial($event->icalname)] = 0;
+ }
+ $numicals[dol_string_nospecial($event->icalname)]++;
+ }
- $color = ($event->icalcolor ? $event->icalcolor : -1);
- $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other');
- } elseif ($event->type_code == 'BIRTHDAY')
- {
- $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]);
- } else {
- $numother++;
- $color = ($event->icalcolor ? $event->icalcolor : -1);
- $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other');
+ $color = ($event->icalcolor ? $event->icalcolor : -1);
+ $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other');
+ } elseif ($event->type_code == 'BIRTHDAY')
+ {
+ $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday unmovable'; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]);
+ } else {
+ $numother++;
+ $color = ($event->icalcolor ? $event->icalcolor : -1);
+ $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other');
- if (empty($cacheusers[$event->userownerid]))
- {
- $newuser = new User($db);
- $newuser->fetch($event->userownerid);
- $cacheusers[$event->userownerid] = $newuser;
- }
- //var_dump($cacheusers[$event->userownerid]->color);
+ if (empty($cacheusers[$event->userownerid]))
+ {
+ $newuser = new User($db);
+ $newuser->fetch($event->userownerid);
+ $cacheusers[$event->userownerid] = $newuser;
+ }
+ //var_dump($cacheusers[$event->userownerid]->color);
- // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event)
- if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color;
- }
+ // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event)
+ if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color;
+ }
- if ($color < 0) // Color was not set on user card. Set color according to color index.
- {
- // Define color index if not yet defined
- $idusertouse = ($event->userownerid ? $event->userownerid : 0);
- if (isset($colorindexused[$idusertouse]))
- {
- $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user
- } else {
- $colorindex = $nextindextouse;
- $colorindexused[$idusertouse] = $colorindex;
- if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color
- }
- //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
';
- // Define color
- $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]);
- }
- $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd;
+ if ($color < 0) // Color was not set on user card. Set color according to color index.
+ {
+ // Define color index if not yet defined
+ $idusertouse = ($event->userownerid ? $event->userownerid : 0);
+ if (isset($colorindexused[$idusertouse]))
+ {
+ $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user
+ } else {
+ $colorindex = $nextindextouse;
+ $colorindexused[$idusertouse] = $colorindex;
+ if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color
+ }
+ //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
';
+ // Define color
+ $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]);
+ }
+ $cssclass = $cssclass.' '.$cssclass.'_day_'.$ymd;
- // Defined style to disable drag and drop feature
- if ($event->type_code == 'AC_OTH_AUTO')
- {
- $cssclass .= " unmovable";
- } elseif ($event->type_code == 'ICALEVENT')
- {
- $cssclass .= " unmovable";
- } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) {
- $tmpyearend = date('Y', $event->date_end_in_calendar);
- $tmpmonthend = date('m', $event->date_end_in_calendar);
- $tmpdayend = date('d', $event->date_end_in_calendar);
- if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour)
- {
- $cssclass .= " unmovable";
- }
- } else {
- if ($user->rights->agenda->allactions->create ||
- (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create))
- {
- $cssclass .= " movable cursormove";
- } else {
- $cssclass .= " unmovable";
- }
- }
+ // Defined style to disable drag and drop feature
+ if ($event->type_code == 'AC_OTH_AUTO')
+ {
+ $cssclass .= " unmovable";
+ } elseif ($event->type_code == 'ICALEVENT')
+ {
+ $cssclass .= " unmovable";
+ } elseif ($event->date_end_in_calendar && date('Ymd', $event->date_start_in_calendar) != date('Ymd', $event->date_end_in_calendar)) {
+ $tmpyearend = date('Y', $event->date_end_in_calendar);
+ $tmpmonthend = date('m', $event->date_end_in_calendar);
+ $tmpdayend = date('d', $event->date_end_in_calendar);
+ if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour)
+ {
+ $cssclass .= " unmovable";
+ }
+ } else {
+ if ($user->rights->agenda->allactions->create ||
+ (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create))
+ {
+ $cssclass .= " movable cursormove";
+ } else {
+ $cssclass .= " unmovable";
+ }
+ }
- $h = ''; $nowrapontd = 1;
- if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; }
- if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; }
+ $h = ''; $nowrapontd = 1;
+ if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; }
+ if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; }
- // Show rect of event
- print "\n";
- print ''."\n";
- print '
';
+ // Show rect of event
+ print "\n";
+ print ''."\n";
+ print '
';
- //var_dump($event->userassigned);
- //var_dump($event->transparency);
- print '
';
- print '';
- print '';
+ //var_dump($event->userassigned);
+ //var_dump($event->transparency);
+ print '';
+ print '';
+ print '';
- $daterange = '';
+ $daterange = '';
- if ($event->type_code == 'BIRTHDAY') // It's a birthday
- {
- print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact');
- } elseif ($event->type_code == 'HOLIDAY')
- {
- print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'holiday', 'user');
- } elseif ($event->type_code != 'BIRTHDAY' && $event->type_code != 'HOLIDAY')
- {
- // Picto
- if (empty($event->fulldayevent))
- {
- //print $event->getNomUrl(2).' ';
- }
+ if ($event->type_code == 'BIRTHDAY') // It's a birthday
+ {
+ print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'birthday', 'contact');
+ } elseif ($event->type_code == 'HOLIDAY')
+ {
+ print $event->getNomUrl(1, $maxnbofchar, 'cal_event', 'holiday', 'user');
+ } elseif ($event->type_code != 'BIRTHDAY' && $event->type_code != 'HOLIDAY')
+ {
+ // Picto
+ if (empty($event->fulldayevent))
+ {
+ //print $event->getNomUrl(2).' ';
+ }
- // Date
- if (empty($event->fulldayevent))
- {
- // Show hours (start ... end)
- $tmpyearstart = date('Y', $event->date_start_in_calendar);
- $tmpmonthstart = date('m', $event->date_start_in_calendar);
- $tmpdaystart = date('d', $event->date_start_in_calendar);
- $tmpyearend = date('Y', $event->date_end_in_calendar);
- $tmpmonthend = date('m', $event->date_end_in_calendar);
- $tmpdayend = date('d', $event->date_end_in_calendar);
- // Hour start
- if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour)
- {
- $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user
- if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar)
- {
- if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend)
- $daterange .= '-';
- //else
- //print '...';
- }
- }
- if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar)
- {
- if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend)
- {
- $daterange .= '...';
- }
- }
- // Hour end
- if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar)
- {
- if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour)
- $daterange .= dol_print_date($event->date_end_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user
- }
- } else {
- if ($showinfo)
- {
- print $langs->trans("EventOnFullDay")." \n";
- }
- }
+ // Date
+ if (empty($event->fulldayevent))
+ {
+ // Show hours (start ... end)
+ $tmpyearstart = date('Y', $event->date_start_in_calendar);
+ $tmpmonthstart = date('m', $event->date_start_in_calendar);
+ $tmpdaystart = date('d', $event->date_start_in_calendar);
+ $tmpyearend = date('Y', $event->date_end_in_calendar);
+ $tmpmonthend = date('m', $event->date_end_in_calendar);
+ $tmpdayend = date('d', $event->date_end_in_calendar);
+ // Hour start
+ if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour)
+ {
+ $daterange .= dol_print_date($event->date_start_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user
+ if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar)
+ {
+ if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend)
+ $daterange .= '-';
+ //else
+ //print '...';
+ }
+ }
+ if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar)
+ {
+ if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend)
+ {
+ $daterange .= '...';
+ }
+ }
+ // Hour end
+ if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar)
+ {
+ if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour)
+ $daterange .= dol_print_date($event->date_end_in_calendar, 'hour'); // Il faudrait utiliser ici tzuser, mais si on ne peut pas car qd on rentre un date dans fiche action, en input la conversion local->gmt se base sur le TZ server et non user
+ }
+ } else {
+ if ($showinfo)
+ {
+ print $langs->trans("EventOnFullDay")." \n";
+ }
+ }
- // Show title
- $titletoshow = $daterange;
- $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle);
+ // Show title
+ $titletoshow = $daterange;
+ $titletoshow .= ($titletoshow ? ' ' : '').($event->label ? $event->label : $event->libelle);
- if ($event->type_code != 'ICALEVENT') {
- $savlabel = $event->label ? $event->label : $event->libelle;
- $event->label = $titletoshow;
- $event->libelle = $titletoshow;
- // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user.
- $titletoshow = $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0);
- $event->label = $savlabel;
- $event->libelle = $savlabel;
- }
+ if ($event->type_code != 'ICALEVENT') {
+ $savlabel = $event->label ? $event->label : $event->libelle;
+ $event->label = $titletoshow;
+ $event->libelle = $titletoshow;
+ // Note: List of users are inside $event->userassigned. Link may be clickable depending on permissions of user.
+ $titletoshow = $event->getNomUrl(0, $maxnbofchar, 'cal_event cal_event_title', '', 0, 0);
+ $event->label = $savlabel;
+ $event->libelle = $savlabel;
+ }
- // Loop on each assigned user
- $listofusertoshow = '';
- $posuserassigned = 0;
- foreach ($event->userassigned as $tmpid => $tmpdata)
- {
- if (!$posuserassigned && $titletoshow) $listofusertoshow .= ' ';
- $posuserassigned++;
- if (empty($cacheusers[$tmpid]))
- {
- $newuser = new User($db);
- $newuser->fetch($tmpid);
- $cacheusers[$tmpid] = $newuser;
- }
+ // Loop on each assigned user
+ $listofusertoshow = '';
+ $posuserassigned = 0;
+ foreach ($event->userassigned as $tmpid => $tmpdata)
+ {
+ if (!$posuserassigned && $titletoshow) $listofusertoshow .= ' ';
+ $posuserassigned++;
+ if (empty($cacheusers[$tmpid]))
+ {
+ $newuser = new User($db);
+ $newuser->fetch($tmpid);
+ $cacheusers[$tmpid] = $newuser;
+ }
- $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom');
- }
+ $listofusertoshow .= $cacheusers[$tmpid]->getNomUrl(-3, '', 0, 0, 0, 0, '', 'paddingright valigntextbottom');
+ }
- print $titletoshow;
- print $listofusertoshow;
+ print $titletoshow;
+ print $listofusertoshow;
- if ($event->type_code == 'ICALEVENT') print ' ('.dol_trunc($event->icalname, $maxnbofchar).')';
+ if ($event->type_code == 'ICALEVENT') print ' ('.dol_trunc($event->icalname, $maxnbofchar).')';
- $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0));
- $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0));
+ $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0));
+ $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0));
- // If action related to company / contact
- $linerelatedto = '';
- if ($thirdparty_id > 0)
- {
- if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id]))
- {
- $thirdparty = new Societe($db);
- $thirdparty->fetch($thirdparty_id);
- $cachethirdparties[$thirdparty_id] = $thirdparty;
- } else $thirdparty = $cachethirdparties[$thirdparty_id];
- if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0);
- }
- if (!empty($contact_id) && $contact_id > 0)
- {
- if (!is_object($cachecontacts[$contact_id]))
- {
- $contact = new Contact($db);
- $contact->fetch($contact_id);
- $cachecontacts[$contact_id] = $contact;
- } else $contact = $cachecontacts[$contact_id];
- if ($linerelatedto) $linerelatedto .= ' ';
- if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0);
- }
- if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT))
- {
- include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
- if ($linerelatedto) $linerelatedto .= ' ';
- $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1);
- }
- if ($linerelatedto) print ' '.$linerelatedto;
- }
+ // If action related to company / contact
+ $linerelatedto = '';
+ if ($thirdparty_id > 0)
+ {
+ if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id]))
+ {
+ $thirdparty = new Societe($db);
+ $thirdparty->fetch($thirdparty_id);
+ $cachethirdparties[$thirdparty_id] = $thirdparty;
+ } else $thirdparty = $cachethirdparties[$thirdparty_id];
+ if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0);
+ }
+ if (!empty($contact_id) && $contact_id > 0)
+ {
+ if (!is_object($cachecontacts[$contact_id]))
+ {
+ $contact = new Contact($db);
+ $contact->fetch($contact_id);
+ $cachecontacts[$contact_id] = $contact;
+ } else $contact = $cachecontacts[$contact_id];
+ if ($linerelatedto) $linerelatedto .= ' ';
+ if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0);
+ }
+ if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT))
+ {
+ include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
+ if ($linerelatedto) $linerelatedto .= ' ';
+ $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1);
+ }
+ if ($linerelatedto) print ' '.$linerelatedto;
+ }
- // Show location
- if ($showinfo)
- {
- if ($event->location)
- {
- print ' ';
- print $langs->trans("Location").': '.$event->location;
- }
- }
+ // Show location
+ if ($showinfo)
+ {
+ if ($event->location)
+ {
+ print ' ';
+ print $langs->trans("Location").': '.$event->location;
+ }
+ }
- print ' ';
- // Status - Percent
- $withstatus = 0;
- if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT')
- {
- $withstatus = 1;
- if ($event->percentage >= 0) $withstatus = 2;
- }
- print '';
- if ($withstatus) print $event->getLibStatut(3, 1);
- else print ' ';
- print '
';
- print ''."\n";
- $i++;
- } else {
- print ''.img_picto("all", "1downarrow_selected.png").' ...';
- print ' +'.(count($eventarray[$daykey]) - $maxprint);
- print ' ';
- break;
- //$ok=false; // To avoid to show twice the link
- }
- }
+ print ' ';
+ // Status - Percent
+ $withstatus = 0;
+ if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT')
+ {
+ $withstatus = 1;
+ if ($event->percentage >= 0) $withstatus = 2;
+ }
+ print '';
+ if ($withstatus) print $event->getLibStatut(3, 1);
+ else print ' ';
+ print '
';
+ print '
'."\n";
+ $i++;
+ } else {
+ print '
'.img_picto("all", "1downarrow_selected.png").' ...';
+ print ' +'.(count($eventarray[$daykey]) - $maxprint);
+ print ' ';
+ break;
+ //$ok=false; // To avoid to show twice the link
+ }
+ }
- break;
- }
- }
- if (!$i) print ' ';
+ break;
+ }
+ }
+ if (!$i) print ' ';
- if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $i > $maxprint && $maxprint)
- {
- print '
'.img_picto("all", "1downarrow_selected.png").' +'.$langs->trans("More").'...
';
- //print ' +'.(count($eventarray[$daykey])-$maxprint);
- print ''."\n";
- }
+ print ''."\n";
+ }
- print '
'; // td tr
+ print '
'; // td tr
- print '
'; // table
- print "\n";
+ print '
'; // table
+ print "\n";
}
diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php
index 20ba2928de1..ee47dbc3387 100644
--- a/htdocs/comm/action/list.php
+++ b/htdocs/comm/action/list.php
@@ -429,7 +429,7 @@ if ($resql)
$arrayofselected = is_array($toselect) ? $toselect : array();
// Local calendar
- $newtitle = '
';
+ $newtitle = '
';
$newtitle .= ' '.$langs->trans("LocalAgenda").' ';
$newtitle .= '
';
//$newtitle=$langs->trans($title);
diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php
index 7eb5b9e5c6d..72b25c9d731 100644
--- a/htdocs/comm/action/pertype.php
+++ b/htdocs/comm/action/pertype.php
@@ -41,9 +41,9 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3;
-$filter = GETPOST("filter", 'alpha', 3);
-$filtert = GETPOST("filtert", "int", 3);
-$usergroup = GETPOST("usergroup", "int", 3);
+$filter = GETPOST("search_filter", 'alpha', 3) ? GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3);
+$filtert = GETPOST("search_filtert", "int", 3) ? GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3);
+$usergroup = GETPOST("search_usergroup", "int", 3) ? GETPOST("search_usergroup", "int", 3) : GETPOST("usergroup", "int", 3);
//if (! ($usergroup > 0) && ! ($filtert > 0)) $filtert = $user->id;
//$showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1;
$showbirthday = 0;
@@ -64,7 +64,7 @@ if (!$sortorder) $sortorder = "ASC";
if (!$sortfield) $sortfield = "a.datec";
// Security check
-$socid = GETPOST("socid", "int");
+$socid = GETPOST("search_socid", "int") ?GETPOST("search_socid", "int") : GETPOST("socid", "int");
if ($user->socid) $socid = $user->socid;
$result = restrictedArea($user, 'agenda', 0, '', 'myactions');
if ($socid < 0) $socid = '';
@@ -79,22 +79,23 @@ if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no per
//$action=GETPOST('action','alpha');
$action = 'show_pertype';
-$resourceid = GETPOST("resourceid", "int");
+$resourceid = GETPOST("search_resourceid", "int") ?GETPOST("search_resourceid", "int") : GETPOST("resourceid", "int");
$year = GETPOST("year", "int") ?GETPOST("year", "int") : date("Y");
$month = GETPOST("month", "int") ?GETPOST("month", "int") : date("m");
$week = GETPOST("week", "int") ?GETPOST("week", "int") : date("W");
$day = GETPOST("day", "int") ?GETPOST("day", "int") : date("d");
-$pid = GETPOST("projectid", "int", 3);
-$status = GETPOST("status", 'alpha');
-$type = GETPOST("type", 'alpha');
+$pid = GETPOST("search_projectid", "int", 3) ?GETPOST("search_projectid", "int", 3) : GETPOST("projectid", "int", 3);
+$status = GETPOST("search_status", 'alpha') ?GETPOST("search_status", 'alpha') : GETPOST("status", 'alpha');
+$type = GETPOST("search_type", 'alpha') ?GETPOST("search_type", 'alpha') : GETPOST("type", 'alpha');
$maxprint = ((GETPOST("maxprint", 'int') != '') ?GETPOST("maxprint", 'int') : $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW);
+$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
// Set actioncode (this code must be same for setting actioncode into peruser, listacton and index)
-if (GETPOST('actioncode', 'array'))
+if (GETPOST('search_actioncode', 'array'))
{
- $actioncode = GETPOST('actioncode', 'array', 3);
+ $actioncode = GETPOST('search_actioncode', 'array', 3);
if (!count($actioncode)) $actioncode = '0';
} else {
- $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE));
+ $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE));
}
if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE);
@@ -107,6 +108,7 @@ if ($dateselect > 0)
}
$tmp = empty($conf->global->MAIN_DEFAULT_WORKING_HOURS) ? '9-18' : $conf->global->MAIN_DEFAULT_WORKING_HOURS;
+$tmp = str_replace(' ', '', $tmp); // FIX 7533
$tmparray = explode('-', $tmp);
$begin_h = GETPOST('begin_h', 'int') != '' ?GETPOST('begin_h', 'int') : ($tmparray[0] != '' ? $tmparray[0] : 9);
$end_h = GETPOST('end_h', 'int') ?GETPOST('end_h', 'int') : ($tmparray[1] != '' ? $tmparray[1] : 18);
@@ -115,14 +117,15 @@ if ($end_h < 1 || $end_h > 24) $end_h = 18;
if ($end_h <= $begin_h) $end_h = $begin_h + 1;
$tmp = empty($conf->global->MAIN_DEFAULT_WORKING_DAYS) ? '1-5' : $conf->global->MAIN_DEFAULT_WORKING_DAYS;
+$tmp = str_replace(' ', '', $tmp); // FIX 7533
$tmparray = explode('-', $tmp);
$begin_d = 1;
-$end_d = 53;
+$end_d = 53;
if ($status == '' && !isset($_GET['status']) && !isset($_POST['status'])) $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS);
if (empty($action) && !isset($_GET['action']) && !isset($_POST['action'])) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW);
-if (GETPOST('viewcal') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') {
+if (GETPOST('viewcal', 'alpha') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') {
$action = 'show_month'; $day = '';
} // View by month
if (GETPOST('viewweek', 'alpha') || $action == 'show_week') {
@@ -150,6 +153,10 @@ if ($action == 'delete_action')
{
$event = new ActionComm($db);
$event->fetch($actionid);
+ $event->fetch_optionals();
+ $event->fetch_userassigned();
+ $event->oldcopy = clone $event;
+
$result = $event->delete();
}
@@ -159,6 +166,27 @@ if ($action == 'delete_action')
* View
*/
+$parameters = array(
+ 'socid' => $socid,
+ 'status' => $status,
+ 'year' => $year,
+ 'month' => $month,
+ 'day' => $day,
+ 'type' => $type,
+ 'maxprint' => $maxprint,
+ 'filter' => $filter,
+ 'filtert' => $filtert,
+ 'showbirthday' => $showbirthday,
+ 'canedit' => $canedit,
+ 'optioncss' => $optioncss,
+ 'actioncode' => $actioncode,
+ 'pid' => $pid,
+ 'resourceid' => $resourceid,
+ 'usergroup' => $usergroup,
+);
+$reshook = $hookmanager->executeHooks('beforeAgendaPerType', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
+if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+
$form = new Form($db);
$companystatic = new Societe($db);
@@ -199,18 +227,26 @@ if ($status == 'done') $title = $langs->trans("DoneActions");
if ($status == 'todo') $title = $langs->trans("ToDoActions");
$param = '';
-if ($actioncode || isset($_GET['actioncode']) || isset($_POST['actioncode'])) $param .= "&actioncode=".$actioncode;
-if ($resourceid > 0) $param .= "&resourceid=".$resourceid;
-if ($status || isset($_GET['status']) || isset($_POST['status'])) $param .= "&status=".$status;
-if ($filter) $param .= "&filter=".$filter;
-if ($filtert) $param .= "&filtert=".$filtert;
-if ($usergroup) $param .= "&usergroup=".$usergroup;
-if ($socid) $param .= "&socid=".$socid;
-if ($showbirthday) $param .= "&showbirthday=1";
-if ($pid) $param .= "&projectid=".$pid;
-if ($type) $param .= "&type=".$type;
-if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser' || $action != 'show_pertype') $param .= '&action='.$action;
-$param .= "&maxprint=".$maxprint;
+if ($actioncode || isset($_GET['search_actioncode']) || isset($_POST['search_actioncode'])) {
+ if (is_array($actioncode)) {
+ foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action);
+ } else $param .= "&search_actioncode=".urlencode($actioncode);
+}
+if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid);
+if ($status || isset($_GET['status']) || isset($_POST['status'])) $param .= "&search_status=".urlencode($status);
+if ($filter) $param .= "&search_filter=".urlencode($filter);
+if ($filtert) $param .= "&search_filtert=".urlencode($filtert);
+if ($usergroup) $param .= "&search_usergroup=".urlencode($usergroup);
+if ($socid) $param .= "&search_socid=".urlencode($socid);
+if ($showbirthday) $param .= "&search_showbirthday=1";
+if ($pid) $param .= "&search_projectid=".urlencode($pid);
+if ($type) $param .= "&search_type=".urlencode($type);
+if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param .= '&action='.urlencode($action);
+if ($begin_h != '') $param .= '&begin_h='.urlencode($begin_h);
+if ($end_h != '') $param .= '&end_h='.urlencode($end_h);
+if ($begin_d != '') $param .= '&begin_d='.urlencode($begin_d);
+if ($end_d != '') $param .= '&end_d='.urlencode($end_d);
+$param .= "&maxprint=".urlencode($maxprint);
$prev = dol_get_first_day($year, 1);
$prev_year = $year - 1;
@@ -238,6 +274,7 @@ $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, 7, 'd');
$max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year));
$tmpday = $first_day;
+$picto = 'calendartype';
$nav = "
".img_previous($langs->trans("Previous"))." \n";
$nav .= "
".dol_print_date(dol_mktime(0, 0, 0, $first_month, $first_day, $first_year), "%Y")." \n";
@@ -245,7 +282,7 @@ $nav .= "
".$langs->trans("Today")." )";
$picto = 'calendarweek';
-$nav .= '
';
+//$nav .= '
';
+$nav .= '
';
+//$nav .= '';
// Must be after the nav definition
-$param .= '&year='.$year.'&month='.$month.($day ? '&day='.$day : '');
+$param .= '&year='.urlencode($year).'&month='.urlencode($month).($day ? '&day='.urlencode($day) : '');
//print 'x'.$param;
-
-
-$tabactive = 'cardpertype';
+$tabactive = '';
+if ($action == 'show_month') $tabactive = 'cardmonth';
+if ($action == 'show_week') $tabactive = 'cardweek';
+if ($action == 'show_day') $tabactive = 'cardday';
+if ($action == 'show_list') $tabactive = 'cardlist';
+if ($action == 'show_peruser') $tabactive = 'cardperuser';
+if ($action == 'show_pertype') $tabactive = 'cardpertype';
$paramnoaction = preg_replace('/action=[a-z_]+/', '', $param);
$head = calendars_prepare_head($paramnoaction);
-dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action');
-print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, $listofextcals, $actioncode, $usergroup, '', $resourceid);
-dol_fiche_end();
+print '
';
// Line header with list of days
@@ -603,6 +712,7 @@ $sql = "SELECT code, color, libelle as label FROM ".MAIN_DB_PREFIX."c_actioncomm
$resql = $db->query($sql);
while ($obj = $db->fetch_object($resql))
{
+ $typeofevents[$obj->code] = $obj->code;
$colorsbytype[$obj->code] = $obj->color;
$labelbytype[$obj->code] = $obj->label;
}
@@ -616,7 +726,7 @@ foreach ($typeofevents as $typeofevent)
{
$var = !$var;
echo "
";
- echo ''.$username->getNomUrl(1).' ';
+ echo ''.$typeofevent.' ';
$tmpday = $sav;
// Lopp on each day of week
@@ -642,7 +752,7 @@ foreach ($typeofevents as $typeofevent)
if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1;
if ($today) $style = 'cal_today_peruser';
- show_day_events_pertype($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var);
+ show_day_events_pertype($typeofevent, $tmpday, $tmpmonth, $tmpyear, $mont, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var);
$i++;
}
@@ -651,7 +761,7 @@ foreach ($typeofevents as $typeofevent)
}
echo "
\n";
-
+echo "
";
if (!empty($conf->global->AGENDA_USE_EVENT_TYPE))
{
@@ -678,6 +788,9 @@ if (!empty($conf->global->AGENDA_USE_EVENT_TYPE))
*/
}
+print "\n".'';
+print "\n";
+
// Add js code to manage click on a box
print '';
- }
- }
- }
+ $out .= '';
+ $out .= '';
+ }
+ }
+ }
return $out;
}
@@ -1975,7 +1975,7 @@ class ExtraFields
foreach ($extralabels as $key => $value)
{
if (!empty($onlykey) && $onlykey != '@GETPOSTISSET' && $key != $onlykey) continue;
- if (!empty($onlykey) && $onlykey == '@GETPOSTISSET' && ! GETPOSTISSET('options_'.$key)) continue;
+ if (!empty($onlykey) && $onlykey == '@GETPOSTISSET' && !GETPOSTISSET('options_'.$key)) continue;
$key_type = $this->attributes[$object->table_element]['type'][$key];
if ($key_type == 'separate') continue;
@@ -1996,8 +1996,8 @@ class ExtraFields
if ($this->attributes[$object->table_element]['required'][$key]) // Value is required
{
// Check if empty without using GETPOST, value can be alpha, int, array, etc...
- if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] != 'select' && $_POST["options_".$key] != '0')
- || (!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'select')
+ if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] != 'select' && $_POST["options_".$key] != '0')
+ || (!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $this->attributes[$object->table_element]['type'][$key] == 'select')
|| (is_array($_POST["options_".$key]) && empty($_POST["options_".$key])))
{
//print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key];
diff --git a/htdocs/core/class/hookmanager.class.php b/htdocs/core/class/hookmanager.class.php
index 089e9fb6717..c1d11c9290b 100644
--- a/htdocs/core/class/hookmanager.class.php
+++ b/htdocs/core/class/hookmanager.class.php
@@ -144,7 +144,7 @@ class HookManager
*/
public function executeHooks($method, $parameters = array(), &$object = '', &$action = '')
{
- if (!is_array($this->hooks) || empty($this->hooks)) return '';
+ if (!is_array($this->hooks) || empty($this->hooks)) return 0; // No hook available, do nothing.
$parameters['context'] = join(':', $this->contextarray);
//dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']);
@@ -225,14 +225,14 @@ class HookManager
// Loop on each hook to qualify modules that have declared context
$modulealreadyexecuted = array();
- $resaction = 0; $error = 0; $result = '';
+ $resaction = 0; $error = 0;
foreach ($this->hooks as $context => $modules) // $this->hooks is an array with context as key and value is an array of modules that handle this context
{
if (!empty($modules))
{
foreach ($modules as $module => $actionclassinstance)
{
- //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."
\n";
+ //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n";
// test to avoid running twice a hook, when a module implements several active contexts
if (in_array($module, $modulealreadyexecuted)) continue;
@@ -290,7 +290,7 @@ class HookManager
}
}
- //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."
\n";
+ //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n";
unset($actionclassinstance->results);
unset($actionclassinstance->resprints);
@@ -298,6 +298,6 @@ class HookManager
}
}
- return ($error ?-1 : $resaction);
+ return ($error ? -1 : $resaction);
}
}
diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php
index c6ebb7511bb..3350507e543 100644
--- a/htdocs/core/class/html.form.class.php
+++ b/htdocs/core/class/html.form.class.php
@@ -647,7 +647,7 @@ class Form
$disabled = 0;
$ret = '
';
- $ret .= '';
+ $ret .= '';
// Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.
$parameters = array();
@@ -666,11 +666,11 @@ class Form
$ret .= ' ';
- if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.'.$name.'select');
+ if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.'.$name.'select');
// Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button
$ret .= ' '; // Hidden button BEFORE so it is the one used when we submit with ENTER.
- $ret .= ' ';
+ $ret .= ' ';
$ret .= '
';
if (!empty($conf->use_javascript_ajax))
@@ -5591,15 +5591,15 @@ class Form
{
if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
//$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
- if ($addnowlink == 1)
- {
- $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');';
- $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
- } elseif ($addnowlink == 2)
- {
- $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
- $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
- }
+ if ($addnowlink == 1)
+ {
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');';
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
+ } elseif ($addnowlink == 2)
+ {
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
+ }
if ($fullday) $reset_scripts .= ' } ';
}
@@ -5608,15 +5608,15 @@ class Form
{
if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
//$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
- if ($addnowlink == 1)
- {
- $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');';
- $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
- } elseif ($addnowlink == 2)
- {
- $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
- $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
- }
+ if ($addnowlink == 1)
+ {
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');';
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
+ } elseif ($addnowlink == 2)
+ {
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
+ $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
+ }
if ($fullday) $reset_scripts .= ' } ';
}
// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
@@ -5684,20 +5684,20 @@ class Form
{
global $langs;
- $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes'));
+ $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes'));
- $retstring = '
';
- foreach ($TDurationTypes as $key=>$typeduration) {
- $retstring .= '";
- }
- $retstring .= " ";
+ $retstring = '
';
+ foreach ($TDurationTypes as $key=>$typeduration) {
+ $retstring .= '";
+ }
+ $retstring .= " ";
- return $retstring;
- }
+ return $retstring;
+ }
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
@@ -6545,23 +6545,23 @@ class Form
foreach ($array as $key => $val)
{
- /* var_dump($val);
+ /* var_dump($val);
var_dump(array_key_exists('enabled', $val));
var_dump(!$val['enabled']);*/
- if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled'])
- {
- unset($array[$key]); // We don't want this field
- continue;
- }
- if ($val['label'])
- {
- if (!empty($val['langfile']) && is_object($langs)) {
- $langs->load($val['langfile']);
- }
+ if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled'])
+ {
+ unset($array[$key]); // We don't want this field
+ continue;
+ }
+ if ($val['label'])
+ {
+ if (!empty($val['langfile']) && is_object($langs)) {
+ $langs->load($val['langfile']);
+ }
- $lis .= '
'.dol_escape_htmltag($langs->trans($val['label'])).' ';
- $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
- }
+ $lis .= '
'.dol_escape_htmltag($langs->trans($val['label'])).' ';
+ $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
+ }
}
$out = '
@@ -7538,20 +7538,20 @@ class Form
}
/**
- * Return HTML to show the search and clear seach button
+ * Return HTML to show the search and clear search button
*
* @param string $cssclass CSS class
* @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
- * @param string $massactionname Mass action button name that will launch an action on the selected items
+ * @param string $massactionname Mass action button name that will launch an action on the selected items
* @return string
*/
- public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
+ public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
{
global $conf, $langs;
$out = '';
$id = uniqid();
- if (!empty($conf->use_javascript_ajax)) $out .= '
';
+ if (!empty($conf->use_javascript_ajax)) $out .= '
';
$out .= '';
- print '
';
+ print '
';
- print '
';
+ print '';
- // Load shipments already done for same order
- $object->loadExpeditions();
+ // Load shipments already done for same order
+ $object->loadExpeditions();
- if ($numAsked)
- {
- print '';
- print ''.$langs->trans("Description").' ';
- print ''.$langs->trans("QtyOrdered").' ';
- print ''.$langs->trans("QtyShipped").' ';
- print ''.$langs->trans("QtyToShip");
+ if ($numAsked)
+ {
+ print ' ';
+ print ''.$langs->trans("Description").' ';
+ print ''.$langs->trans("QtyOrdered").' ';
+ print ''.$langs->trans("QtyShipped").' ';
+ print ''.$langs->trans("QtyToShip");
if (empty($conf->productbatch->enabled))
{
- print ''.$langs->trans("Fill").' ';
- print ' / ';
+ print ''.$langs->trans("Fill").' ';
+ print ' / ';
} else {
print ' ';
}
print ''.$langs->trans("Reset").' ';
- print ' ';
- if (!empty($conf->stock->enabled))
- {
+ print '';
+ if (!empty($conf->stock->enabled))
+ {
if (empty($conf->productbatch->enabled))
{
- print ''.$langs->trans("Warehouse").' ('.$langs->trans("Stock").') ';
+ print ''.$langs->trans("Warehouse").' ('.$langs->trans("Stock").') ';
} else {
print ''.$langs->trans("Warehouse").' / '.$langs->trans("Batch").' ('.$langs->trans("Stock").') ';
}
- }
- print " \n";
- }
+ }
+ print "\n";
+ }
- $indiceAsked = 0;
- while ($indiceAsked < $numAsked)
- {
- $product = new Product($db);
+ $indiceAsked = 0;
+ while ($indiceAsked < $numAsked)
+ {
+ $product = new Product($db);
- $line = $object->lines[$indiceAsked];
+ $line = $object->lines[$indiceAsked];
- $parameters = array('i' => $indiceAsked, 'line' => $line, 'num' => $numAsked);
- $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action);
- if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
+ $parameters = array('i' => $indiceAsked, 'line' => $line, 'num' => $numAsked);
+ $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action);
+ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
- if (empty($reshook))
- {
- // Show product and description
- $type = $line->product_type ? $line->product_type : $line->fk_product_type;
- // Try to enhance type detection using date_start and date_end for free lines where type
- // was not saved.
- if (!empty($line->date_start)) $type = 1;
- if (!empty($line->date_end)) $type = 1;
+ if (empty($reshook))
+ {
+ // Show product and description
+ $type = $line->product_type ? $line->product_type : $line->fk_product_type;
+ // Try to enhance type detection using date_start and date_end for free lines where type
+ // was not saved.
+ if (!empty($line->date_start)) $type = 1;
+ if (!empty($line->date_end)) $type = 1;
- print ''."\n";
- print ''."\n";
+ print ''."\n";
+ print ' '."\n";
- // Product label
- if ($line->fk_product > 0) // If predefined product
- {
- $product->fetch($line->fk_product);
- $product->load_stock('warehouseopen'); // Load all $product->stock_warehouse[idwarehouse]->detail_batch
- //var_dump($product->stock_warehouse[1]);
+ // Product label
+ if ($line->fk_product > 0) // If predefined product
+ {
+ $product->fetch($line->fk_product);
+ $product->load_stock('warehouseopen'); // Load all $product->stock_warehouse[idwarehouse]->detail_batch
+ //var_dump($product->stock_warehouse[1]);
- print '';
- print ' '; // ancre pour retourner sur la ligne
+ print ' ';
+ print ' '; // ancre pour retourner sur la ligne
- // Show product and description
- $product_static->type = $line->fk_product_type;
- $product_static->id = $line->fk_product;
- $product_static->ref = $line->ref;
- $product_static->status_batch = $line->product_tobatch;
- $text = $product_static->getNomUrl(1);
- $text .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
- $description = ($conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($line->desc));
- print $form->textwithtooltip($text, $description, 3, '', '', $i);
+ // Show product and description
+ $product_static->type = $line->fk_product_type;
+ $product_static->id = $line->fk_product;
+ $product_static->ref = $line->ref;
+ $product_static->status_batch = $line->product_tobatch;
+ $text = $product_static->getNomUrl(1);
+ $text .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
+ $description = ($conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($line->desc));
+ print $form->textwithtooltip($text, $description, 3, '', '', $i);
- // Show range
- print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end));
+ // Show range
+ print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end));
- // Add description in form
- if (!empty($conf->global->PRODUIT_DESC_IN_FORM))
- {
- print ($line->desc && $line->desc != $line->product_label) ? ' '.dol_htmlentitiesbr($line->desc) : '';
- }
+ // Add description in form
+ if (!empty($conf->global->PRODUIT_DESC_IN_FORM))
+ {
+ print ($line->desc && $line->desc != $line->product_label) ? ' '.dol_htmlentitiesbr($line->desc) : '';
+ }
- print ' ';
- } else {
- print "";
- if ($type == 1) $text = img_object($langs->trans('Service'), 'service');
- else $text = img_object($langs->trans('Product'), 'product');
+ print ' ';
+ } else {
+ print "";
+ if ($type == 1) $text = img_object($langs->trans('Service'), 'service');
+ else $text = img_object($langs->trans('Product'), 'product');
- if (!empty($line->label)) {
- $text .= ' '.$line->label.' ';
- print $form->textwithtooltip($text, $line->desc, 3, '', '', $i);
- } else {
- print $text.' '.nl2br($line->desc);
- }
+ if (!empty($line->label)) {
+ $text .= ' '.$line->label.' ';
+ print $form->textwithtooltip($text, $line->desc, 3, '', '', $i);
+ } else {
+ print $text.' '.nl2br($line->desc);
+ }
- // Show range
- print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end));
- print " \n";
- }
+ // Show range
+ print_date_range($db->jdate($line->date_start), $db->jdate($line->date_end));
+ print "\n";
+ }
- // Qty
- print ''.$line->qty;
- print ' ';
- print ' ';
- $qtyProdCom = $line->qty;
+ // Qty
+ print ''.$line->qty;
+ print ' ';
+ print ' ';
+ $qtyProdCom = $line->qty;
- // Qty already shipped
- print '';
- $quantityDelivered = $object->expeditions[$line->id];
- print $quantityDelivered;
- print ' ';
- print ' ';
+ // Qty already shipped
+ print '';
+ $quantityDelivered = $object->expeditions[$line->id];
+ print $quantityDelivered;
+ print ' ';
+ print ' ';
- // Qty to ship
- $quantityAsked = $line->qty;
+ // Qty to ship
+ $quantityAsked = $line->qty;
if ($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES))
{
$quantityToBeDelivered = 0;
} else {
$quantityToBeDelivered = $quantityAsked - $quantityDelivered;
}
- $warehouse_id = GETPOST('entrepot_id', 'int');
+ $warehouse_id = GETPOST('entrepot_id', 'int');
$warehouseObject = null;
if ($warehouse_id > 0 || !($line->fk_product > 0) || empty($conf->stock->enabled)) // If warehouse was already selected or if product is not a predefined, we go into this part with no multiwarehouse selection
{
- print '';
+ print '';
//ship from preselected location
$stock = + $product->stock_warehouse[$warehouse_id]->real; // Convert to number
$deliverableQty = min($quantityToBeDelivered, $stock);
@@ -2523,7 +2523,7 @@ if ($action == 'create')
$genallowed = $user->rights->expedition->lire;
$delallowed = $user->rights->expedition->creer;
- print $formfile->showdocuments('expedition', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
+ print $formfile->showdocuments('expedition', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
// Show links to link elements
diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php
index 46d964756ff..f601f483d89 100644
--- a/htdocs/expedition/class/expedition.class.php
+++ b/htdocs/expedition/class/expedition.class.php
@@ -3,7 +3,7 @@
* Copyright (C) 2005-2012 Regis Houssin
* Copyright (C) 2007 Franky Van Liedekerke
* Copyright (C) 2006-2012 Laurent Destailleur
- * Copyright (C) 2011-2017 Juanjo Menent
+ * Copyright (C) 2011-2020 Juanjo Menent
* Copyright (C) 2013 Florian Henry
* Copyright (C) 2014 Cedric GROSS
* Copyright (C) 2014-2015 Marcos GarcÃa
@@ -1067,7 +1067,7 @@ class Expedition extends CommonObject
if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight);
if (isset($this->note_private)) $this->note = trim($this->note_private);
if (isset($this->note_public)) $this->note = trim($this->note_public);
- if (isset($this->modelpdf)) $this->modelpdf = trim($this->modelpdf);
+ if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf);
@@ -1508,6 +1508,9 @@ class Expedition extends CommonObject
{
$this->db->commit();
+ // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
+ $this->deleteEcmFiles();
+
// We delete PDFs
$ref = dol_sanitizeFileName($this->ref);
if (!empty($conf->expedition->dir_output))
diff --git a/htdocs/expedition/index.php b/htdocs/expedition/index.php
index 849e2054cd6..6f21683cc69 100644
--- a/htdocs/expedition/index.php
+++ b/htdocs/expedition/index.php
@@ -3,6 +3,7 @@
* Copyright (C) 2004-2011 Laurent Destailleur
* Copyright (C) 2005-2012 Regis Houssin
* Copyright (C) 2019 Nicolas ZABOURI
+ * Copyright (C) 2020 Tobias Sekan
*
* 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
@@ -84,7 +85,7 @@ if (!$user->rights->societe->client->voir && !$socid)
$sql .= $clause." sc.fk_user = ".$user->id;
$clause = " AND ";
}
-$sql .= $clause." e.fk_statut = 0";
+$sql .= $clause." e.fk_statut = ".Expedition::STATUS_DRAFT;
$sql .= " AND e.entity IN (".getEntity('expedition').")";
if ($socid) $sql .= " AND c.fk_soc = ".$socid;
@@ -96,7 +97,13 @@ if ($resql)
print '';
print '
';
print '';
- print ''.$langs->trans("SendingsToValidate").' ';
+ print '';
+ print $langs->trans("SendingsToValidate").' ';
+ print '';
+ print ''.$num.' ';
+ print ' ';
+ print ' ';
+ print '';
if ($num)
{
@@ -156,13 +163,21 @@ $resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
+
+ print '';
+ print '
';
+ print '';
+ print '';
+ print $langs->trans("LastSendings").' ';
+ print '';
+ print ''.$num.' ';
+ print ' ';
+ print ' ';
+ print ' ';
+
if ($num)
{
$i = 0;
- print '';
- print '
';
- print '';
- print ''.$langs->trans("LastSendings", $num).' ';
while ($i < $num)
{
$obj = $db->fetch_object($resql);
@@ -189,8 +204,10 @@ if ($resql)
print '';
$i++;
}
- print "
";
+ } else {
+ print ''.$langs->trans("None").' ';
}
+ print "
";
$db->free($resql);
} else dol_print_error($db);
@@ -214,13 +231,21 @@ if ($resql)
$langs->load("orders");
$num = $db->num_rows($resql);
+
+ print '';
+ print '
';
+
+ print '';
+ print ''.$langs->trans("OrdersToProcess").' ';
+ print '';
+ print ''.$num.' ';
+ print ' ';
+ print ' ';
+ print ' ';
+
if ($num)
{
$i = 0;
- print '';
- print '
';
- print '';
- print ''.$langs->trans("OrdersToProcess").' '.$num.' ';
while ($i < $num && $i < 10)
{
$obj = $db->fetch_object($resql);
@@ -254,9 +279,11 @@ if ($resql)
print ' ';
print '';
}
-
- print "
";
+ } else {
+ print ''.$langs->trans("None").' ';
}
+
+ print "
";
} else dol_print_error($db);
diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php
index d4f09f793bc..023b114835a 100644
--- a/htdocs/expensereport/card.php
+++ b/htdocs/expensereport/card.php
@@ -1,6 +1,6 @@
- * Copyright (C) 2004-2019 Laurent Destailleur
+ * Copyright (C) 2004-2020 Laurent Destailleur
* Copyright (C) 2005-2009 Regis Houssin
* Copyright (C) 2015-2017 Alexandre Spangaro
* Copyright (C) 2017 Ferran Marcet
@@ -115,14 +115,14 @@ $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object-
if ($object->id > 0)
{
- // Check current user can read this expense report
- $canread = 0;
- if (!empty($user->rights->expensereport->readall)) $canread = 1;
- if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1;
- if (!$canread)
- {
- accessforbidden();
- }
+ // Check current user can read this expense report
+ $canread = 0;
+ if (!empty($user->rights->expensereport->readall)) $canread = 1;
+ if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1;
+ if (!$canread)
+ {
+ accessforbidden();
+ }
}
@@ -145,243 +145,243 @@ if (empty($reshook))
}
$action = '';
- $fk_project = '';
- $date_start = '';
- $date_end = '';
- $date = '';
- $comments = '';
- $vatrate = '';
- $value_unit_ht = '';
- $value_unit = '';
- $qty = 1;
- $fk_c_type_fees = -1;
+ $fk_project = '';
+ $date_start = '';
+ $date_end = '';
+ $date = '';
+ $comments = '';
+ $vatrate = '';
+ $value_unit_ht = '';
+ $value_unit = '';
+ $qty = 1;
+ $fk_c_type_fees = -1;
}
include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php';
if (GETPOSTISSET('sendit')) // If we just submit a file
{
- if ($action == 'updateline') $action = 'editline'; // To avoid to make the updateline now
- else $action = ''; // To avoid to make the addline now
+ if ($action == 'updateline') $action = 'editline'; // To avoid to make the updateline now
+ else $action = ''; // To avoid to make the addline now
}
- include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
+ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
- include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
+ include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
- include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
+ include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
- // Action clone object
- if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->expensereport->creer)
- {
- if (1 == 0 && !GETPOST('clone_content', 'alpha') && !GETPOST('clone_receivers', 'alpha'))
- {
- setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
- } else {
- if ($object->id > 0)
- {
- // Because createFromClone modifies the object, we must clone it so that we can restore it later if it fails
- $orig = clone $object;
+ // Action clone object
+ if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->expensereport->creer)
+ {
+ if (1 == 0 && !GETPOST('clone_content', 'alpha') && !GETPOST('clone_receivers', 'alpha'))
+ {
+ setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
+ } else {
+ if ($object->id > 0)
+ {
+ // Because createFromClone modifies the object, we must clone it so that we can restore it later if it fails
+ $orig = clone $object;
- $result = $object->createFromClone($user, GETPOST('fk_user_author', 'int'));
- if ($result > 0)
- {
- header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
- exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- $object = $orig;
- $action = '';
- }
- }
- }
- }
+ $result = $object->createFromClone($user, GETPOST('fk_user_author', 'int'));
+ if ($result > 0)
+ {
+ header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ $object = $orig;
+ $action = '';
+ }
+ }
+ }
+ }
- if ($action == 'confirm_delete' && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->supprimer)
- {
- $object = new ExpenseReport($db);
- $result = $object->fetch($id);
- $result = $object->delete($user);
- if ($result >= 0)
- {
- header("Location: index.php");
- exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
+ if ($action == 'confirm_delete' && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->supprimer)
+ {
+ $object = new ExpenseReport($db);
+ $result = $object->fetch($id);
+ $result = $object->delete($user);
+ if ($result >= 0)
+ {
+ header("Location: index.php");
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+ }
- if ($action == 'add' && $user->rights->expensereport->creer)
- {
- $object = new ExpenseReport($db);
+ if ($action == 'add' && $user->rights->expensereport->creer)
+ {
+ $object = new ExpenseReport($db);
- $object->date_debut = $date_start;
- $object->date_fin = $date_end;
+ $object->date_debut = $date_start;
+ $object->date_fin = $date_end;
- $object->fk_user_author = GETPOST('fk_user_author', 'int');
- if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id;
+ $object->fk_user_author = GETPOST('fk_user_author', 'int');
+ if (!($object->fk_user_author > 0)) $object->fk_user_author = $user->id;
- $fuser = new User($db);
- $fuser->fetch($object->fk_user_author);
+ $fuser = new User($db);
+ $fuser->fetch($object->fk_user_author);
- $object->fk_statut = 1;
- $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int');
- $object->fk_user_validator = GETPOST('fk_user_validator', 'int');
- $object->note_public = GETPOST('note_public', 'none');
- $object->note_private = GETPOST('note_private', 'none');
- // Fill array 'array_options' with data from add form
- if (!$error)
- {
- $ret = $extrafields->setOptionalsFromPost(null, $object);
- if ($ret < 0) $error++;
- }
+ $object->fk_statut = 1;
+ $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int');
+ $object->fk_user_validator = GETPOST('fk_user_validator', 'int');
+ $object->note_public = GETPOST('note_public', 'none');
+ $object->note_private = GETPOST('note_private', 'none');
+ // Fill array 'array_options' with data from add form
+ if (!$error)
+ {
+ $ret = $extrafields->setOptionalsFromPost(null, $object);
+ if ($ret < 0) $error++;
+ }
- if (!$error && empty($conf->global->EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS) && $object->periode_existe($fuser, $object->date_debut, $object->date_fin))
- {
- $error++;
- setEventMessages($langs->trans("ErrorDoubleDeclaration"), null, 'errors');
- $action = 'create';
- }
+ if (!$error && empty($conf->global->EXPENSEREPORT_ALLOW_OVERLAPPING_PERIODS) && $object->periode_existe($fuser, $object->date_debut, $object->date_fin))
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorDoubleDeclaration"), null, 'errors');
+ $action = 'create';
+ }
- if (!$error)
- {
- $db->begin();
+ if (!$error)
+ {
+ $db->begin();
- $id = $object->create($user);
- if ($id <= 0)
- {
- $error++;
- }
+ $id = $object->create($user);
+ if ($id <= 0)
+ {
+ $error++;
+ }
- if (!$error)
- {
- $db->commit();
- Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- $db->rollback();
- $action = 'create';
- }
- }
- }
+ if (!$error)
+ {
+ $db->commit();
+ Header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ $db->rollback();
+ $action = 'create';
+ }
+ }
+ }
- if ($action == 'update' && $user->rights->expensereport->creer)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ if ($action == 'update' && $user->rights->expensereport->creer)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- $object->date_debut = $date_start;
- $object->date_fin = $date_end;
+ $object->date_debut = $date_start;
+ $object->date_fin = $date_end;
- if ($object->fk_statut < 3)
- {
- $object->fk_user_validator = GETPOST('fk_user_validator', 'int');
- }
+ if ($object->fk_statut < 3)
+ {
+ $object->fk_user_validator = GETPOST('fk_user_validator', 'int');
+ }
- $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int');
- $object->note_public = GETPOST('note_public', 'none');
- $object->note_private = GETPOST('note_private', 'none');
- $object->fk_user_modif = $user->id;
+ $object->fk_c_paiement = GETPOST('fk_c_paiement', 'int');
+ $object->note_public = GETPOST('note_public', 'none');
+ $object->note_private = GETPOST('note_private', 'none');
+ $object->fk_user_modif = $user->id;
- $result = $object->update($user);
- if ($result > 0)
- {
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']);
- exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
+ $result = $object->update($user);
+ if ($result > 0)
+ {
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_POST['id']);
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+ }
- if ($action == 'update_extras')
- {
- $object->oldcopy = dol_clone($object);
+ if ($action == 'update_extras')
+ {
+ $object->oldcopy = dol_clone($object);
- // Fill array 'array_options' with data from update form
- $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none'));
- if ($ret < 0) $error++;
+ // Fill array 'array_options' with data from update form
+ $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'none'));
+ if ($ret < 0) $error++;
- if (!$error)
- {
- // Actions on extra fields
- $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY');
+ if (!$error)
+ {
+ // Actions on extra fields
+ $result = $object->insertExtraFields('EXPENSEREPORT_MODIFY');
if ($result < 0)
{
setEventMessages($object->error, $object->errors, 'errors');
$error++;
}
- }
+ }
- if ($error)
- $action = 'edit_extras';
- }
+ if ($error)
+ $action = 'edit_extras';
+ }
- if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
- {
- $error = 0;
+ if ($action == "confirm_validate" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
+ {
+ $error = 0;
- $db->begin();
+ $db->begin();
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- $result = $object->setValidate($user);
+ $result = $object->setValidate($user);
- if ($result >= 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result >= 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- $error++;
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ $error++;
+ }
- if (!$error && $result > 0 && $object->fk_user_validator > 0)
- {
- $langs->load("mails");
+ if (!$error && $result > 0 && $object->fk_user_validator > 0)
+ {
+ $langs->load("mails");
- // TO
- $destinataire = new User($db);
- $destinataire->fetch($object->fk_user_validator);
- $emailTo = $destinataire->email;
+ // TO
+ $destinataire = new User($db);
+ $destinataire->fetch($object->fk_user_validator);
+ $emailTo = $destinataire->email;
- // FROM
- $expediteur = new User($db);
- $expediteur->fetch($object->fk_user_author);
- $emailFrom = $expediteur->email;
+ // FROM
+ $expediteur = new User($db);
+ $expediteur->fetch($object->fk_user_author);
+ $emailFrom = $expediteur->email;
- if ($emailTo && $emailFrom)
- {
- $filename = array(); $filedir = array(); $mimetype = array();
+ if ($emailTo && $emailFrom)
+ {
+ $filename = array(); $filedir = array(); $mimetype = array();
- // SUBJECT
- $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
- if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
+ // SUBJECT
+ $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
+ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
- $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval");
+ $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForApproval");
- // CONTENT
- $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+ // CONTENT
+ $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
$link = ''.$link.' ';
- $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link);
+ $message = $langs->transnoentities("ExpenseReportWaitingForApprovalMessage", $expediteur->getFullName($langs), get_date_range($object->date_debut, $object->date_fin, '', $langs), $link);
- // Rebuild pdf
- /*
+ // Rebuild pdf
+ /*
$object->setDocModel($user,"");
$resultPDF = expensereport_pdf_create($db,$id,'',"",$langs);
@@ -392,38 +392,38 @@ if (empty($reshook))
array_push($mimetype,"application/pdf");
*/
- // PREPARE SEND
- $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
+ // PREPARE SEND
+ $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
- if ($mailfile)
- {
- // SEND
- $result = $mailfile->sendfile();
- if ($result)
- {
- $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
- setEventMessages($mesg, null, 'mesgs');
- } else {
- $langs->load("other");
- if ($mailfile->error)
- {
- $mesg = '';
- $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
- $mesg .= ' '.$mailfile->error;
- setEventMessages($mesg, null, 'errors');
- } else {
- setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
- }
- }
- } else {
- setEventMessages($mailfile->error, $mailfile->errors, 'errors');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
- $action = '';
- }
- }
+ if ($mailfile)
+ {
+ // SEND
+ $result = $mailfile->sendfile();
+ if ($result)
+ {
+ $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
+ setEventMessages($mesg, null, 'mesgs');
+ } else {
+ $langs->load("other");
+ if ($mailfile->error)
+ {
+ $mesg = '';
+ $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+ $mesg .= ' '.$mailfile->error;
+ setEventMessages($mesg, null, 'errors');
+ } else {
+ setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+ }
+ }
+ } else {
+ setEventMessages($mailfile->error, $mailfile->errors, 'errors');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+ $action = '';
+ }
+ }
if (!$error)
{
@@ -433,37 +433,37 @@ if (empty($reshook))
} else {
$db->rollback();
}
- }
+ }
- if ($action == "confirm_save_from_refuse" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
- $result = $object->set_save_from_refuse($user);
+ if ($action == "confirm_save_from_refuse" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
+ $result = $object->set_save_from_refuse($user);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- if ($result > 0)
- {
- // Send mail
+ if ($result > 0)
+ {
+ // Send mail
// TO
$destinataire = new User($db);
@@ -477,19 +477,19 @@ if (empty($reshook))
if ($emailFrom && $emailTo)
{
- $filename = array(); $filedir = array(); $mimetype = array();
+ $filename = array(); $filedir = array(); $mimetype = array();
- // SUBJECT
- $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
- if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
+ // SUBJECT
+ $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
+ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
- $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval");
+ $subject = $societeName." - ".$langs->transnoentities("ExpenseReportWaitingForReApproval");
- // CONTENT
- $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+ // CONTENT
+ $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
$link = ''.$link.' ';
$dateRefusEx = explode(" ", $object->date_refuse);
- $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link);
+ $message = $langs->transnoentities("ExpenseReportWaitingForReApprovalMessage", $dateRefusEx[0], $object->detail_refuse, $expediteur->getFullName($langs), $link);
// Rebuild pdf
/*
@@ -507,75 +507,75 @@ if (empty($reshook))
*/
- // PREPARE SEND
- $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
+ // PREPARE SEND
+ $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
- if ($mailfile)
- {
- // SEND
- $result = $mailfile->sendfile();
- if ($result)
- {
- $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
- setEventMessages($mesg, null, 'mesgs');
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- exit;
- } else {
- $langs->load("other");
- if ($mailfile->error)
- {
- $mesg = '';
- $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
- $mesg .= ' '.$mailfile->error;
- setEventMessages($mesg, null, 'errors');
- } else {
- setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
- }
- }
- } else {
- setEventMessages($mailfile->error, $mailfile->errors, 'errors');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
- $action = '';
- }
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
+ if ($mailfile)
+ {
+ // SEND
+ $result = $mailfile->sendfile();
+ if ($result)
+ {
+ $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
+ setEventMessages($mesg, null, 'mesgs');
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ exit;
+ } else {
+ $langs->load("other");
+ if ($mailfile->error)
+ {
+ $mesg = '';
+ $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+ $mesg .= ' '.$mailfile->error;
+ setEventMessages($mesg, null, 'errors');
+ } else {
+ setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+ }
+ }
+ } else {
+ setEventMessages($mailfile->error, $mailfile->errors, 'errors');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+ $action = '';
+ }
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+ }
- // Approve
- if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ // Approve
+ if ($action == "confirm_approve" && GETPOST("confirm", 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- $result = $object->setApproved($user);
+ $result = $object->setApproved($user);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- if ($result > 0)
- {
- // Send mail
+ if ($result > 0)
+ {
+ // Send mail
// TO
$destinataire = new User($db);
@@ -584,7 +584,7 @@ if (empty($reshook))
// CC
$emailCC = $conf->global->NDF_CC_EMAILS;
- if (empty($emailTo)) $emailTo = $emailCC;
+ if (empty($emailTo)) $emailTo = $emailCC;
// FROM
$expediteur = new User($db);
@@ -593,21 +593,21 @@ if (empty($reshook))
if ($emailFrom && $emailTo)
{
- $filename = array(); $filedir = array(); $mimetype = array();
+ $filename = array(); $filedir = array(); $mimetype = array();
- // SUBJECT
- $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
- if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
+ // SUBJECT
+ $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
+ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
- $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved");
+ $subject = $societeName." - ".$langs->transnoentities("ExpenseReportApproved");
- // CONTENT
- $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+ // CONTENT
+ $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
$link = ''.$link.' ';
- $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
+ $message = $langs->transnoentities("ExpenseReportApprovedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
- // Rebuilt pdf
- /*
+ // Rebuilt pdf
+ /*
$object->setDocModel($user,"");
$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
@@ -621,103 +621,103 @@ if (empty($reshook))
}
*/
- $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
+ $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
- if ($mailfile)
- {
- // SEND
- $result = $mailfile->sendfile();
- if ($result)
- {
- $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
- setEventMessages($mesg, null, 'mesgs');
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- exit;
- } else {
- $langs->load("other");
- if ($mailfile->error)
- {
- $mesg = '';
- $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
- $mesg .= ' '.$mailfile->error;
- setEventMessages($mesg, null, 'errors');
- } else {
- setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
- }
- }
- } else {
- setEventMessages($mailfile->error, $mailfile->errors, 'errors');
- $action = '';
- }
+ if ($mailfile)
+ {
+ // SEND
+ $result = $mailfile->sendfile();
+ if ($result)
+ {
+ $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
+ setEventMessages($mesg, null, 'mesgs');
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ exit;
+ } else {
+ $langs->load("other");
+ if ($mailfile->error)
+ {
+ $mesg = '';
+ $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+ $mesg .= ' '.$mailfile->error;
+ setEventMessages($mesg, null, 'errors');
+ } else {
+ setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+ }
+ }
+ } else {
+ setEventMessages($mailfile->error, $mailfile->errors, 'errors');
+ $action = '';
+ }
} else {
- setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
- $action = '';
- }
- } else {
+ setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+ $action = '';
+ }
+ } else {
setEventMessages($langs->trans("FailedtoSetToApprove"), null, 'warnings');
$action = '';
}
}
- if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ if ($action == "confirm_refuse" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->approve)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
$detailRefuse = GETPOST('detail_refuse', 'alpha');
- $result = $object->setDeny($user, $detailRefuse);
+ $result = $object->setDeny($user, $detailRefuse);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- if ($result > 0)
- {
- // Send mail
+ if ($result > 0)
+ {
+ // Send mail
- // TO
- $destinataire = new User($db);
- $destinataire->fetch($object->fk_user_author);
- $emailTo = $destinataire->email;
+ // TO
+ $destinataire = new User($db);
+ $destinataire->fetch($object->fk_user_author);
+ $emailTo = $destinataire->email;
- // FROM
- $expediteur = new User($db);
- $expediteur->fetch($object->fk_user_refuse);
- $emailFrom = $expediteur->email;
+ // FROM
+ $expediteur = new User($db);
+ $expediteur->fetch($object->fk_user_refuse);
+ $emailFrom = $expediteur->email;
- if ($emailFrom && $emailTo)
- {
- $filename = array(); $filedir = array(); $mimetype = array();
+ if ($emailFrom && $emailTo)
+ {
+ $filename = array(); $filedir = array(); $mimetype = array();
- // SUBJECT
- $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
- if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
+ // SUBJECT
+ $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
+ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
- $subject = $societeName." - ".$langs->transnoentities("ExpenseReportRefused");
+ $subject = $societeName." - ".$langs->transnoentities("ExpenseReportRefused");
- // CONTENT
- $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+ // CONTENT
+ $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
$link = ''.$link.' ';
- $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link);
+ $message = $langs->transnoentities("ExpenseReportRefusedMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailRefuse, $link);
- // Rebuilt pdf
- /*
+ // Rebuilt pdf
+ /*
$object->setDocModel($user,"");
$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
@@ -731,111 +731,111 @@ if (empty($reshook))
}
*/
- // PREPARE SEND
- $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
+ // PREPARE SEND
+ $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
- if ($mailfile)
- {
- // SEND
- $result = $mailfile->sendfile();
- if ($result)
- {
- $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
- setEventMessages($mesg, null, 'mesgs');
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- exit;
- } else {
- $langs->load("other");
- if ($mailfile->error)
- {
- $mesg = '';
- $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
- $mesg .= ' '.$mailfile->error;
- setEventMessages($mesg, null, 'errors');
- } else {
- setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
- }
- }
- } else {
- setEventMessages($mailfile->error, $mailfile->errors, 'errors');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings');
- $action = '';
- }
- }
+ if ($mailfile)
+ {
+ // SEND
+ $result = $mailfile->sendfile();
+ if ($result)
+ {
+ $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
+ setEventMessages($mesg, null, 'mesgs');
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ exit;
+ } else {
+ $langs->load("other");
+ if ($mailfile->error)
+ {
+ $mesg = '';
+ $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+ $mesg .= ' '.$mailfile->error;
+ setEventMessages($mesg, null, 'errors');
+ } else {
+ setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+ }
+ }
+ } else {
+ setEventMessages($mailfile->error, $mailfile->errors, 'errors');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("FailedtoSetToDeny"), null, 'warnings');
+ $action = '';
+ }
+ }
- //var_dump($user->id == $object->fk_user_validator);exit;
- if ($action == "confirm_cancel" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
- {
- if (!GETPOST('detail_cancel', 'alpha'))
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors');
- } else {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ //var_dump($user->id == $object->fk_user_validator);exit;
+ if ($action == "confirm_cancel" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
+ {
+ if (!GETPOST('detail_cancel', 'alpha'))
+ {
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors');
+ } else {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- if ($user->id == $object->fk_user_valid || $user->id == $object->fk_user_author)
- {
+ if ($user->id == $object->fk_user_valid || $user->id == $object->fk_user_author)
+ {
$detailCancel = GETPOST('detail_cancel', 'alpha');
- $result = $object->set_cancel($user, $detailCancel);
+ $result = $object->set_cancel($user, $detailCancel);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- if ($result > 0)
- {
- // Send mail
+ if ($result > 0)
+ {
+ // Send mail
- // TO
- $destinataire = new User($db);
- $destinataire->fetch($object->fk_user_author);
- $emailTo = $destinataire->email;
+ // TO
+ $destinataire = new User($db);
+ $destinataire->fetch($object->fk_user_author);
+ $emailTo = $destinataire->email;
- // FROM
- $expediteur = new User($db);
- $expediteur->fetch($object->fk_user_cancel);
- $emailFrom = $expediteur->email;
+ // FROM
+ $expediteur = new User($db);
+ $expediteur->fetch($object->fk_user_cancel);
+ $emailFrom = $expediteur->email;
- if ($emailFrom && $emailTo)
- {
- $filename = array(); $filedir = array(); $mimetype = array();
+ if ($emailFrom && $emailTo)
+ {
+ $filename = array(); $filedir = array(); $mimetype = array();
- // SUBJECT
- $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
- if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
+ // SUBJECT
+ $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
+ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
- $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled");
+ $subject = $societeName." - ".$langs->transnoentities("ExpenseReportCanceled");
- // CONTENT
- $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+ // CONTENT
+ $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
$link = ''.$link.' ';
- $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link);
+ $message = $langs->transnoentities("ExpenseReportCanceledMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $detailCancel, $link);
- // Rebuilt pdf
- /*
+ // Rebuilt pdf
+ /*
$object->setDocModel($user,"");
$resultPDF = expensereport_pdf_create($db,$object,'',"",$langs);
@@ -849,318 +849,318 @@ if (empty($reshook))
}
*/
- // PREPARE SEND
- $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
+ // PREPARE SEND
+ $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
- if ($mailfile)
- {
- // SEND
- $result = $mailfile->sendfile();
- if ($result)
- {
- $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
- setEventMessages($mesg, null, 'mesgs');
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- exit;
- } else {
- $langs->load("other");
- if ($mailfile->error)
- {
- $mesg = '';
- $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
- $mesg .= ' '.$mailfile->error;
- setEventMessages($mesg, null, 'errors');
- } else {
- setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
- }
- }
- } else {
- setEventMessages($mailfile->error, $mailfile->errors, 'errors');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings');
- $action = '';
- }
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- }
+ if ($mailfile)
+ {
+ // SEND
+ $result = $mailfile->sendfile();
+ if ($result)
+ {
+ $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
+ setEventMessages($mesg, null, 'mesgs');
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ exit;
+ } else {
+ $langs->load("other");
+ if ($mailfile->error)
+ {
+ $mesg = '';
+ $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+ $mesg .= ' '.$mailfile->error;
+ setEventMessages($mesg, null, 'errors');
+ } else {
+ setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+ }
+ }
+ } else {
+ setEventMessages($mailfile->error, $mailfile->errors, 'errors');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("FailedToSetToCancel"), null, 'warnings');
+ $action = '';
+ }
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+ }
+ }
- if ($action == "confirm_setdraft" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
- if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid)
- {
- $result = $object->setStatut(0);
+ if ($action == "confirm_setdraft" && GETPOST('confirm', 'alpha') == "yes" && $id > 0 && $user->rights->expensereport->creer)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
+ if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid)
+ {
+ $result = $object->setStatut(0);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- if ($result > 0)
- {
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- } else {
- setEventMessages("NOT_AUTHOR", '', 'errors');
- }
- }
+ if ($result > 0)
+ {
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+ } else {
+ setEventMessages("NOT_AUTHOR", '', 'errors');
+ }
+ }
- if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- $result = $object->set_unpaid($user);
+ $result = $object->set_unpaid($user);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
+ }
- if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ if ($action == 'set_unpaid' && $id > 0 && $user->rights->expensereport->to_paid)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- $result = $object->set_unpaid($user);
+ $result = $object->set_unpaid($user);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
+ }
- if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ if ($action == 'set_paid' && $id > 0 && $user->rights->expensereport->to_paid)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- $result = $object->set_paid($id, $user);
+ $result = $object->set_paid($id, $user);
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- if ($result > 0)
- {
- // Send mail
+ if ($result > 0)
+ {
+ // Send mail
- // TO
- $destinataire = new User($db);
- $destinataire->fetch($object->fk_user_author);
- $emailTo = $destinataire->email;
+ // TO
+ $destinataire = new User($db);
+ $destinataire->fetch($object->fk_user_author);
+ $emailTo = $destinataire->email;
- // FROM
- $expediteur = new User($db);
- $expediteur->fetch($user->id);
- $emailFrom = $expediteur->email;
+ // FROM
+ $expediteur = new User($db);
+ $expediteur->fetch($user->id);
+ $emailFrom = $expediteur->email;
- if ($emailFrom && $emailTo)
- {
- $filename = array(); $filedir = array(); $mimetype = array();
+ if ($emailFrom && $emailTo)
+ {
+ $filename = array(); $filedir = array(); $mimetype = array();
- // SUBJECT
- $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
- if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
+ // SUBJECT
+ $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
+ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $societeName = $conf->global->MAIN_APPLICATION_TITLE;
- $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid");
+ $subject = $societeName." - ".$langs->transnoentities("ExpenseReportPaid");
- // CONTENT
- $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
+ // CONTENT
+ $link = $urlwithroot.'/expensereport/card.php?id='.$object->id;
$link = ''.$link.' ';
- $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
+ $message = $langs->transnoentities("ExpenseReportPaidMessage", $object->ref, $destinataire->getFullName($langs), $expediteur->getFullName($langs), $link);
- // Generate pdf before attachment
- $object->setDocModel($user, "");
- $resultPDF = expensereport_pdf_create($db, $object, '', "", $langs);
+ // Generate pdf before attachment
+ $object->setDocModel($user, "");
+ $resultPDF = expensereport_pdf_create($db, $object, '', "", $langs);
- // PREPARE SEND
- $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
+ // PREPARE SEND
+ $mailfile = new CMailFile($subject, $emailTo, $emailFrom, $message, $filedir, $mimetype, $filename, '', '', 0, -1);
- if ($mailfile)
- {
- // SEND
- $result = $mailfile->sendfile();
- if ($result)
- {
- $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
- setEventMessages($mesg, null, 'mesgs');
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- exit;
- } else {
- $langs->load("other");
- if ($mailfile->error)
- {
- $mesg = '';
- $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
- $mesg .= ' '.$mailfile->error;
- setEventMessages($mesg, null, 'errors');
- } else {
- setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
- }
- }
- } else {
- setEventMessages($mailfile->error, $mailfile->errors, 'errors');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
- $action = '';
- }
- } else {
- setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings');
- $action = '';
- }
- }
+ if ($mailfile)
+ {
+ // SEND
+ $result = $mailfile->sendfile();
+ if ($result)
+ {
+ $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($emailFrom, 2), $mailfile->getValidAddress($emailTo, 2));
+ setEventMessages($mesg, null, 'mesgs');
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ exit;
+ } else {
+ $langs->load("other");
+ if ($mailfile->error)
+ {
+ $mesg = '';
+ $mesg .= $langs->trans('ErrorFailedToSendMail', $emailFrom, $emailTo);
+ $mesg .= ' '.$mailfile->error;
+ setEventMessages($mesg, null, 'errors');
+ } else {
+ setEventMessages('No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS', null, 'warnings');
+ }
+ }
+ } else {
+ setEventMessages($mailfile->error, $mailfile->errors, 'errors');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("NoEmailSentBadSenderOrRecipientEmail"), null, 'warnings');
+ $action = '';
+ }
+ } else {
+ setEventMessages($langs->trans("FailedToSetPaid"), null, 'warnings');
+ $action = '';
+ }
+ }
- if ($action == "addline" && $user->rights->expensereport->creer)
- {
- $error = 0;
+ if ($action == "addline" && $user->rights->expensereport->creer)
+ {
+ $error = 0;
- // First save uploaded file
- $fk_ecm_files = 0;
- if (GETPOSTISSET('attachfile'))
- {
- $arrayoffiles = GETPOST('attachfile', 'array');
- if (is_array($arrayoffiles) && !empty($arrayoffiles[0]))
- {
- include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
- $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0];
- $ecmfiles = new EcmFiles($db);
- $ecmfiles->fetch(0, '', $relativepath);
- $fk_ecm_files = $ecmfiles->id;
- }
- }
+ // First save uploaded file
+ $fk_ecm_files = 0;
+ if (GETPOSTISSET('attachfile'))
+ {
+ $arrayoffiles = GETPOST('attachfile', 'array');
+ if (is_array($arrayoffiles) && !empty($arrayoffiles[0]))
+ {
+ include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
+ $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0];
+ $ecmfiles = new EcmFiles($db);
+ $ecmfiles->fetch(0, '', $relativepath);
+ $fk_ecm_files = $ecmfiles->id;
+ }
+ }
// if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary.
- if (empty($vatrate)) $vatrate = "0.000";
- $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate));
+ if (empty($vatrate)) $vatrate = "0.000";
+ $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate));
$value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU');
$value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU');
if (empty($value_unit))
{
- $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU');
+ $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU');
}
$fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int');
- $qty = GETPOST('qty', 'int');
- if (empty($qty)) $qty = 1;
+ $qty = GETPOST('qty', 'int');
+ if (empty($qty)) $qty = 1;
- if (!($fk_c_type_fees > 0))
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
- $action = '';
- }
+ if (!($fk_c_type_fees > 0))
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
+ $action = '';
+ }
- if ((int) $tmpvat < 0 || $tmpvat == '')
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("VAT")), null, 'errors');
- $action = '';
- }
+ if ((int) $tmpvat < 0 || $tmpvat == '')
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("VAT")), null, 'errors');
+ $action = '';
+ }
- // Si aucune date n'est rentrée
- if (empty($date) || $date == "--")
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
- }
- // Si aucun prix n'est rentré
- if ($value_unit == 0)
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PriceUTTC")), null, 'errors');
- }
- // Warning if date out of range
- if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1)))
- {
- $langs->load("errors");
- setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings');
- }
+ // Si aucune date n'est rentrée
+ if (empty($date) || $date == "--")
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
+ }
+ // Si aucun prix n'est rentré
+ if ($value_unit == 0)
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PriceUTTC")), null, 'errors');
+ }
+ // Warning if date out of range
+ if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1)))
+ {
+ $langs->load("errors");
+ setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings');
+ }
- if (!$error)
- {
- $type = 0; // TODO What if service ? We should take the type product/service from the type of expense report llx_c_type_fees
+ if (!$error)
+ {
+ $type = 0; // TODO What if service ? We should take the type product/service from the type of expense report llx_c_type_fees
// Insert line
- $result = $object->addline($qty, $value_unit, $fk_c_type_fees, $vatrate, $date, $comments, $fk_project, $fk_c_exp_tax_cat, $type, $fk_ecm_files);
+ $result = $object->addline($qty, $value_unit, $fk_c_type_fees, $vatrate, $date, $comments, $fk_project, $fk_c_exp_tax_cat, $type, $fk_ecm_files);
if ($result > 0)
{
$ret = $object->fetch($object->id); // Reload to get new records
@@ -1176,7 +1176,7 @@ if (empty($reshook))
$outputlangs->setDefaultLang($newlang);
}
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
unset($qty);
@@ -1191,159 +1191,159 @@ if (empty($reshook))
} else {
setEventMessages($object->error, $object->errors, 'errors');
}
- }
+ }
- $action = '';
- }
+ $action = '';
+ }
- if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ if ($action == 'confirm_delete_line' && GETPOST("confirm", 'alpha') == "yes" && $user->rights->expensereport->creer)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- $object_ligne = new ExpenseReportLine($db);
- $object_ligne->fetch(GETPOST("rowid", 'int'));
- $total_ht = $object_ligne->total_ht;
- $total_tva = $object_ligne->total_tva;
+ $object_ligne = new ExpenseReportLine($db);
+ $object_ligne->fetch(GETPOST("rowid", 'int'));
+ $total_ht = $object_ligne->total_ht;
+ $total_tva = $object_ligne->total_tva;
- $result = $object->deleteline(GETPOST("rowid", 'int'), $user);
- if ($result >= 0)
- {
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ $result = $object->deleteline(GETPOST("rowid", 'int'), $user);
+ if ($result >= 0)
+ {
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- $object->update_totaux_del($object_ligne->total_ht, $object_ligne->total_tva);
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_GET['id']);
- exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
+ $object->update_totaux_del($object_ligne->total_ht, $object_ligne->total_tva);
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$_GET['id']);
+ exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+ }
- if ($action == "updateline" && $user->rights->expensereport->creer)
- {
- $object = new ExpenseReport($db);
- $object->fetch($id);
+ if ($action == "updateline" && $user->rights->expensereport->creer)
+ {
+ $object = new ExpenseReport($db);
+ $object->fetch($id);
- // First save uploaded file
- $fk_ecm_files = 0;
- if (GETPOSTISSET('attachfile'))
- {
- $arrayoffiles = GETPOST('attachfile', 'array');
- if (is_array($arrayoffiles) && !empty($arrayoffiles[0]))
- {
- include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
- $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0];
- $ecmfiles = new EcmFiles($db);
- $ecmfiles->fetch(0, '', $relativepath);
- $fk_ecm_files = $ecmfiles->id;
- }
- }
+ // First save uploaded file
+ $fk_ecm_files = 0;
+ if (GETPOSTISSET('attachfile'))
+ {
+ $arrayoffiles = GETPOST('attachfile', 'array');
+ if (is_array($arrayoffiles) && !empty($arrayoffiles[0]))
+ {
+ include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
+ $relativepath = 'expensereport/'.$object->ref.'/'.$arrayoffiles[0];
+ $ecmfiles = new EcmFiles($db);
+ $ecmfiles->fetch(0, '', $relativepath);
+ $fk_ecm_files = $ecmfiles->id;
+ }
+ }
- $rowid = $_POST['rowid'];
- $type_fees_id = GETPOST('fk_c_type_fees', 'int');
+ $rowid = $_POST['rowid'];
+ $type_fees_id = GETPOST('fk_c_type_fees', 'int');
$fk_c_exp_tax_cat = GETPOST('fk_c_exp_tax_cat', 'int');
- $projet_id = $fk_project;
- $comments = GETPOST('comments', 'none');
- $qty = GETPOST('qty', 'int');
- $vatrate = GETPOST('vatrate', 'alpha');
+ $projet_id = $fk_project;
+ $comments = GETPOST('comments', 'none');
+ $qty = GETPOST('qty', 'int');
+ $vatrate = GETPOST('vatrate', 'alpha');
- // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary.
- if (empty($vatrate)) $vatrate = "0.000";
- $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate));
+ // if VAT is not used in Dolibarr, set VAT rate to 0 because VAT rate is necessary.
+ if (empty($vatrate)) $vatrate = "0.000";
+ $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $vatrate));
- $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU');
- $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU');
- if (empty($value_unit))
- {
- $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU');
- }
+ $value_unit_ht = price2num(GETPOST('value_unit_ht', 'alpha'), 'MU');
+ $value_unit = price2num(GETPOST('value_unit', 'alpha'), 'MU');
+ if (empty($value_unit))
+ {
+ $value_unit = price2num($value_unit_ht + ($value_unit_ht * $tmpvat / 100), 'MU');
+ }
- if (!GETPOST('fk_c_type_fees', 'int') > 0)
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
- $action = '';
- }
- if ((int) $tmpvat < 0 || $tmpvat == '')
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Vat")), null, 'errors');
- $action = '';
- }
- // Warning if date out of range
+ if (!GETPOST('fk_c_type_fees', 'int') > 0)
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
+ $action = '';
+ }
+ if ((int) $tmpvat < 0 || $tmpvat == '')
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Vat")), null, 'errors');
+ $action = '';
+ }
+ // Warning if date out of range
if ($date < $object->date_debut || $date > ($object->date_fin + (24 * 3600 - 1)))
- {
- $langs->load("errors");
- setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings');
- }
+ {
+ $langs->load("errors");
+ setEventMessages($langs->trans("WarningDateOfLineMustBeInExpenseReportRange"), null, 'warnings');
+ }
- if (!$error)
- {
- // TODO Use update method of ExpenseReportLine
- $result = $object->updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $id, $fk_c_exp_tax_cat, $fk_ecm_files);
- if ($result >= 0)
- {
- if ($result > 0)
- {
- // Define output language
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- $outputlangs = $langs;
- $newlang = '';
- if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
- if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
- if (!empty($newlang)) {
- $outputlangs = new Translate("", $conf);
- $outputlangs->setDefaultLang($newlang);
- }
- $model = $object->modelpdf;
- $ret = $object->fetch($id); // Reload to get new records
+ if (!$error)
+ {
+ // TODO Use update method of ExpenseReportLine
+ $result = $object->updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $id, $fk_c_exp_tax_cat, $fk_ecm_files);
+ if ($result >= 0)
+ {
+ if ($result > 0)
+ {
+ // Define output language
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ $outputlangs = $langs;
+ $newlang = '';
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
+ if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
+ if (!empty($newlang)) {
+ $outputlangs = new Translate("", $conf);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ $model = $object->model_pdf;
+ $ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
- }
+ $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+ }
- $result = $object->recalculer($id);
+ $result = $object->recalculer($id);
- //header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
- //exit;
- } else {
- setEventMessages($object->error, $object->errors, 'errors');
- }
- }
- }
+ //header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
+ //exit;
+ } else {
+ setEventMessages($object->error, $object->errors, 'errors');
+ }
+ }
+ }
// Actions when printing a doc from card
- include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
+ include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
- // Actions to send emails
- $triggersendname = 'EXPENSEREPORT_SENTBYMAIL';
- $autocopy = 'MAIN_MAIL_AUTOCOPY_EXPENSEREPORT_TO';
- $trackid = 'exp'.$object->id;
- include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
+ // Actions to send emails
+ $triggersendname = 'EXPENSEREPORT_SENTBYMAIL';
+ $autocopy = 'MAIN_MAIL_AUTOCOPY_EXPENSEREPORT_TO';
+ $trackid = 'exp'.$object->id;
+ include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
- // Actions to build doc
- $upload_dir = $conf->expensereport->dir_output;
- $permissiontoadd = $user->rights->expensereport->creer;
- include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
+ // Actions to build doc
+ $upload_dir = $conf->expensereport->dir_output;
+ $permissiontoadd = $user->rights->expensereport->creer;
+ include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
}
@@ -1399,8 +1399,8 @@ if ($action == 'create')
print '';
$defaultselectuser = $user->id;
if (GETPOST('fk_user_author', 'int') > 0) $defaultselectuser = GETPOST('fk_user_author', 'int');
- $include_users = 'hierarchyme';
- if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expensereport->writeall_advance)) $include_users = array();
+ $include_users = 'hierarchyme';
+ if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expensereport->writeall_advance)) $include_users = array();
$s = $form->select_dolusers($defaultselectuser, "fk_user_author", 0, "", 0, $include_users, '', '0,'.$conf->entity);
print $s;
print ' ';
@@ -1414,11 +1414,11 @@ if ($action == 'create')
$include_users = $object->fetch_users_approver_expensereport();
if (empty($include_users)) print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateExpenseReport");
else {
- $defaultselectuser = (empty($user->fk_user_expense_validator) ? $user->fk_user : $user->fk_user_expense_validator); // Will work only if supervisor has permission to approve so is inside include_users
- if (!empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR)) $defaultselectuser = $conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR; // Can force default approver
- if (GETPOST('fk_user_validator', 'int') > 0) $defaultselectuser = GETPOST('fk_user_validator', 'int');
- $s = $form->select_dolusers($defaultselectuser, "fk_user_validator", 1, "", ((empty($defaultselectuser) || empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR_UNCHANGEABLE)) ? 0 : 1), $include_users);
- print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
+ $defaultselectuser = (empty($user->fk_user_expense_validator) ? $user->fk_user : $user->fk_user_expense_validator); // Will work only if supervisor has permission to approve so is inside include_users
+ if (!empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR)) $defaultselectuser = $conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR; // Can force default approver
+ if (GETPOST('fk_user_validator', 'int') > 0) $defaultselectuser = GETPOST('fk_user_validator', 'int');
+ $s = $form->select_dolusers($defaultselectuser, "fk_user_validator", 1, "", ((empty($defaultselectuser) || empty($conf->global->EXPENSEREPORT_DEFAULT_VALIDATOR_UNCHANGEABLE)) ? 0 : 1), $include_users);
+ print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
}
print '';
print '';
@@ -1457,9 +1457,9 @@ if ($action == 'create')
// Other attributes
$parameters = array('colspan' => ' colspan="3"', 'cols' => 3);
$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by
- print $hookmanager->resPrint;
+ print $hookmanager->resPrint;
if (empty($reshook)) {
- print $object->showOptionals($extrafields, 'edit', $parameters);
+ print $object->showOptionals($extrafields, 'edit', $parameters);
}
print '';
@@ -1485,7 +1485,7 @@ if ($action == 'create')
if (!in_array($object->fk_user_author, $user->getAllChildIds(1)))
{
if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)
- && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)))
+ && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance)))
{
print load_fiche_titre($langs->trans('TripCard'), '', 'trip');
@@ -1494,8 +1494,8 @@ if ($action == 'create')
print '';
// End of page
- llxFooter();
- $db->close();
+ llxFooter();
+ $db->close();
exit;
}
@@ -1528,15 +1528,15 @@ if ($action == 'create')
$userfee = new User($db);
if ($object->fk_user_author > 0)
{
- $userfee->fetch($object->fk_user_author);
- print $userfee->getNomUrl(-1);
+ $userfee->fetch($object->fk_user_author);
+ print $userfee->getNomUrl(-1);
}
print '';
- // Ref
- print ''.$langs->trans("Ref").' ';
- print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '');
- print ' ';
+ // Ref
+ print ''.$langs->trans("Ref").' ';
+ print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '');
+ print ' ';
print '';
print ''.$langs->trans("DateStart").' ';
@@ -1611,15 +1611,15 @@ if ($action == 'create')
// Clone confirmation
if ($action == 'clone') {
- // Create an array for form
- $criteriaforfilter = 'hierarchyme';
- if (!empty($user->rights->expensereport->readall)) $criteriaforfilter = '';
- $formquestion = array(
- 'text' => '',
- array('type' => 'other', 'name' => 'fk_user_author', 'label' => $langs->trans("SelectTargetUser"), 'value' => $form->select_dolusers((GETPOST('fk_user_author', 'int') > 0 ? GETPOST('fk_user_author', 'int') : $user->id), 'fk_user_author', 0, null, 0, $criteriaforfilter))
- );
- // Paiement incomplet. On demande si motif = escompte ou autre
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneExpenseReport', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
+ // Create an array for form
+ $criteriaforfilter = 'hierarchyme';
+ if (!empty($user->rights->expensereport->readall)) $criteriaforfilter = '';
+ $formquestion = array(
+ 'text' => '',
+ array('type' => 'other', 'name' => 'fk_user_author', 'label' => $langs->trans("SelectTargetUser"), 'value' => $form->select_dolusers((GETPOST('fk_user_author', 'int') > 0 ? GETPOST('fk_user_author', 'int') : $user->id), 'fk_user_author', 0, null, 0, $criteriaforfilter))
+ );
+ // Paiement incomplet. On demande si motif = escompte ou autre
+ $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneExpenseReport', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
}
if ($action == 'save')
@@ -1655,7 +1655,7 @@ if ($action == 'create')
if ($action == 'setdraft')
{
- $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1);
+ $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("BrouillonnerTrip"), $langs->trans("ConfirmBrouillonnerTrip"), "confirm_setdraft", "", "", 1);
}
if ($action == 'refuse') // Deny
@@ -1730,10 +1730,10 @@ if ($action == 'create')
print '';
if ($object->fk_user_author > 0)
{
- $userauthor = new User($db);
- $result = $userauthor->fetch($object->fk_user_author);
- if ($result < 0) dol_print_error('', $userauthor->error);
- elseif ($result > 0) print $userauthor->getNomUrl(-1);
+ $userauthor = new User($db);
+ $result = $userauthor->fetch($object->fk_user_author);
+ if ($result < 0) dol_print_error('', $userauthor->error);
+ elseif ($result > 0) print $userauthor->getNomUrl(-1);
}
print ' ';
@@ -1773,8 +1773,8 @@ if ($action == 'create')
if ($result > 0) print $userfee->getNomUrl(-1);
if (empty($userfee->email) || !isValidEmail($userfee->email))
{
- $langs->load("errors");
- print img_warning($langs->trans("ErrorBadEMail", $userfee->email));
+ $langs->load("errors");
+ print img_warning($langs->trans("ErrorBadEMail", $userfee->email));
}
}
print '';
@@ -1835,7 +1835,7 @@ if ($action == 'create')
print '';
}
- if ($object->fk_statut == 6)
+ if ($object->fk_statut == $object::STATUS_CLOSED)
{
/* TODO this fields are not yet filled
print '';
@@ -1924,26 +1924,25 @@ if ($action == 'create')
$resql = $db->query($sql);
if ($resql)
{
- $num = $db->num_rows($resql);
- $i = 0; $totalpaid = 0;
- while ($i < $num)
- {
- $objp = $db->fetch_object($resql);
+ $num = $db->num_rows($resql);
+ $i = 0; $totalpaid = 0;
+ while ($i < $num)
+ {
+ $objp = $db->fetch_object($resql);
- $paymentexpensereportstatic->id = $objp->rowid;
- $paymentexpensereportstatic->datepaye = $db->jdate($objp->dp);
- $paymentexpensereportstatic->ref = $objp->rowid;
- $paymentexpensereportstatic->num_paiement = $objp->num_payment;
- $paymentexpensereportstatic->num_payment = $objp->num_payment;
- $paymentexpensereportstatic->payment_code = $objp->payment_code;
+ $paymentexpensereportstatic->id = $objp->rowid;
+ $paymentexpensereportstatic->datepaye = $db->jdate($objp->dp);
+ $paymentexpensereportstatic->ref = $objp->rowid;
+ $paymentexpensereportstatic->num_payment = $objp->num_payment;
+ $paymentexpensereportstatic->payment_code = $objp->payment_code;
- print ' ';
- print '';
+ print ' ';
+ print '';
print $paymentexpensereportstatic->getNomUrl(1);
print ' ';
- print ''.dol_print_date($db->jdate($objp->dp), 'day')." \n";
- $labeltype = $langs->trans("PaymentType".$objp->p_code) != ("PaymentType".$objp->p_code) ? $langs->trans("PaymentType".$objp->p_code) : $objp->payment_type;
- print "".$labeltype.' '.$objp->num_payment." \n";
+ print ''.dol_print_date($db->jdate($objp->dp), 'day')." \n";
+ $labeltype = $langs->trans("PaymentType".$objp->p_code) != ("PaymentType".$objp->p_code) ? $langs->trans("PaymentType".$objp->p_code) : $objp->payment_type;
+ print "".$labeltype.' '.$objp->num_payment." \n";
if (!empty($conf->banque->enabled))
{
$bankaccountstatic->id = $objp->baid;
@@ -1964,39 +1963,39 @@ if ($action == 'create')
print $bankaccountstatic->getNomUrl(1, 'transactions');
print '';
}
- print ''.price($objp->amount)." ";
- print ' ';
- print " ";
- $totalpaid += $objp->amount;
- $i++;
- }
+ print ''.price($objp->amount)." ";
+ print ' ';
+ print "";
+ $totalpaid += $objp->amount;
+ $i++;
+ }
if (!is_null($totalpaid))
{
- $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop
+ $totalpaid = price2num($totalpaid); // Round $totalpaid to fix floating problem after addition into loop
}
- $remaintopay = price2num($object->total_ttc - $totalpaid);
- $resteapayeraffiche = $remaintopay;
+ $remaintopay = price2num($object->total_ttc - $totalpaid);
+ $resteapayeraffiche = $remaintopay;
- $cssforamountpaymentcomplete = 'amountpaymentcomplete';
+ $cssforamountpaymentcomplete = 'amountpaymentcomplete';
- if ($object->status == ExpenseReport::STATUS_REFUSED)
- {
- $cssforamountpaymentcomplete = 'amountpaymentneutral';
- $resteapayeraffiche = 0;
- } elseif ($object->paid == 0)
- {
- $cssforamountpaymentcomplete = 'amountpaymentneutral';
- }
- print ''.$langs->trans("AlreadyPaid").': '.price($totalpaid).' ';
- print ''.$langs->trans("AmountExpected").': '.price($object->total_ttc).' ';
+ if ($object->status == ExpenseReport::STATUS_REFUSED)
+ {
+ $cssforamountpaymentcomplete = 'amountpaymentneutral';
+ $resteapayeraffiche = 0;
+ } elseif ($object->paid == 0)
+ {
+ $cssforamountpaymentcomplete = 'amountpaymentneutral';
+ }
+ print ''.$langs->trans("AlreadyPaid").': '.price($totalpaid).' ';
+ print ''.$langs->trans("AmountExpected").': '.price($object->total_ttc).' ';
- print ''.$langs->trans("RemainderToPay").': ';
- print ''.price($resteapayeraffiche).' ';
+ print ''.$langs->trans("RemainderToPay").': ';
+ print ''.price($resteapayeraffiche).' ';
- $db->free($resql);
+ $db->free($resql);
} else {
- dol_print_error($db);
+ dol_print_error($db);
}
print "
";
@@ -2029,8 +2028,8 @@ if ($action == 'create')
//print '
'.$langs->trans('Piece').' ';
print '
'.$langs->trans('Date').' ';
if (!empty($conf->projet->enabled)) print '
'.$langs->trans('Project').' ';
- if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print '
'.$langs->trans('CarCategory').' ';
print '
'.$langs->trans('Type').' ';
+ if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print '
'.$langs->trans('CarCategory').' ';
print '
'.$langs->trans('Description').' ';
print '
'.$langs->trans('VAT').' ';
print '
'.$langs->trans('PriceUHT').' ';
@@ -2041,7 +2040,7 @@ if ($action == 'create')
print '
'.$langs->trans('AmountHT').' ';
print '
'.$langs->trans('AmountTTC').' ';
}
- // Picture
+ // Picture
print '
';
print ' ';
// Ajout des boutons de modification/suppression
@@ -2080,6 +2079,13 @@ if ($action == 'create')
}
print '';
}
+
+ // Type of fee
+ print '
';
+ $labeltype = ($langs->trans(($line->type_fees_code)) == $line->type_fees_code ? $line->type_fees_libelle : $langs->trans($line->type_fees_code));
+ print $labeltype;
+ print ' ';
+
// IK
if (!empty($conf->global->MAIN_USE_EXPENSE_IK))
{
@@ -2087,24 +2093,20 @@ if ($action == 'create')
print dol_getIdFromCode($db, $line->fk_c_exp_tax_cat, 'c_exp_tax_cat', 'rowid', 'label');
print '';
}
- // Type of fee
- print '
';
- $labeltype = ($langs->trans(($line->type_fees_code)) == $line->type_fees_code ? $line->type_fees_libelle : $langs->trans($line->type_fees_code));
- print $labeltype;
- print ' ';
+
// Comment
print '
'.dol_nl2br($line->comments).' ';
// VAT rate
print '
'.vatrate($line->vatrate, true).' ';
- // Unit price HT
+ // Unit price HT
print '
';
if (!empty($line->value_unit_ht))
{
- print price($line->value_unit_ht);
+ print price($line->value_unit_ht);
} else {
- $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate));
- $pricenettoshow = price2num($line->value_unit / (1 + $tmpvat / 100), 'MU');
- print $pricenettoshow;
+ $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $line->vatrate));
+ $pricenettoshow = price2num($line->value_unit / (1 + $tmpvat / 100), 'MU');
+ print $pricenettoshow;
}
print ' ';
@@ -2122,71 +2124,71 @@ if ($action == 'create')
print '
';
if ($line->fk_ecm_files > 0)
{
- $modulepart = 'expensereport';
- $maxheightmini = 32;
+ $modulepart = 'expensereport';
+ $maxheightmini = 32;
- $result = $ecmfilesstatic->fetch($line->fk_ecm_files);
- if ($result > 0)
- {
- $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath);
- $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename);
- if (image_format_supported($fileinfo['basename']) > 0)
- {
- $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
- if (!dol_is_file($conf->expensereport->dir_output.'/'.$relativepath.'/'.$minifile)) $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
- //print $file['path'].'/'.$minifile.' ';
- $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.'/'.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
- if (empty($urlforhref)) {
- $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
- print '';
- } else {
- print ' ';
- }
- print ' ';
- print ' ';
- } else {
- $modulepart = 'expensereport';
- $thumbshown = 0;
- if (preg_match('/\.pdf$/i', $ecmfilesstatic->filename))
- {
- $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename;
- $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename.'_preview.png';
- $relativepathimage = $relativepath.'/'.$ecmfilesstatic->filename.'_preview.png';
+ $result = $ecmfilesstatic->fetch($line->fk_ecm_files);
+ if ($result > 0)
+ {
+ $relativepath = preg_replace('/expensereport\//', '', $ecmfilesstatic->filepath);
+ $fileinfo = pathinfo($ecmfilesstatic->filepath.'/'.$ecmfilesstatic->filename);
+ if (image_format_supported($fileinfo['basename']) > 0)
+ {
+ $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
+ if (!dol_is_file($conf->expensereport->dir_output.'/'.$relativepath.'/'.$minifile)) $minifile = getImageFileNameForSize($fileinfo['basename'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
+ //print $file['path'].'/'.$minifile.' ';
+ $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.'/'.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
+ if (empty($urlforhref)) {
+ $urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
+ print '';
+ } else {
+ print ' ';
+ }
+ print ' ';
+ print ' ';
+ } else {
+ $modulepart = 'expensereport';
+ $thumbshown = 0;
+ if (preg_match('/\.pdf$/i', $ecmfilesstatic->filename))
+ {
+ $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename;
+ $fileimage = $conf->expensereport->dir_output.'/'.$relativepath.'/'.$ecmfilesstatic->filename.'_preview.png';
+ $relativepathimage = $relativepath.'/'.$ecmfilesstatic->filename.'_preview.png';
- $pdfexists = file_exists($filepdf);
- if ($pdfexists)
- {
- // Conversion du PDF en image png si fichier png non existant
- if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
- {
- if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
- {
- include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
- if ($ret < 0) $error++;
- }
- }
- }
+ $pdfexists = file_exists($filepdf);
+ if ($pdfexists)
+ {
+ // Conversion du PDF en image png si fichier png non existant
+ if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
+ {
+ if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
+ {
+ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
+ if ($ret < 0) $error++;
+ }
+ }
+ }
- if ($pdfexists && !$error)
- {
- $heightforphotref = 70;
- if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
- // If the preview file is found
- if (file_exists($fileimage))
- {
- $thumbshown = 1;
- print ' ';
- }
- }
- }
+ if ($pdfexists && !$error)
+ {
+ $heightforphotref = 70;
+ if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
+ // If the preview file is found
+ if (file_exists($fileimage))
+ {
+ $thumbshown = 1;
+ print ' ';
+ }
+ }
+ }
- if (!$thumbshown)
- {
- print img_mime($ecmfilesstatic->filename);
- }
- }
- }
+ if (!$thumbshown)
+ {
+ print img_mime($ecmfilesstatic->filename);
+ }
+ }
+ }
}
print ' ';
@@ -2210,30 +2212,30 @@ if ($action == 'create')
if ($action == 'editline' && $line->rowid == GETPOST('rowid', 'int'))
{
- // Add line with link to add new file or attach line to an existing file
- $colspan = 10;
- if (!empty($conf->projet->enabled)) $colspan++;
- if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++;
+ // Add line with link to add new file or attach line to an existing file
+ $colspan = 10;
+ if (!empty($conf->projet->enabled)) $colspan++;
+ if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++;
- print '
';
+ print ' ';
- print '';
- print $numline;
- print ' ';
+ print '';
+ print $numline;
+ print ' ';
- print '';
- print ''.$langs->trans("UploadANewFileNow");
- print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
- print ' ';
- if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
- {
- print ' - '.$langs->trans("AttachTheNewLineToTheDocument");
- print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
- print ' ';
- }
+ print ' ';
+ print ''.$langs->trans("UploadANewFileNow");
+ print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
+ print ' ';
+ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
+ {
+ print ' - '.$langs->trans("AttachTheNewLineToTheDocument");
+ print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
+ print ' ';
+ }
- print ''."\n";
- print ' ';
+ print ''."\n";
+ print '
';
- $filenamelinked = '';
- if ($line->fk_ecm_files > 0)
- {
- $result = $ecmfilesstatic->fetch($line->fk_ecm_files);
- if ($result > 0)
- {
- $filenamelinked = $ecmfilesstatic->filename;
- }
- }
+ $filenamelinked = '';
+ if ($line->fk_ecm_files > 0)
+ {
+ $result = $ecmfilesstatic->fetch($line->fk_ecm_files);
+ if ($result > 0)
+ {
+ $filenamelinked = $ecmfilesstatic->filename;
+ }
+ }
- $tredited = 'tredited';
- include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php';
- include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php';
+ $tredited = 'tredited';
+ include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php';
+ include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php';
print '';
@@ -2285,6 +2287,11 @@ if ($action == 'create')
print '';
}
+ // Select type
+ print '';
+ print select_type_fees_id($line->fk_c_type_fees, 'fk_c_type_fees');
+ print ' ';
+
if (!empty($conf->global->MAIN_USE_EXPENSE_IK))
{
print '';
@@ -2293,11 +2300,6 @@ if ($action == 'create')
print ' ';
}
- // Select type
- print '';
- select_type_fees_id($line->fk_c_type_fees, 'fk_c_type_fees');
- print ' ';
-
// Add comments
print '';
print '';
@@ -2344,44 +2346,44 @@ if ($action == 'create')
}
}
- // Add a line
+ // Add a new line
if (($object->fk_statut == ExpenseReport::STATUS_DRAFT || $object->fk_statut == ExpenseReport::STATUS_REFUSED)
- && $action != 'editline'
- && $user->rights->expensereport->creer)
+ && $action != 'editline'
+ && $user->rights->expensereport->creer)
{
- $colspan = 11;
- if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++;
- if (!empty($conf->projet->enabled)) $colspan++;
- if ($action != 'editline') $colspan++;
+ $colspan = 11;
+ if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) $colspan++;
+ if (!empty($conf->projet->enabled)) $colspan++;
+ if ($action != 'editline') $colspan++;
- $nbFiles = $nbLinks = 0;
- $arrayoffiles = array();
- if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
- {
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
- require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
- $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref);
- $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$');
- $nbFiles = count($arrayoffiles);
- $nbLinks = Link::count($db, $object->element, $object->id);
- }
+ $nbFiles = $nbLinks = 0;
+ $arrayoffiles = array();
+ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
+ {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
+ $upload_dir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref);
+ $arrayoffiles = dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png|'.preg_quote(dol_sanitizeFileName($object->ref.'.pdf'), '/').')$');
+ $nbFiles = count($arrayoffiles);
+ $nbLinks = Link::count($db, $object->element, $object->id);
+ }
- // Add line with link to add new file or attach to an existing file
- print ' ';
- print '';
- print ''.$langs->trans("UploadANewFileNow");
- print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
- print ' ';
- if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
- {
- print ' - '.$langs->trans("AttachTheNewLineToTheDocument");
- print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
- print ' ';
- }
+ // Add line with link to add new file or attach to an existing file
+ print ' ';
+ print '';
+ print ''.$langs->trans("UploadANewFileNow");
+ print img_picto($langs->trans("UploadANewFileNow"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
+ print ' ';
+ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES))
+ {
+ print ' - '.$langs->trans("AttachTheNewLineToTheDocument");
+ print img_picto($langs->trans("AttachTheNewLineToTheDocument"), 'chevron-down', '', false, 0, 0, '', 'marginleftonly');
+ print ' ';
+ }
- print ''."\n";
- print ' ';
+ print ''."\n";
+ print '';
- include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php';
- include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php';
+ include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_addfile.tpl.php';
+ include DOL_DOCUMENT_ROOT.'/expensereport/tpl/expensereport_linktofile.tpl.php';
print '';
print ' ';
print ''.$langs->trans('Date').' ';
- if (!empty($conf->projet->enabled)) print ''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).' ';
- if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) print ''.$langs->trans('CarCategory').' ';
+ if (!empty($conf->projet->enabled)) {
+ print ''.$form->textwithpicto($langs->trans('Project'), $langs->trans("ClosedProjectsAreHidden")).' ';
+ }
print ''.$langs->trans('Type').' ';
+ if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) {
+ print ''.$langs->trans('CarCategory').' ';
+ }
print ''.$langs->trans('Description').' ';
print ''.$langs->trans('VAT').' ';
print ''.$langs->trans('PriceUHT').' ';
@@ -2440,19 +2446,19 @@ if ($action == 'create')
print '';
}
+ // Select type
+ print '';
+ print select_type_fees_id($fk_c_type_fees, 'fk_c_type_fees', 1);
+ print ' ';
+
if (!empty($conf->global->MAIN_USE_EXPENSE_IK))
{
print '';
$params = array('fk_expense' => $object->id);
- print $form->selectExpenseCategories('', 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params);
+ print $form->selectExpenseCategories('', 'fk_c_exp_tax_cat', 1, array(), 'fk_c_type_fees', $userauthor->default_c_exp_tax_cat, $params, 0);
print ' ';
}
- // Select type
- print '';
- select_type_fees_id($fk_c_type_fees, 'fk_c_type_fees', 1);
- print ' ';
-
// Add comments
print '';
print '';
@@ -2634,7 +2640,7 @@ if ($action != 'create' && $action != 'edit')
if ($user->rights->expensereport->approve && $object->fk_statut == ExpenseReport::STATUS_APPROVED)
{
- print '';
+ print '';
}
// If bank module is used
@@ -2661,15 +2667,15 @@ if ($action != 'create' && $action != 'edit')
if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->fk_statut == ExpenseReport::STATUS_APPROVED)
{
- // Cancel
+ // Cancel
print '';
}
- // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled.
+ // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled.
if (($user->rights->expensereport->approve || $user->rights->expensereport->to_paid) && $object->fk_statut == ExpenseReport::STATUS_CLOSED)
{
- // Cancel
- print '';
+ // Cancel
+ print '';
}
if ($user->rights->expensereport->to_paid && $object->paid && $object->fk_statut == ExpenseReport::STATUS_CLOSED)
@@ -2680,18 +2686,18 @@ if ($action != 'create' && $action != 'edit')
// Clone
if ($user->rights->expensereport->creer) {
- print '';
+ print '';
}
/* If draft, validated, cancel, and user can create, he can always delete its card before it is approved */
if ($user->rights->expensereport->creer && $user->id == $object->fk_user_author && $object->fk_statut < ExpenseReport::STATUS_APPROVED)
{
- // Delete
+ // Delete
print '';
} elseif ($user->rights->expensereport->supprimer && $object->fk_statut != ExpenseReport::STATUS_CLOSED)
{
- // Delete
- print '';
+ // Delete
+ print '';
}
$parameters = array();
diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php
index e2ea2b377a4..8770a0ab1a2 100644
--- a/htdocs/expensereport/class/expensereport.class.php
+++ b/htdocs/expensereport/class/expensereport.class.php
@@ -34,80 +34,80 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.ph
*/
class ExpenseReport extends CommonObject
{
- /**
+ /**
* @var string ID to identify managed object
*/
public $element = 'expensereport';
- /**
+ /**
* @var string Name of table without prefix where object is stored
*/
public $table_element = 'expensereport';
- public $table_element_line = 'expensereport_det';
- public $fk_element = 'fk_expensereport';
+ public $table_element_line = 'expensereport_det';
+ public $fk_element = 'fk_expensereport';
- /**
- * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
- */
- public $picto = 'trip';
+ /**
+ * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
+ */
+ public $picto = 'trip';
- public $lines = array();
+ public $lines = array();
- public $date_debut;
+ public $date_debut;
- public $date_fin;
+ public $date_fin;
- /**
- * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied
- *
- * @var int Status
- */
- public $status;
- public $fk_statut;
+ /**
+ * 0=draft, 2=validated (attente approb), 4=canceled, 5=approved, 6=payed, 99=denied
+ *
+ * @var int Status
+ */
+ public $status;
+ public $fk_statut;
- public $fk_c_paiement;
- public $paid;
+ public $fk_c_paiement;
+ public $paid;
- public $user_author_infos;
- public $user_validator_infos;
+ public $user_author_infos;
+ public $user_validator_infos;
- // ACTIONS
+ // ACTIONS
- // Create
- public $date_create;
- public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
+ // Create
+ public $date_create;
+ public $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
- // Update
+ // Update
public $date_modif;
- public $fk_user_modif;
+ public $fk_user_modif;
- // Refus
- public $date_refuse;
- public $detail_refuse;
- public $fk_user_refuse;
+ // Refus
+ public $date_refuse;
+ public $detail_refuse;
+ public $fk_user_refuse;
- // Annulation
- public $date_cancel;
- public $detail_cancel;
- public $fk_user_cancel;
+ // Annulation
+ public $date_cancel;
+ public $detail_cancel;
+ public $fk_user_cancel;
- public $fk_user_validator; // User that is defined to approve
+ public $fk_user_validator; // User that is defined to approve
- // Validation
- public $date_valid; // User making validation
- public $fk_user_valid;
- public $user_valid_infos;
+ // Validation
+ public $date_valid; // User making validation
+ public $fk_user_valid;
+ public $user_valid_infos;
- // Approve
- public $date_approve;
- public $fk_user_approve; // User that has approved
+ // Approve
+ public $date_approve;
+ public $fk_user_approve; // User that has approved
- // Paiement
- public $user_paid_infos;
+ // Paiement
+ public $user_paid_infos;
- /**
+ /**
* Draft status
*/
const STATUS_DRAFT = 0;
@@ -185,156 +185,156 @@ class ExpenseReport extends CommonObject
);
/**
- * Constructor
- *
- * @param DoliDB $db Handler acces base de donnees
- */
- public function __construct($db)
- {
- $this->db = $db;
- $this->total_ht = 0;
- $this->total_ttc = 0;
- $this->total_tva = 0;
- $this->modepaymentid = 0;
+ * Constructor
+ *
+ * @param DoliDB $db Handler acces base de donnees
+ */
+ public function __construct($db)
+ {
+ $this->db = $db;
+ $this->total_ht = 0;
+ $this->total_ttc = 0;
+ $this->total_tva = 0;
+ $this->modepaymentid = 0;
- // List of language codes for status
- $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
- $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
- $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
- }
+ // List of language codes for status
+ $this->statuts_short = array(0 => 'Draft', 2 => 'Validated', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
+ $this->statuts = array(0 => 'Draft', 2 => 'ValidatedWaitingApproval', 4 => 'Canceled', 5 => 'Approved', 6 => 'Paid', 99 => 'Refused');
+ $this->statuts_logo = array(0 => 'status0', 2 => 'status1', 4 => 'status6', 5 => 'status4', 6 => 'status6', 99 => 'status5');
+ }
- /**
- * Create object in database
- *
- * @param User $user User that create
- * @param int $notrigger Disable triggers
- * @return int <0 if KO, >0 if OK
- */
- public function create($user, $notrigger = 0)
- {
- global $conf, $langs;
+ /**
+ * Create object in database
+ *
+ * @param User $user User that create
+ * @param int $notrigger Disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function create($user, $notrigger = 0)
+ {
+ global $conf, $langs;
- $now = dol_now();
+ $now = dol_now();
- $error = 0;
+ $error = 0;
- // Check parameters
- if (empty($this->date_debut) || empty($this->date_fin))
- {
- $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
- return -1;
- }
+ // Check parameters
+ if (empty($this->date_debut) || empty($this->date_fin))
+ {
+ $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date'));
+ return -1;
+ }
- $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
- if (empty($fuserid)) $fuserid = $user->id;
+ $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
+ if (empty($fuserid)) $fuserid = $user->id;
- $this->db->begin();
+ $this->db->begin();
- $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
- $sql .= "ref";
- $sql .= ",total_ht";
- $sql .= ",total_ttc";
- $sql .= ",total_tva";
- $sql .= ",date_debut";
- $sql .= ",date_fin";
- $sql .= ",date_create";
- $sql .= ",fk_user_author";
- $sql .= ",fk_user_validator";
- $sql .= ",fk_user_approve";
- $sql .= ",fk_user_modif";
- $sql .= ",fk_statut";
- $sql .= ",fk_c_paiement";
- $sql .= ",paid";
- $sql .= ",note_public";
- $sql .= ",note_private";
- $sql .= ",entity";
- $sql .= ") VALUES(";
- $sql .= "'(PROV)'";
- $sql .= ", ".$this->total_ht;
- $sql .= ", ".$this->total_ttc;
- $sql .= ", ".$this->total_tva;
- $sql .= ", '".$this->db->idate($this->date_debut)."'";
- $sql .= ", '".$this->db->idate($this->date_fin)."'";
- $sql .= ", '".$this->db->idate($now)."'";
- $sql .= ", ".$fuserid;
- $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
- $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
- $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null");
- $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0);
- $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null");
- $sql .= ", 0";
- $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
- $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
- $sql .= ", ".$conf->entity;
- $sql .= ")";
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
+ $sql .= "ref";
+ $sql .= ",total_ht";
+ $sql .= ",total_ttc";
+ $sql .= ",total_tva";
+ $sql .= ",date_debut";
+ $sql .= ",date_fin";
+ $sql .= ",date_create";
+ $sql .= ",fk_user_author";
+ $sql .= ",fk_user_validator";
+ $sql .= ",fk_user_approve";
+ $sql .= ",fk_user_modif";
+ $sql .= ",fk_statut";
+ $sql .= ",fk_c_paiement";
+ $sql .= ",paid";
+ $sql .= ",note_public";
+ $sql .= ",note_private";
+ $sql .= ",entity";
+ $sql .= ") VALUES(";
+ $sql .= "'(PROV)'";
+ $sql .= ", ".$this->total_ht;
+ $sql .= ", ".$this->total_ttc;
+ $sql .= ", ".$this->total_tva;
+ $sql .= ", '".$this->db->idate($this->date_debut)."'";
+ $sql .= ", '".$this->db->idate($this->date_fin)."'";
+ $sql .= ", '".$this->db->idate($now)."'";
+ $sql .= ", ".$fuserid;
+ $sql .= ", ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
+ $sql .= ", ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
+ $sql .= ", ".($this->fk_user_modif > 0 ? $this->fk_user_modif : "null");
+ $sql .= ", ".($this->fk_statut > 1 ? $this->fk_statut : 0);
+ $sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null");
+ $sql .= ", 0";
+ $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
+ $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
+ $sql .= ", ".$conf->entity;
+ $sql .= ")";
- $result = $this->db->query($sql);
- if ($result)
- {
- $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
- $this->ref = '(PROV'.$this->id.')';
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
+ $this->ref = '(PROV'.$this->id.')';
- $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
- $resql = $this->db->query($sql);
- if (!$resql)
- {
- $this->error = $this->db->lasterror();
- $error++;
- }
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
+ $resql = $this->db->query($sql);
+ if (!$resql)
+ {
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
- if (!$error)
- {
- if (is_array($this->lines) && count($this->lines) > 0)
- {
- foreach ($this->lines as $line)
- {
- // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
- //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
- if (!is_object($line)) {
- $line = (object) $line;
- $newndfline = new ExpenseReportLine($this->db);
- $newndfline->fk_expensereport = $line->fk_expensereport;
- $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
- $newndfline->fk_project = $line->fk_project;
- $newndfline->vatrate = $line->vatrate;
- $newndfline->vat_src_code = $line->vat_src_code;
- $newndfline->comments = $line->comments;
- $newndfline->qty = $line->qty;
- $newndfline->value_unit = $line->value_unit;
- $newndfline->total_ht = $line->total_ht;
- $newndfline->total_ttc = $line->total_ttc;
- $newndfline->total_tva = $line->total_tva;
- $newndfline->date = $line->date;
- $newndfline->rule_warning_message = $line->rule_warning_message;
- $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
- $newndfline->fk_ecm_files = $line->fk_ecm_files;
- } else {
- $newndfline = $line;
- }
- //$newndfline=new ExpenseReportLine($this->db);
- $newndfline->fk_expensereport = $this->id;
- $result = $newndfline->insert();
- if ($result < 0)
- {
- $this->error = $newndfline->error;
- $error++;
- break;
- }
- }
- }
- }
+ if (!$error)
+ {
+ if (is_array($this->lines) && count($this->lines) > 0)
+ {
+ foreach ($this->lines as $line)
+ {
+ // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
+ //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
+ if (!is_object($line)) {
+ $line = (object) $line;
+ $newndfline = new ExpenseReportLine($this->db);
+ $newndfline->fk_expensereport = $line->fk_expensereport;
+ $newndfline->fk_c_type_fees = $line->fk_c_type_fees;
+ $newndfline->fk_project = $line->fk_project;
+ $newndfline->vatrate = $line->vatrate;
+ $newndfline->vat_src_code = $line->vat_src_code;
+ $newndfline->comments = $line->comments;
+ $newndfline->qty = $line->qty;
+ $newndfline->value_unit = $line->value_unit;
+ $newndfline->total_ht = $line->total_ht;
+ $newndfline->total_ttc = $line->total_ttc;
+ $newndfline->total_tva = $line->total_tva;
+ $newndfline->date = $line->date;
+ $newndfline->rule_warning_message = $line->rule_warning_message;
+ $newndfline->fk_c_exp_tax_cat = $line->fk_c_exp_tax_cat;
+ $newndfline->fk_ecm_files = $line->fk_ecm_files;
+ } else {
+ $newndfline = $line;
+ }
+ //$newndfline=new ExpenseReportLine($this->db);
+ $newndfline->fk_expensereport = $this->id;
+ $result = $newndfline->insert();
+ if ($result < 0)
+ {
+ $this->error = $newndfline->error;
+ $error++;
+ break;
+ }
+ }
+ }
+ }
- if (!$error)
- {
- $result = $this->insertExtraFields();
- if ($result < 0) $error++;
- }
+ if (!$error)
+ {
+ $result = $this->insertExtraFields();
+ if ($result < 0) $error++;
+ }
- if (!$error)
- {
- $result = $this->update_price();
- if ($result > 0)
- {
+ if (!$error)
+ {
+ $result = $this->update_price();
+ if ($result > 0)
+ {
if (!$notrigger)
{
// Call trigger
@@ -354,131 +354,131 @@ class ExpenseReport extends CommonObject
$this->db->rollback();
return -4;
}
- } else {
- $this->db->rollback();
- return -3;
- }
- } else {
- dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
- $this->db->rollback();
- return -2;
- }
- } else {
- $this->error = $this->db->lasterror()." sql=".$sql;
- $this->db->rollback();
- return -1;
- }
- }
+ } else {
+ $this->db->rollback();
+ return -3;
+ }
+ } else {
+ dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
+ $this->db->rollback();
+ return -2;
+ }
+ } else {
+ $this->error = $this->db->lasterror()." sql=".$sql;
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Load an object from its id and create a new one in database
- *
+ /**
+ * Load an object from its id and create a new one in database
+ *
* @param User $user User making the clone
- * @param int $fk_user_author Id of new user
- * @return int New id of clone
- */
- public function createFromClone(User $user, $fk_user_author)
- {
- global $hookmanager;
+ * @param int $fk_user_author Id of new user
+ * @return int New id of clone
+ */
+ public function createFromClone(User $user, $fk_user_author)
+ {
+ global $hookmanager;
- $error = 0;
+ $error = 0;
- if (empty($fk_user_author)) $fk_user_author = $user->id;
+ if (empty($fk_user_author)) $fk_user_author = $user->id;
- $this->db->begin();
+ $this->db->begin();
- // get extrafields so they will be clone
- //foreach($this->lines as $line)
- //$line->fetch_optionals();
+ // get extrafields so they will be clone
+ //foreach($this->lines as $line)
+ //$line->fetch_optionals();
- // Load source object
- $objFrom = clone $this;
+ // Load source object
+ $objFrom = clone $this;
- $this->id = 0;
- $this->ref = '';
- $this->status = 0;
- $this->fk_statut = 0;
+ $this->id = 0;
+ $this->ref = '';
+ $this->status = 0;
+ $this->fk_statut = 0;
- // Clear fields
- $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
- $this->fk_user_valid = '';
- $this->date_create = '';
- $this->date_creation = '';
- $this->date_validation = '';
+ // Clear fields
+ $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
+ $this->fk_user_valid = '';
+ $this->date_create = '';
+ $this->date_creation = '';
+ $this->date_validation = '';
- // Create clone
- $this->context['createfromclone'] = 'createfromclone';
- $result = $this->create($user);
- if ($result < 0) $error++;
+ // Create clone
+ $this->context['createfromclone'] = 'createfromclone';
+ $result = $this->create($user);
+ if ($result < 0) $error++;
- if (!$error)
- {
- // Hook of thirdparty module
- if (is_object($hookmanager))
- {
- $parameters = array('objFrom'=>$objFrom);
- $action = '';
- $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
- if ($reshook < 0) $error++;
- }
- }
+ if (!$error)
+ {
+ // Hook of thirdparty module
+ if (is_object($hookmanager))
+ {
+ $parameters = array('objFrom'=>$objFrom);
+ $action = '';
+ $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook < 0) $error++;
+ }
+ }
- unset($this->context['createfromclone']);
+ unset($this->context['createfromclone']);
- // End
- if (!$error)
- {
- $this->db->commit();
- return $this->id;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ // End
+ if (!$error)
+ {
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * update
- *
- * @param User $user User making change
+ /**
+ * update
+ *
+ * @param User $user User making change
* @param int $notrigger Disable triggers
- * @param User $userofexpensereport New user we want to have the expense report on.
- * @return int <0 if KO, >0 if OK
- */
- public function update($user, $notrigger = 0, $userofexpensereport = null)
- {
- global $langs;
+ * @param User $userofexpensereport New user we want to have the expense report on.
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update($user, $notrigger = 0, $userofexpensereport = null)
+ {
+ global $langs;
$error = 0;
$this->db->begin();
- $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
- $sql .= " total_ht = ".$this->total_ht;
- $sql .= " , total_ttc = ".$this->total_ttc;
- $sql .= " , total_tva = ".$this->total_tva;
- $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
- $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
- if ($userofexpensereport && is_object($userofexpensereport))
- {
- $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? "'".$userofexpensereport->id."'" : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for.
- }
- $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
- $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
- $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
- $sql .= " , fk_user_modif = ".$user->id;
- $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
- $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
- $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
- $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
- $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
- $sql .= " WHERE rowid = ".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
+ $sql .= " total_ht = ".$this->total_ht;
+ $sql .= " , total_ttc = ".$this->total_ttc;
+ $sql .= " , total_tva = ".$this->total_tva;
+ $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'";
+ $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'";
+ if ($userofexpensereport && is_object($userofexpensereport))
+ {
+ $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? "'".$userofexpensereport->id."'" : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for.
+ }
+ $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null");
+ $sql .= " , fk_user_valid = ".($this->fk_user_valid > 0 ? $this->fk_user_valid : "null");
+ $sql .= " , fk_user_approve = ".($this->fk_user_approve > 0 ? $this->fk_user_approve : "null");
+ $sql .= " , fk_user_modif = ".$user->id;
+ $sql .= " , fk_statut = ".($this->fk_statut >= 0 ? $this->fk_statut : '0');
+ $sql .= " , fk_c_paiement = ".($this->fk_c_paiement > 0 ? $this->fk_c_paiement : "null");
+ $sql .= " , note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "''");
+ $sql .= " , note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "''");
+ $sql .= " , detail_refuse = ".(!empty($this->detail_refuse) ? "'".$this->db->escape($this->detail_refuse)."'" : "''");
+ $sql .= " WHERE rowid = ".$this->id;
- dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
- $result = $this->db->query($sql);
- if ($result)
- {
- if (!$notrigger)
+ dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ if (!$notrigger)
{
// Call trigger
$result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user);
@@ -498,132 +498,132 @@ class ExpenseReport extends CommonObject
$this->error = $this->db->error();
return -2;
}
- } else {
+ } else {
$this->db->rollback();
- $this->error = $this->db->error();
- return -1;
- }
- }
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- /**
- * Load an object from database
- *
- * @param int $id Id {@min 1}
- * @param string $ref Ref {@name ref}
- * @return int <0 if KO, >0 if OK
- */
- public function fetch($id, $ref = '')
- {
- global $conf;
+ /**
+ * Load an object from database
+ *
+ * @param int $id Id {@min 1}
+ * @param string $ref Ref {@name ref}
+ * @return int <0 if KO, >0 if OK
+ */
+ public function fetch($id, $ref = '')
+ {
+ global $conf;
- $sql = "SELECT d.rowid, d.ref, d.note_public, d.note_private,"; // DEFAULT
- $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
- $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
- $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int)
- $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
- $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
- $sql .= " d.fk_user_valid, d.fk_user_approve,";
- $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
- $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
- if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
- else $sql .= " WHERE d.rowid = ".$id;
- //$sql.= $restrict;
+ $sql = "SELECT d.rowid, d.ref, d.note_public, d.note_private,"; // DEFAULT
+ $sql .= " d.detail_refuse, d.detail_cancel, d.fk_user_refuse, d.fk_user_cancel,"; // ACTIONS
+ $sql .= " d.date_refuse, d.date_cancel,"; // ACTIONS
+ $sql .= " d.total_ht, d.total_ttc, d.total_tva,"; // TOTAUX (int)
+ $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve,"; // DATES (datetime)
+ $sql .= " d.fk_user_author, d.fk_user_modif, d.fk_user_validator,";
+ $sql .= " d.fk_user_valid, d.fk_user_approve,";
+ $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid";
+ $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d";
+ if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'";
+ else $sql .= " WHERE d.rowid = ".$id;
+ //$sql.= $restrict;
- dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $obj = $this->db->fetch_object($resql);
- if ($obj)
- {
- $this->id = $obj->rowid;
- $this->ref = $obj->ref;
- $this->total_ht = $obj->total_ht;
- $this->total_tva = $obj->total_tva;
- $this->total_ttc = $obj->total_ttc;
- $this->note_public = $obj->note_public;
- $this->note_private = $obj->note_private;
- $this->detail_refuse = $obj->detail_refuse;
- $this->detail_cancel = $obj->detail_cancel;
+ dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $obj = $this->db->fetch_object($resql);
+ if ($obj)
+ {
+ $this->id = $obj->rowid;
+ $this->ref = $obj->ref;
+ $this->total_ht = $obj->total_ht;
+ $this->total_tva = $obj->total_tva;
+ $this->total_ttc = $obj->total_ttc;
+ $this->note_public = $obj->note_public;
+ $this->note_private = $obj->note_private;
+ $this->detail_refuse = $obj->detail_refuse;
+ $this->detail_cancel = $obj->detail_cancel;
- $this->date_debut = $this->db->jdate($obj->date_debut);
- $this->date_fin = $this->db->jdate($obj->date_fin);
- $this->date_valid = $this->db->jdate($obj->date_valid);
- $this->date_approve = $this->db->jdate($obj->date_approve);
- $this->date_create = $this->db->jdate($obj->date_create);
- $this->date_modif = $this->db->jdate($obj->date_modif);
- $this->date_refuse = $this->db->jdate($obj->date_refuse);
- $this->date_cancel = $this->db->jdate($obj->date_cancel);
+ $this->date_debut = $this->db->jdate($obj->date_debut);
+ $this->date_fin = $this->db->jdate($obj->date_fin);
+ $this->date_valid = $this->db->jdate($obj->date_valid);
+ $this->date_approve = $this->db->jdate($obj->date_approve);
+ $this->date_create = $this->db->jdate($obj->date_create);
+ $this->date_modif = $this->db->jdate($obj->date_modif);
+ $this->date_refuse = $this->db->jdate($obj->date_refuse);
+ $this->date_cancel = $this->db->jdate($obj->date_cancel);
- $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
- $this->fk_user_modif = $obj->fk_user_modif;
- $this->fk_user_validator = $obj->fk_user_validator;
- $this->fk_user_valid = $obj->fk_user_valid;
- $this->fk_user_refuse = $obj->fk_user_refuse;
- $this->fk_user_cancel = $obj->fk_user_cancel;
- $this->fk_user_approve = $obj->fk_user_approve;
+ $this->fk_user_author = $obj->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for.
+ $this->fk_user_modif = $obj->fk_user_modif;
+ $this->fk_user_validator = $obj->fk_user_validator;
+ $this->fk_user_valid = $obj->fk_user_valid;
+ $this->fk_user_refuse = $obj->fk_user_refuse;
+ $this->fk_user_cancel = $obj->fk_user_cancel;
+ $this->fk_user_approve = $obj->fk_user_approve;
- $user_author = new User($this->db);
- if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author);
+ $user_author = new User($this->db);
+ if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author);
- $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
+ $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname);
- $user_approver = new User($this->db);
- if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve);
- elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility
- $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
+ $user_approver = new User($this->db);
+ if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve);
+ elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility
+ $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname);
- $this->fk_statut = $obj->status; // deprecated
- $this->status = $obj->status;
- $this->fk_c_paiement = $obj->fk_c_paiement;
- $this->paid = $obj->paid;
+ $this->fk_statut = $obj->status; // deprecated
+ $this->status = $obj->status;
+ $this->fk_c_paiement = $obj->fk_c_paiement;
+ $this->paid = $obj->paid;
- if ($this->fk_statut == self::STATUS_APPROVED || $this->fk_statut == self::STATUS_CLOSED)
- {
- $user_valid = new User($this->db);
- if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid);
- $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
- }
+ if ($this->fk_statut == self::STATUS_APPROVED || $this->fk_statut == self::STATUS_CLOSED)
+ {
+ $user_valid = new User($this->db);
+ if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid);
+ $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname);
+ }
- $this->lines = array();
+ $this->lines = array();
- $result = $this->fetch_lines();
+ $result = $this->fetch_lines();
- return $result;
- } else {
- return 0;
- }
- } else {
- $this->error = $this->db->lasterror();
- return -1;
- }
- }
+ return $result;
+ } else {
+ return 0;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Classify the expense report as paid
- *
- * @param int $id Id of expense report
- * @param user $fuser User making change
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Classify the expense report as paid
+ *
+ * @param int $id Id of expense report
+ * @param user $fuser User making change
* @param int $notrigger Disable triggers
- * @return int <0 if KO, >0 if OK
- */
- public function set_paid($id, $fuser, $notrigger = 0)
- {
- // phpcs:enable
+ * @return int <0 if KO, >0 if OK
+ */
+ public function set_paid($id, $fuser, $notrigger = 0)
+ {
+ // phpcs:enable
$error = 0;
$this->db->begin();
- $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
- $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1";
- $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport";
+ $sql .= " SET fk_statut = ".self::STATUS_CLOSED.", paid=1";
+ $sql .= " WHERE rowid = ".$id." AND fk_statut = ".self::STATUS_APPROVED;
- dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->affected_rows($resql))
- {
+ dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ if ($this->db->affected_rows($resql))
+ {
if (!$notrigger)
{
// Call trigger
@@ -644,263 +644,263 @@ class ExpenseReport extends CommonObject
$this->error = $this->db->error();
return -2;
}
- } else {
+ } else {
$this->db->commit();
- return 0;
- }
- } else {
+ return 0;
+ }
+ } else {
$this->db->rollback();
- dol_print_error($this->db);
- return -1;
- }
- }
+ dol_print_error($this->db);
+ return -1;
+ }
+ }
- /**
- * Returns the label status
- *
- * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
- * @return string Label
- */
- public function getLibStatut($mode = 0)
- {
- return $this->LibStatut($this->status, $mode);
- }
+ /**
+ * Returns the label status
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
+ * @return string Label
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Returns the label of a statut
- *
- * @param int $status id statut
- * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
- * @return string Label
- */
- public function LibStatut($status, $mode = 0)
- {
- // phpcs:enable
- global $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Returns the label of a statut
+ *
+ * @param int $status id statut
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+ * @return string Label
+ */
+ public function LibStatut($status, $mode = 0)
+ {
+ // phpcs:enable
+ global $langs;
- $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
- $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]);
+ $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
+ $labelStatusShort = $langs->transnoentitiesnoconv($this->statuts_short[$status]);
- $statusType = $this->statuts_logo[$status];
+ $statusType = $this->statuts_logo[$status];
- return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
- }
+ return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
+ }
- /**
- * Load information on object
- *
- * @param int $id Id of object
- * @return void
- */
- public function info($id)
- {
- global $conf;
+ /**
+ * Load information on object
+ *
+ * @param int $id Id of object
+ * @return void
+ */
+ public function info($id)
+ {
+ global $conf;
- $sql = "SELECT f.rowid,";
- $sql .= " f.date_create as datec,";
- $sql .= " f.tms as date_modification,";
- $sql .= " f.date_valid as datev,";
- $sql .= " f.date_approve as datea,";
- //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for.
- $sql .= " f.fk_user_modif as fk_user_modification,";
- $sql .= " f.fk_user_valid,";
- $sql .= " f.fk_user_approve";
- $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
- $sql .= " WHERE f.rowid = ".$id;
- $sql .= " AND f.entity = ".$conf->entity;
+ $sql = "SELECT f.rowid,";
+ $sql .= " f.date_create as datec,";
+ $sql .= " f.tms as date_modification,";
+ $sql .= " f.date_valid as datev,";
+ $sql .= " f.date_approve as datea,";
+ //$sql.= " f.fk_user_author as fk_user_creation,"; // This is not user of creation but user the expense is for.
+ $sql .= " f.fk_user_modif as fk_user_modification,";
+ $sql .= " f.fk_user_valid,";
+ $sql .= " f.fk_user_approve";
+ $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as f";
+ $sql .= " WHERE f.rowid = ".$id;
+ $sql .= " AND f.entity = ".$conf->entity;
- $resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
- $obj = $this->db->fetch_object($resql);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ if ($this->db->num_rows($resql))
+ {
+ $obj = $this->db->fetch_object($resql);
- $this->id = $obj->rowid;
+ $this->id = $obj->rowid;
- $this->date_creation = $this->db->jdate($obj->datec);
- $this->date_modification = $this->db->jdate($obj->date_modification);
- $this->date_validation = $this->db->jdate($obj->datev);
- $this->date_approbation = $this->db->jdate($obj->datea);
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_modification = $this->db->jdate($obj->date_modification);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ $this->date_approbation = $this->db->jdate($obj->datea);
- $cuser = new User($this->db);
- $cuser->fetch($obj->fk_user_author);
- $this->user_creation = $cuser;
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
- if ($obj->fk_user_creation)
- {
- $cuser = new User($this->db);
- $cuser->fetch($obj->fk_user_creation);
- $this->user_creation = $cuser;
- }
- if ($obj->fk_user_valid)
- {
- $vuser = new User($this->db);
- $vuser->fetch($obj->fk_user_valid);
- $this->user_validation = $vuser;
- }
- if ($obj->fk_user_modification)
- {
- $muser = new User($this->db);
- $muser->fetch($obj->fk_user_modification);
- $this->user_modification = $muser;
- }
- if ($obj->fk_user_approve)
- {
- $auser = new User($this->db);
- $auser->fetch($obj->fk_user_approve);
- $this->user_approve = $auser;
- }
- }
- $this->db->free($resql);
- } else {
- dol_print_error($this->db);
- }
- }
+ if ($obj->fk_user_creation)
+ {
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_creation);
+ $this->user_creation = $cuser;
+ }
+ if ($obj->fk_user_valid)
+ {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+ if ($obj->fk_user_modification)
+ {
+ $muser = new User($this->db);
+ $muser->fetch($obj->fk_user_modification);
+ $this->user_modification = $muser;
+ }
+ if ($obj->fk_user_approve)
+ {
+ $auser = new User($this->db);
+ $auser->fetch($obj->fk_user_approve);
+ $this->user_approve = $auser;
+ }
+ }
+ $this->db->free($resql);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
- /**
- * Initialise an instance with random values.
- * Used to build previews or test instances.
- * id must be 0 if object instance is a specimen.
- *
- * @return void
- */
- public function initAsSpecimen()
- {
- global $user, $langs, $conf;
+ /**
+ * Initialise an instance with random values.
+ * Used to build previews or test instances.
+ * id must be 0 if object instance is a specimen.
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ global $user, $langs, $conf;
- $now = dol_now();
+ $now = dol_now();
- // Initialise parametres
- $this->id = 0;
- $this->ref = 'SPECIMEN';
- $this->specimen = 1;
- $this->date_create = $now;
- $this->date_debut = $now;
- $this->date_fin = $now;
- $this->date_valid = $now;
- $this->date_approve = $now;
+ // Initialise parametres
+ $this->id = 0;
+ $this->ref = 'SPECIMEN';
+ $this->specimen = 1;
+ $this->date_create = $now;
+ $this->date_debut = $now;
+ $this->date_fin = $now;
+ $this->date_valid = $now;
+ $this->date_approve = $now;
- $type_fees_id = 2; // TF_TRIP
+ $type_fees_id = 2; // TF_TRIP
- $this->status = 5;
- $this->fk_statut = 5;
+ $this->status = 5;
+ $this->fk_statut = 5;
- $this->fk_user_author = $user->id;
- $this->fk_user_validator = $user->id;
- $this->fk_user_valid = $user->id;
- $this->fk_user_approve = $user->id;
+ $this->fk_user_author = $user->id;
+ $this->fk_user_validator = $user->id;
+ $this->fk_user_valid = $user->id;
+ $this->fk_user_approve = $user->id;
- $this->note_private = 'Private note';
- $this->note_public = 'SPECIMEN';
- $nbp = 5;
- $xnbp = 0;
- while ($xnbp < $nbp) {
- $line = new ExpenseReportLine($this->db);
- $line->comments = $langs->trans("Comment")." ".$xnbp;
- $line->date = ($now - 3600 * (1 + $xnbp));
- $line->total_ht = 100;
- $line->total_tva = 20;
- $line->total_ttc = 120;
- $line->qty = 1;
- $line->vatrate = 20;
- $line->value_unit = 120;
- $line->fk_expensereport = 0;
- $line->type_fees_code = 'TRA';
- $line->fk_c_type_fees = $type_fees_id;
+ $this->note_private = 'Private note';
+ $this->note_public = 'SPECIMEN';
+ $nbp = 5;
+ $xnbp = 0;
+ while ($xnbp < $nbp) {
+ $line = new ExpenseReportLine($this->db);
+ $line->comments = $langs->trans("Comment")." ".$xnbp;
+ $line->date = ($now - 3600 * (1 + $xnbp));
+ $line->total_ht = 100;
+ $line->total_tva = 20;
+ $line->total_ttc = 120;
+ $line->qty = 1;
+ $line->vatrate = 20;
+ $line->value_unit = 120;
+ $line->fk_expensereport = 0;
+ $line->type_fees_code = 'TRA';
+ $line->fk_c_type_fees = $type_fees_id;
- $line->projet_ref = 'ABC';
+ $line->projet_ref = 'ABC';
- $this->lines[$xnbp] = $line;
- $xnbp++;
+ $this->lines[$xnbp] = $line;
+ $xnbp++;
- $this->total_ht += $line->total_ht;
- $this->total_tva += $line->total_tva;
- $this->total_ttc += $line->total_ttc;
- }
- }
+ $this->total_ht += $line->total_ht;
+ $this->total_tva += $line->total_tva;
+ $this->total_ttc += $line->total_ttc;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * fetch_line_by_project
- *
- * @param int $projectid Project id
- * @param User $user User
- * @return int <0 if KO, >0 if OK
- */
- public function fetch_line_by_project($projectid, $user = '')
- {
- // phpcs:enable
- global $conf, $db, $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * fetch_line_by_project
+ *
+ * @param int $projectid Project id
+ * @param User $user User
+ * @return int <0 if KO, >0 if OK
+ */
+ public function fetch_line_by_project($projectid, $user = '')
+ {
+ // phpcs:enable
+ global $conf, $db, $langs;
- $langs->load('trips');
+ $langs->load('trips');
- if ($user->rights->expensereport->lire) {
- $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
- $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
- $sql .= " WHERE de.fk_projet = ".$projectid;
+ if ($user->rights->expensereport->lire) {
+ $sql = "SELECT de.fk_expensereport, de.date, de.comments, de.total_ht, de.total_ttc";
+ $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as de";
+ $sql .= " WHERE de.fk_projet = ".$projectid;
- dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
- $result = $db->query($sql);
- if ($result)
- {
- $num = $db->num_rows($result);
- $i = 0;
- $total_HT = 0;
- $total_TTC = 0;
+ dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
+ $result = $db->query($sql);
+ if ($result)
+ {
+ $num = $db->num_rows($result);
+ $i = 0;
+ $total_HT = 0;
+ $total_TTC = 0;
- while ($i < $num)
- {
- $objp = $db->fetch_object($result);
+ while ($i < $num)
+ {
+ $objp = $db->fetch_object($result);
- $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut";
- $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
- $sql2 .= " WHERE d.rowid = '".$objp->fk_expensereport."'";
+ $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut";
+ $sql2 .= " FROM ".MAIN_DB_PREFIX."expensereport as d";
+ $sql2 .= " WHERE d.rowid = '".$objp->fk_expensereport."'";
- $result2 = $db->query($sql2);
- $obj = $db->fetch_object($result2);
+ $result2 = $db->query($sql2);
+ $obj = $db->fetch_object($result2);
- $objp->fk_user_author = $obj->fk_user_author;
- $objp->ref = $obj->ref;
- $objp->fk_c_expensereport_status = $obj->fk_statut;
- $objp->rowid = $obj->rowid;
+ $objp->fk_user_author = $obj->fk_user_author;
+ $objp->ref = $obj->ref;
+ $objp->fk_c_expensereport_status = $obj->fk_statut;
+ $objp->rowid = $obj->rowid;
- $total_HT = $total_HT + $objp->total_ht;
- $total_TTC = $total_TTC + $objp->total_ttc;
- $author = new User($db);
- $author->fetch($objp->fk_user_author);
+ $total_HT = $total_HT + $objp->total_ht;
+ $total_TTC = $total_TTC + $objp->total_ttc;
+ $author = new User($db);
+ $author->fetch($objp->fk_user_author);
- print ' ';
- print ''.$objp->ref_num.' ';
- print ''.dol_print_date($objp->date, 'day').' ';
- print ''.$author->getNomUrl(1).' ';
- print ''.$objp->comments.' ';
- print ''.price($objp->total_ht).' ';
- print ''.price($objp->total_ttc).' ';
- print '';
+ print ' ';
+ print ''.$objp->ref_num.' ';
+ print ''.dol_print_date($objp->date, 'day').' ';
+ print ''.$author->getNomUrl(1).' ';
+ print ''.$objp->comments.' ';
+ print ''.price($objp->total_ht).' ';
+ print ''.price($objp->total_ttc).' ';
+ print '';
- switch ($objp->fk_c_expensereport_status) {
- case 4:
- print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
- break;
- case 1:
- print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
- break;
- case 2:
- print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
- break;
- case 5:
- print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
- break;
- case 6:
- print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
- break;
- }
- /*
+ switch ($objp->fk_c_expensereport_status) {
+ case 4:
+ print img_picto($langs->trans('StatusOrderCanceled'), 'statut5');
+ break;
+ case 1:
+ print $langs->trans('Draft').' '.img_picto($langs->trans('Draft'), 'statut0');
+ break;
+ case 2:
+ print $langs->trans('TripForValid').' '.img_picto($langs->trans('TripForValid'), 'statut3');
+ break;
+ case 5:
+ print $langs->trans('TripForPaid').' '.img_picto($langs->trans('TripForPaid'), 'statut3');
+ break;
+ case 6:
+ print $langs->trans('TripPaid').' '.img_picto($langs->trans('TripPaid'), 'statut4');
+ break;
+ }
+ /*
if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5');
if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0');
if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1');
@@ -908,237 +908,237 @@ class ExpenseReport extends CommonObject
if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4');
if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6');
*/
- print ' ';
- print ' ';
+ print '';
+ print '';
- $i++;
- }
+ $i++;
+ }
- print ''.$langs->trans("Number").': '.$i.' ';
- print ''.$langs->trans("TotalHT").' : '.price($total_HT).' ';
- print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).' ';
- print ' ';
- print ' ';
- } else {
- $this->error = $db->lasterror();
- return -1;
- }
- }
- }
+ print ''.$langs->trans("Number").': '.$i.' ';
+ print ''.$langs->trans("TotalHT").' : '.price($total_HT).' ';
+ print ''.$langs->trans("TotalTTC").' : '.price($total_TTC).' ';
+ print ' ';
+ print ' ';
+ } else {
+ $this->error = $db->lasterror();
+ return -1;
+ }
+ }
+ }
- /**
- * recalculer
- * TODO Replace this with call to update_price if not already done
- *
- * @param int $id Id of expense report
- * @return int <0 if KO, >0 if OK
- */
- public function recalculer($id)
- {
- $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva';
- $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt';
- $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id;
+ /**
+ * recalculer
+ * TODO Replace this with call to update_price if not already done
+ *
+ * @param int $id Id of expense report
+ * @return int <0 if KO, >0 if OK
+ */
+ public function recalculer($id)
+ {
+ $sql = 'SELECT tt.total_ht, tt.total_ttc, tt.total_tva';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as tt';
+ $sql .= ' WHERE tt.'.$this->fk_element.' = '.$id;
- $total_ht = 0; $total_tva = 0; $total_ttc = 0;
+ $total_ht = 0; $total_tva = 0; $total_ttc = 0;
- $result = $this->db->query($sql);
- if ($result)
- {
- $num = $this->db->num_rows($result);
- $i = 0;
- while ($i < $num):
- $objp = $this->db->fetch_object($result);
- $total_ht += $objp->total_ht;
- $total_tva += $objp->total_tva;
- $i++;
- endwhile;
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ $num = $this->db->num_rows($result);
+ $i = 0;
+ while ($i < $num):
+ $objp = $this->db->fetch_object($result);
+ $total_ht += $objp->total_ht;
+ $total_tva += $objp->total_tva;
+ $i++;
+ endwhile;
- $total_ttc = $total_ht + $total_tva;
- $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
- $sql .= " total_ht = ".$total_ht;
- $sql .= " , total_ttc = ".$total_ttc;
- $sql .= " , total_tva = ".$total_tva;
- $sql .= " WHERE rowid = ".$id;
- $result = $this->db->query($sql);
- if ($result):
- $this->db->free($result);
- return 1;
- else :
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
- return -3;
- endif;
- } else {
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
- return -3;
- }
- }
+ $total_ttc = $total_ht + $total_tva;
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
+ $sql .= " total_ht = ".$total_ht;
+ $sql .= " , total_ttc = ".$total_ttc;
+ $sql .= " , total_tva = ".$total_tva;
+ $sql .= " WHERE rowid = ".$id;
+ $result = $this->db->query($sql);
+ if ($result):
+ $this->db->free($result);
+ return 1;
+ else :
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
+ return -3;
+ endif;
+ } else {
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::recalculer: Error ".$this->error, LOG_ERR);
+ return -3;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * fetch_lines
- *
- * @return int <0 if OK, >0 if KO
- */
- public function fetch_lines()
- {
- // phpcs:enable
- global $conf;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * fetch_lines
+ *
+ * @return int <0 if OK, >0 if KO
+ */
+ public function fetch_lines()
+ {
+ // phpcs:enable
+ global $conf;
- $this->lines = array();
+ $this->lines = array();
- $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
- $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,';
- $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
- $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,';
- $sql .= ' p.ref as ref_projet, p.title as title_projet';
- $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
- $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id;
- if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID))
- {
- $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
- } else {
- $sql .= ' ORDER BY de.rang ASC, de.date ASC';
- }
+ $sql = ' SELECT de.rowid, de.comments, de.qty, de.value_unit, de.date, de.rang,';
+ $sql .= ' de.'.$this->fk_element.', de.fk_c_type_fees, de.fk_c_exp_tax_cat, de.fk_projet as fk_project, de.tva_tx, de.fk_ecm_files,';
+ $sql .= ' de.total_ht, de.total_tva, de.total_ttc,';
+ $sql .= ' ctf.code as code_type_fees, ctf.label as libelle_type_fees,';
+ $sql .= ' p.ref as ref_projet, p.title as title_projet';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line.' as de';
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id';
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid';
+ $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id;
+ if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID))
+ {
+ $sql .= ' ORDER BY de.rang ASC, de.rowid ASC';
+ } else {
+ $sql .= ' ORDER BY de.rang ASC, de.date ASC';
+ }
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $num = $this->db->num_rows($resql);
- $i = 0;
- while ($i < $num)
- {
- $objp = $this->db->fetch_object($resql);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < $num)
+ {
+ $objp = $this->db->fetch_object($resql);
- $deplig = new ExpenseReportLine($this->db);
+ $deplig = new ExpenseReportLine($this->db);
- $deplig->rowid = $objp->rowid;
- $deplig->id = $objp->rowid;
- $deplig->comments = $objp->comments;
- $deplig->qty = $objp->qty;
- $deplig->value_unit = $objp->value_unit;
- $deplig->date = $objp->date;
- $deplig->dates = $this->db->jdate($objp->date);
+ $deplig->rowid = $objp->rowid;
+ $deplig->id = $objp->rowid;
+ $deplig->comments = $objp->comments;
+ $deplig->qty = $objp->qty;
+ $deplig->value_unit = $objp->value_unit;
+ $deplig->date = $objp->date;
+ $deplig->dates = $this->db->jdate($objp->date);
- $deplig->fk_expensereport = $objp->fk_expensereport;
- $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
- $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
- $deplig->fk_projet = $objp->fk_project; // deprecated
- $deplig->fk_project = $objp->fk_project;
- $deplig->fk_ecm_files = $objp->fk_ecm_files;
+ $deplig->fk_expensereport = $objp->fk_expensereport;
+ $deplig->fk_c_type_fees = $objp->fk_c_type_fees;
+ $deplig->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
+ $deplig->fk_projet = $objp->fk_project; // deprecated
+ $deplig->fk_project = $objp->fk_project;
+ $deplig->fk_ecm_files = $objp->fk_ecm_files;
- $deplig->total_ht = $objp->total_ht;
- $deplig->total_tva = $objp->total_tva;
- $deplig->total_ttc = $objp->total_ttc;
+ $deplig->total_ht = $objp->total_ht;
+ $deplig->total_tva = $objp->total_tva;
+ $deplig->total_ttc = $objp->total_ttc;
- $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
- $deplig->type_fees_libelle = $objp->libelle_type_fees;
+ $deplig->type_fees_code = empty($objp->code_type_fees) ? 'TF_OTHER' : $objp->code_type_fees;
+ $deplig->type_fees_libelle = $objp->libelle_type_fees;
$deplig->tva_tx = $objp->tva_tx;
- $deplig->vatrate = $objp->tva_tx;
- $deplig->projet_ref = $objp->ref_projet;
- $deplig->projet_title = $objp->title_projet;
+ $deplig->vatrate = $objp->tva_tx;
+ $deplig->projet_ref = $objp->ref_projet;
+ $deplig->projet_title = $objp->title_projet;
- $deplig->rang = $objp->rang;
+ $deplig->rang = $objp->rang;
- $this->lines[$i] = $deplig;
+ $this->lines[$i] = $deplig;
- $i++;
- }
- $this->db->free($resql);
- return 1;
- } else {
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
- return -3;
- }
- }
+ $i++;
+ }
+ $this->db->free($resql);
+ return 1;
+ } else {
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::fetch_lines: Error ".$this->error, LOG_ERR);
+ return -3;
+ }
+ }
- /**
- * delete
- *
- * @param User $fuser User that delete
- * @return int <0 if KO, >0 if OK
- */
- public function delete(User $fuser = null)
- {
- global $user, $langs, $conf;
+ /**
+ * delete
+ *
+ * @param User $fuser User that delete
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $fuser = null)
+ {
+ global $user, $langs, $conf;
- if (!$rowid) $rowid = $this->id;
+ if (!$rowid) $rowid = $this->id;
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line.' WHERE '.$this->fk_element.' = '.$rowid;
- if ($this->db->query($sql))
- {
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid = '.$rowid;
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->error = $this->db->error()." sql=".$sql;
- dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
- $this->db->rollback();
- return -6;
- }
- } else {
- $this->error = $this->db->error()." sql=".$sql;
- dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
- $this->db->rollback();
- return -4;
- }
- }
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line.' WHERE '.$this->fk_element.' = '.$rowid;
+ if ($this->db->query($sql))
+ {
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid = '.$rowid;
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->error = $this->db->error()." sql=".$sql;
+ dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
+ $this->db->rollback();
+ return -6;
+ }
+ } else {
+ $this->error = $this->db->error()." sql=".$sql;
+ dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
+ $this->db->rollback();
+ return -4;
+ }
+ }
- /**
- * Set to status validate
- *
- * @param User $fuser User
+ /**
+ * Set to status validate
+ *
+ * @param User $fuser User
* @param int $notrigger Disable triggers
- * @return int <0 if KO, 0 if nothing done, >0 if OK
- */
- public function setValidate($fuser, $notrigger = 0)
- {
- global $conf, $langs, $user;
+ * @return int <0 if KO, 0 if nothing done, >0 if OK
+ */
+ public function setValidate($fuser, $notrigger = 0)
+ {
+ global $conf, $langs, $user;
$error = 0;
$now = dol_now();
- // Protection
- if ($this->statut == self::STATUS_VALIDATED)
- {
- dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
- return 0;
- }
+ // Protection
+ if ($this->statut == self::STATUS_VALIDATED)
+ {
+ dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING);
+ return 0;
+ }
- $this->date_valid = $now; // Required for the getNextNum later.
+ $this->date_valid = $now; // Required for the getNextNum later.
// 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;
- }
- if (empty($num) || $num < 0) return -1;
+ 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;
+ }
+ if (empty($num) || $num < 0) return -1;
- $this->newref = dol_sanitizeFileName($num);
+ $this->newref = dol_sanitizeFileName($num);
$this->db->begin();
- // Validate
- $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
- $sql .= " SET ref = '".$num."',";
- $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
- $sql .= " date_valid='".$this->db->idate($this->date_valid)."',";
- $sql .= " fk_user_valid = ".$user->id;
- $sql .= " WHERE rowid = ".$this->id;
+ // Validate
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$num."',";
+ $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
+ $sql .= " date_valid='".$this->db->idate($this->date_valid)."',";
+ $sql .= " fk_user_valid = ".$user->id;
+ $sql .= " WHERE rowid = ".$this->id;
- $resql = $this->db->query($sql);
- if ($resql)
- {
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
if (!$error && !$notrigger)
{
// Call trigger
@@ -1151,42 +1151,42 @@ class ExpenseReport extends CommonObject
if (!$error)
{
- $this->oldref = $this->ref;
+ $this->oldref = $this->ref;
- // Rename directory if dir was a temporary ref
- if (preg_match('/^[\(]?PROV/i', $this->ref))
- {
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ // Rename directory if dir was a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref))
+ {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- // 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 = 'expensereport/".$this->db->escape($this->newref)."'";
- $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
+ // 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 = 'expensereport/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$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
+ // 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->expensereport->dir_output.'/'.$oldref;
$dirdest = $conf->expensereport->dir_output.'/'.$newref;
if (!$error && file_exists($dirsource))
{
- dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest);
+ dol_syslog(get_class($this)."::setValidate() 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->expensereport->dir_output.'/'.$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);
- }
- }
+ if (@rename($dirsource, $dirdest))
+ {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$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);
+ }
+ }
}
}
}
@@ -1194,8 +1194,8 @@ class ExpenseReport extends CommonObject
// Set new ref and current status
if (!$error)
{
- $this->ref = $num;
- $this->statut = self::STATUS_VALIDATED;
+ $this->ref = $num;
+ $this->statut = self::STATUS_VALIDATED;
}
if (empty($error))
@@ -1207,81 +1207,81 @@ class ExpenseReport extends CommonObject
$this->error = $this->db->error();
return -2;
}
- } else {
+ } else {
$this->db->rollback();
- $this->error = $this->db->lasterror();
- return -1;
- }
- }
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * set_save_from_refuse
- *
- * @param User $fuser User
- * @return int <0 if KO, >0 if OK
- */
- public function set_save_from_refuse($fuser)
- {
- // phpcs:enable
- global $conf, $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * set_save_from_refuse
+ *
+ * @param User $fuser User
+ * @return int <0 if KO, >0 if OK
+ */
+ public function set_save_from_refuse($fuser)
+ {
+ // phpcs:enable
+ global $conf, $langs;
- // Sélection de la date de début de la NDF
- $sql = 'SELECT date_debut';
- $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
- $sql .= ' WHERE rowid = '.$this->id;
+ // Sélection de la date de début de la NDF
+ $sql = 'SELECT date_debut';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
+ $sql .= ' WHERE rowid = '.$this->id;
- $result = $this->db->query($sql);
+ $result = $this->db->query($sql);
- $objp = $this->db->fetch_object($result);
+ $objp = $this->db->fetch_object($result);
- $this->date_debut = $this->db->jdate($objp->date_debut);
+ $this->date_debut = $this->db->jdate($objp->date_debut);
- if ($this->fk_statut != self::STATUS_VALIDATED)
- {
- $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
- $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
- $sql .= ' WHERE rowid = '.$this->id;
+ if ($this->fk_statut != self::STATUS_VALIDATED)
+ {
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET fk_statut = ".self::STATUS_VALIDATED;
+ $sql .= ' WHERE rowid = '.$this->id;
- dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG);
+ dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG);
- if ($this->db->query($sql))
- {
- return 1;
- } else {
- $this->error = $this->db->lasterror();
- return -1;
- }
- } else {
- dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
- }
- }
+ if ($this->db->query($sql))
+ {
+ return 1;
+ } else {
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::set_save_from_refuse expensereport already with save status", LOG_WARNING);
+ }
+ }
- /**
- * Set status to approved
- *
- * @param User $fuser User
+ /**
+ * Set status to approved
+ *
+ * @param User $fuser User
* @param int $notrigger Disable triggers
- * @return int <0 if KO, 0 if nothing done, >0 if OK
- */
- public function setApproved($fuser, $notrigger = 0)
- {
- $now = dol_now();
- $error = 0;
+ * @return int <0 if KO, 0 if nothing done, >0 if OK
+ */
+ public function setApproved($fuser, $notrigger = 0)
+ {
+ $now = dol_now();
+ $error = 0;
- // date approval
- $this->date_approve = $now;
- if ($this->fk_statut != self::STATUS_APPROVED)
- {
+ // date approval
+ $this->date_approve = $now;
+ if ($this->fk_statut != self::STATUS_APPROVED)
+ {
$this->db->begin();
- $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
- $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.",";
- $sql .= " date_approve='".$this->db->idate($this->date_approve)."'";
- $sql .= ' WHERE rowid = '.$this->id;
- if ($this->db->query($sql))
- {
- if (!$notrigger)
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.",";
+ $sql .= " date_approve='".$this->db->idate($this->date_approve)."'";
+ $sql .= ' WHERE rowid = '.$this->id;
+ if ($this->db->query($sql))
+ {
+ if (!$notrigger)
{
// Call trigger
$result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser);
@@ -1301,46 +1301,46 @@ class ExpenseReport extends CommonObject
$this->error = $this->db->error();
return -2;
}
- } else {
+ } else {
$this->db->rollback();
- $this->error = $this->db->lasterror();
- return -1;
- }
- } else {
- dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
- }
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::setApproved expensereport already with approve status", LOG_WARNING);
+ }
- return 0;
- }
+ return 0;
+ }
- /**
- * setDeny
- *
- * @param User $fuser User
- * @param string $details Details
- * @param int $notrigger Disable triggers
- * @return int
- */
- public function setDeny($fuser, $details, $notrigger = 0)
- {
- $now = dol_now();
+ /**
+ * setDeny
+ *
+ * @param User $fuser User
+ * @param string $details Details
+ * @param int $notrigger Disable triggers
+ * @return int
+ */
+ public function setDeny($fuser, $details, $notrigger = 0)
+ {
+ $now = dol_now();
$error = 0;
- // date de refus
+ // date de refus
if ($this->fk_statut != self::STATUS_REFUSED)
- {
- $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
- $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.",";
- $sql .= " date_refuse='".$this->db->idate($now)."',";
- $sql .= " detail_refuse='".$this->db->escape($details)."',";
- $sql .= " fk_user_approve = NULL";
- $sql .= ' WHERE rowid = '.$this->id;
- if ($this->db->query($sql))
- {
- $this->fk_statut = 99;
- $this->fk_user_refuse = $fuser->id;
- $this->detail_refuse = $details;
- $this->date_refuse = $now;
+ {
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.",";
+ $sql .= " date_refuse='".$this->db->idate($now)."',";
+ $sql .= " detail_refuse='".$this->db->escape($details)."',";
+ $sql .= " fk_user_approve = NULL";
+ $sql .= ' WHERE rowid = '.$this->id;
+ if ($this->db->query($sql))
+ {
+ $this->fk_statut = 99;
+ $this->fk_user_refuse = $fuser->id;
+ $this->detail_refuse = $details;
+ $this->date_refuse = $now;
if (!$notrigger)
{
@@ -1362,38 +1362,38 @@ class ExpenseReport extends CommonObject
$this->error = $this->db->error();
return -2;
}
- } else {
+ } else {
$this->db->rollback();
- $this->error = $this->db->lasterror();
- return -1;
- }
- } else {
- dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
- }
- }
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::setDeny expensereport already with refuse status", LOG_WARNING);
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * set_unpaid
- *
- * @param User $fuser User
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * set_unpaid
+ *
+ * @param User $fuser User
* @param int $notrigger Disable triggers
- * @return int <0 if KO, >0 if OK
- */
- public function set_unpaid($fuser, $notrigger = 0)
- {
- // phpcs:enable
+ * @return int <0 if KO, >0 if OK
+ */
+ public function set_unpaid($fuser, $notrigger = 0)
+ {
+ // phpcs:enable
$error = 0;
if ($this->paid)
- {
+ {
$this->db->begin();
- $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
- $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
- $sql .= ' WHERE rowid = '.$this->id;
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET paid = 0, fk_statut = ".self::STATUS_APPROVED;
+ $sql .= ' WHERE rowid = '.$this->id;
- dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG);
+ dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG);
if ($this->db->query($sql))
{
@@ -1422,39 +1422,39 @@ class ExpenseReport extends CommonObject
$this->error = $this->db->error();
return -1;
}
- } else {
- dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
- }
- }
+ } else {
+ dol_syslog(get_class($this)."::set_unpaid expensereport already with unpaid status", LOG_WARNING);
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * set_cancel
- *
- * @param User $fuser User
- * @param string $detail Detail
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * set_cancel
+ *
+ * @param User $fuser User
+ * @param string $detail Detail
* @param int $notrigger Disable triggers
- * @return int <0 if KO, >0 if OK
- */
- public function set_cancel($fuser, $detail, $notrigger = 0)
- {
- // phpcs:enable
+ * @return int <0 if KO, >0 if OK
+ */
+ public function set_cancel($fuser, $detail, $notrigger = 0)
+ {
+ // phpcs:enable
$error = 0;
- $this->date_cancel = $this->db->idate(dol_now());
- if ($this->fk_statut != self::STATUS_CANCELED)
- {
+ $this->date_cancel = $this->db->idate(dol_now());
+ if ($this->fk_statut != self::STATUS_CANCELED)
+ {
$this->db->begin();
- $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
- $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id;
- $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'";
- $sql .= " ,detail_cancel='".$this->db->escape($detail)."'";
- $sql .= ' WHERE rowid = '.$this->id;
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " SET fk_statut = ".self::STATUS_CANCELED.", fk_user_cancel = ".$fuser->id;
+ $sql .= ", date_cancel='".$this->db->idate($this->date_cancel)."'";
+ $sql .= " ,detail_cancel='".$this->db->escape($detail)."'";
+ $sql .= ' WHERE rowid = '.$this->id;
- dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG);
+ dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG);
- if ($this->db->query($sql))
- {
+ if ($this->db->query($sql))
+ {
if (!$notrigger)
{
// Call trigger
@@ -1475,192 +1475,192 @@ class ExpenseReport extends CommonObject
$this->error = $this->db->error();
return -2;
}
- } else {
+ } else {
$this->db->rollback();
- $this->error = $this->db->error();
- return -1;
- }
- } else {
- dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
- }
- }
+ $this->error = $this->db->error();
+ return -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::set_cancel expensereport already with cancel status", LOG_WARNING);
+ }
+ }
- /**
- * Return next reference of expense report not already used
- *
- * @return string free ref
- */
- public function getNextNumRef()
- {
- global $langs, $conf;
- $langs->load("trips");
+ /**
+ * Return next reference of expense report not already used
+ *
+ * @return string free ref
+ */
+ public function getNextNumRef()
+ {
+ global $langs, $conf;
+ $langs->load("trips");
- if (!empty($conf->global->EXPENSEREPORT_ADDON))
- {
- $mybool = false;
+ if (!empty($conf->global->EXPENSEREPORT_ADDON))
+ {
+ $mybool = false;
- $file = $conf->global->EXPENSEREPORT_ADDON.".php";
+ $file = $conf->global->EXPENSEREPORT_ADDON.".php";
$classname = $conf->global->EXPENSEREPORT_ADDON;
// Include file with class
$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
foreach ($dirmodels as $reldir)
{
- $dir = dol_buildpath($reldir."core/modules/expensereport/");
+ $dir = dol_buildpath($reldir."core/modules/expensereport/");
- // Load file with numbering class (if found)
- $mybool |= @include_once $dir.$file;
- }
+ // 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 ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
- $obj = new $classname();
- $numref = $obj->getNextValue($this);
+ $obj = new $classname();
+ $numref = $obj->getNextValue($this);
- if ($numref != "")
- {
- return $numref;
- } else {
+ if ($numref != "")
+ {
+ return $numref;
+ } else {
$this->error = $obj->error;
$this->errors = $obj->errors;
- //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
- return -1;
- }
- } else {
- $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
- return -2;
- }
- }
+ //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
+ return -1;
+ }
+ } else {
+ $this->error = "Error_EXPENSEREPORT_ADDON_NotDefined";
+ return -2;
+ }
+ }
- /**
- * Return clicable name (with picto eventually)
- *
- * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
- * @param int $max Max length of shown ref
- * @param int $short 1=Return just URL
- * @param string $moretitle Add more text to title tooltip
- * @param int $notooltip 1=Disable tooltip
- * @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, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
- {
- global $langs, $conf;
+ /**
+ * Return clicable name (with picto eventually)
+ *
+ * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
+ * @param int $max Max length of shown ref
+ * @param int $short 1=Return just URL
+ * @param string $moretitle Add more text to title tooltip
+ * @param int $notooltip 1=Disable tooltip
+ * @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, $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1)
+ {
+ global $langs, $conf;
- $result = '';
+ $result = '';
- $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id;
+ $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id;
- if ($short) return $url;
+ if ($short) return $url;
- $label = ''.$langs->trans("ShowExpenseReport").' ';
- if (!empty($this->ref))
- $label .= ''.$langs->trans('Ref').': '.$this->ref;
- if (!empty($this->total_ht))
- $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_tva))
- $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_ttc))
- $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
- if ($moretitle) $label .= ' - '.$moretitle;
+ $label = img_picto('', $this->picto).' '.$langs->trans("ExpenseReport").' ';
+ if (!empty($this->ref))
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+ if (!empty($this->total_ht))
+ $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_tva))
+ $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_ttc))
+ $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
+ if ($moretitle) $label .= ' - '.$moretitle;
- //if ($option != 'nolink')
- //{
- // Add param to save lastsearch_values or not
- $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
- if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
- if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
- //}
+ //if ($option != 'nolink')
+ //{
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
+ if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+ //}
- $ref = $this->ref;
- if (empty($ref)) $ref = $this->id;
+ $ref = $this->ref;
+ if (empty($ref)) $ref = $this->id;
- $linkclose = '';
- if (empty($notooltip))
- {
- if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
- {
- $label = $langs->trans("ShowExpenseReport");
- $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
- }
- $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
- $linkclose .= ' class="classfortooltip"';
- }
+ $linkclose = '';
+ if (empty($notooltip))
+ {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+ {
+ $label = $langs->trans("ShowExpenseReport");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip"';
+ }
- $linkstart = '';
- $linkend = ' ';
+ $linkstart = '';
+ $linkend = ' ';
- $result .= $linkstart;
- if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
- if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref);
- $result .= $linkend;
+ $result .= $linkstart;
+ if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref);
+ $result .= $linkend;
- return $result;
- }
+ return $result;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Update total of an expense report when you add a line.
- *
- * @param string $ligne_total_ht Amount without taxes
- * @param string $ligne_total_tva Amount of all taxes
- * @return void
- */
- public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
- {
- // phpcs:enable
- $this->total_ht = $this->total_ht + $ligne_total_ht;
- $this->total_tva = $this->total_tva + $ligne_total_tva;
- $this->total_ttc = $this->total_ht + $this->total_tva;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Update total of an expense report when you add a line.
+ *
+ * @param string $ligne_total_ht Amount without taxes
+ * @param string $ligne_total_tva Amount of all taxes
+ * @return void
+ */
+ public function update_totaux_add($ligne_total_ht, $ligne_total_tva)
+ {
+ // phpcs:enable
+ $this->total_ht = $this->total_ht + $ligne_total_ht;
+ $this->total_tva = $this->total_tva + $ligne_total_tva;
+ $this->total_ttc = $this->total_ht + $this->total_tva;
- $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
- $sql .= " total_ht = ".$this->total_ht;
- $sql .= " , total_ttc = ".$this->total_ttc;
- $sql .= " , total_tva = ".$this->total_tva;
- $sql .= " WHERE rowid = ".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
+ $sql .= " total_ht = ".$this->total_ht;
+ $sql .= " , total_ttc = ".$this->total_ttc;
+ $sql .= " , total_tva = ".$this->total_tva;
+ $sql .= " WHERE rowid = ".$this->id;
- $result = $this->db->query($sql);
- if ($result):
- return 1;
- else :
- $this->error = $this->db->error();
- return -1;
- endif;
- }
+ $result = $this->db->query($sql);
+ if ($result):
+ return 1;
+ else :
+ $this->error = $this->db->error();
+ return -1;
+ endif;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Update total of an expense report when you delete a line.
- *
- * @param string $ligne_total_ht Amount without taxes
- * @param string $ligne_total_tva Amount of all taxes
- * @return void
- */
- public function update_totaux_del($ligne_total_ht, $ligne_total_tva)
- {
- // phpcs:enable
- $this->total_ht = $this->total_ht - $ligne_total_ht;
- $this->total_tva = $this->total_tva - $ligne_total_tva;
- $this->total_ttc = $this->total_ht + $this->total_tva;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Update total of an expense report when you delete a line.
+ *
+ * @param string $ligne_total_ht Amount without taxes
+ * @param string $ligne_total_tva Amount of all taxes
+ * @return void
+ */
+ public function update_totaux_del($ligne_total_ht, $ligne_total_tva)
+ {
+ // phpcs:enable
+ $this->total_ht = $this->total_ht - $ligne_total_ht;
+ $this->total_tva = $this->total_tva - $ligne_total_tva;
+ $this->total_ttc = $this->total_ht + $this->total_tva;
- $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
- $sql .= " total_ht = ".$this->total_ht;
- $sql .= " , total_ttc = ".$this->total_ttc;
- $sql .= " , total_tva = ".$this->total_tva;
- $sql .= " WHERE rowid = ".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
+ $sql .= " total_ht = ".$this->total_ht;
+ $sql .= " , total_ttc = ".$this->total_ttc;
+ $sql .= " , total_tva = ".$this->total_tva;
+ $sql .= " WHERE rowid = ".$this->id;
- $result = $this->db->query($sql);
- if ($result):
- return 1;
- else :
- $this->error = $this->db->error();
- return -1;
- endif;
- }
+ $result = $this->db->query($sql);
+ if ($result):
+ return 1;
+ else :
+ $this->error = $this->db->error();
+ return -1;
+ endif;
+ }
/**
* addline
@@ -1677,11 +1677,11 @@ class ExpenseReport extends CommonObject
* @param int $fk_ecm_files Id of ECM file to link to this expensereport line
* @return int <0 if KO, >0 if OK
*/
- public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0)
+ public function addline($qty = 0, $up = 0, $fk_c_type_fees = 0, $vatrate = 0, $date = '', $comments = '', $fk_project = 0, $fk_c_exp_tax_cat = 0, $type = 0, $fk_ecm_files = 0)
{
global $conf, $langs, $mysoc;
- dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG);
+ dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG);
if ($this->fk_statut == self::STATUS_DRAFT)
{
@@ -1738,28 +1738,28 @@ class ExpenseReport extends CommonObject
$this->checkRules($type, $seller);
$result = $this->line->insert(0, true);
- if ($result > 0)
- {
- $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
- if ($result > 0)
- {
- $this->db->commit();
- return $this->line->id;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->error = $this->line->error;
- dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
- $this->db->rollback();
- return -2;
- }
+ if ($result > 0)
+ {
+ $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode.
+ if ($result > 0)
+ {
+ $this->db->commit();
+ return $this->line->id;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->error = $this->line->error;
+ dol_syslog(get_class($this)."::addline error=".$this->error, LOG_ERR);
+ $this->db->rollback();
+ return -2;
+ }
} else {
- dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
+ dol_syslog(get_class($this)."::addline status of expense report must be Draft to allow use of ->addline()", LOG_ERR);
$this->error = 'ErrorExpenseNotDraft';
- return -3;
- }
+ return -3;
+ }
}
/**
@@ -1905,329 +1905,329 @@ class ExpenseReport extends CommonObject
return false;
}
- /**
- * Update an expense report line
- *
- * @param int $rowid Line to edit
- * @param int $type_fees_id Type payment
- * @param int $projet_id Project id
- * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)'
- * @param string $comments Description
- * @param float $qty Qty
- * @param double $value_unit Value init
- * @param int $date Date
- * @param int $expensereport_id Expense report id
- * @param int $fk_c_exp_tax_cat Id of category of car
+ /**
+ * Update an expense report line
+ *
+ * @param int $rowid Line to edit
+ * @param int $type_fees_id Type payment
+ * @param int $projet_id Project id
+ * @param double $vatrate Vat rate. Can be '8.5' or '8.5* (8.5NPROM...)'
+ * @param string $comments Description
+ * @param float $qty Qty
+ * @param double $value_unit Value init
+ * @param int $date Date
+ * @param int $expensereport_id Expense report id
+ * @param int $fk_c_exp_tax_cat Id of category of car
* @param int $fk_ecm_files Id of ECM file to link to this expensereport line
- * @return int <0 if KO, >0 if OK
- */
- public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0)
- {
- global $user, $mysoc;
+ * @return int <0 if KO, >0 if OK
+ */
+ public function updateline($rowid, $type_fees_id, $projet_id, $vatrate, $comments, $qty, $value_unit, $date, $expensereport_id, $fk_c_exp_tax_cat = 0, $fk_ecm_files = 0)
+ {
+ global $user, $mysoc;
- if ($this->fk_statut == 0 || $this->fk_statut == 99)
- {
- $this->db->begin();
+ if ($this->fk_statut == 0 || $this->fk_statut == 99)
+ {
+ $this->db->begin();
- $type = 0; // TODO What if type is service ?
+ $type = 0; // TODO What if type is service ?
- // We don't know seller and buyer for expense reports
- $seller = $mysoc;
- $buyer = new Societe($this->db);
+ // We don't know seller and buyer for expense reports
+ $seller = $mysoc;
+ $buyer = new Societe($this->db);
- $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
+ $localtaxes_type = getLocalTaxesFromRate($vatrate, 0, $buyer, $seller);
- // Clean vat code
- $vat_src_code = '';
- if (preg_match('/\((.*)\)/', $vatrate, $reg))
- {
- $vat_src_code = $reg[1];
- $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
- }
- $vatrate = preg_replace('/\*/', '', $vatrate);
+ // Clean vat code
+ $vat_src_code = '';
+ if (preg_match('/\((.*)\)/', $vatrate, $reg))
+ {
+ $vat_src_code = $reg[1];
+ $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
+ }
+ $vatrate = preg_replace('/\*/', '', $vatrate);
- $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
+ $tmp = calcul_price_total($qty, $value_unit, 0, $vatrate, 0, 0, 0, 'TTC', 0, $type, $seller, $localtaxes_type);
- // calcul total of line
- //$total_ttc = price2num($qty*$value_unit, 'MT');
+ // calcul total of line
+ //$total_ttc = price2num($qty*$value_unit, 'MT');
- $tx_tva = $vatrate / 100;
- $tx_tva = $tx_tva + 1;
- $total_ht = price2num($total_ttc / $tx_tva, 'MT');
+ $tx_tva = $vatrate / 100;
+ $tx_tva = $tx_tva + 1;
+ $total_ht = price2num($total_ttc / $tx_tva, 'MT');
- $total_tva = price2num($total_ttc - $total_ht, 'MT');
- // fin calculs
+ $total_tva = price2num($total_ttc - $total_ht, 'MT');
+ // fin calculs
- $this->line = new ExpenseReportLine($this->db);
- $this->line->comments = $comments;
- $this->line->qty = $qty;
- $this->line->value_unit = $value_unit;
- $this->line->date = $date;
+ $this->line = new ExpenseReportLine($this->db);
+ $this->line->comments = $comments;
+ $this->line->qty = $qty;
+ $this->line->value_unit = $value_unit;
+ $this->line->date = $date;
- $this->line->fk_expensereport = $expensereport_id;
- $this->line->fk_c_type_fees = $type_fees_id;
- $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
- $this->line->fk_projet = $projet_id; // deprecated
- $this->line->fk_project = $projet_id;
+ $this->line->fk_expensereport = $expensereport_id;
+ $this->line->fk_c_type_fees = $type_fees_id;
+ $this->line->fk_c_exp_tax_cat = $fk_c_exp_tax_cat;
+ $this->line->fk_projet = $projet_id; // deprecated
+ $this->line->fk_project = $projet_id;
- $this->line->vat_src_code = $vat_src_code;
- $this->line->vatrate = price2num($vatrate);
- $this->line->total_ttc = $tmp[2];
- $this->line->total_ht = $tmp[0];
- $this->line->total_tva = $tmp[1];
- $this->line->localtax1_tx = $localtaxes_type[1];
- $this->line->localtax2_tx = $localtaxes_type[3];
- $this->line->localtax1_type = $localtaxes_type[0];
- $this->line->localtax2_type = $localtaxes_type[2];
+ $this->line->vat_src_code = $vat_src_code;
+ $this->line->vatrate = price2num($vatrate);
+ $this->line->total_ttc = $tmp[2];
+ $this->line->total_ht = $tmp[0];
+ $this->line->total_tva = $tmp[1];
+ $this->line->localtax1_tx = $localtaxes_type[1];
+ $this->line->localtax2_tx = $localtaxes_type[3];
+ $this->line->localtax1_type = $localtaxes_type[0];
+ $this->line->localtax2_type = $localtaxes_type[2];
- $this->line->fk_ecm_files = $fk_ecm_files;
+ $this->line->fk_ecm_files = $fk_ecm_files;
- $this->line->id = $rowid;
+ $this->line->id = $rowid;
- // Select des infos sur le type fees
- $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees";
- $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
- $sql .= " WHERE c.id = ".$type_fees_id;
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $objp_fees = $this->db->fetch_object($resql);
- $this->line->type_fees_code = $objp_fees->code_type_fees;
- $this->line->type_fees_libelle = $objp_fees->libelle_type_fees;
- $this->db->free($resql);
- }
+ // Select des infos sur le type fees
+ $sql = "SELECT c.code as code_type_fees, c.label as libelle_type_fees";
+ $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
+ $sql .= " WHERE c.id = ".$type_fees_id;
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $objp_fees = $this->db->fetch_object($resql);
+ $this->line->type_fees_code = $objp_fees->code_type_fees;
+ $this->line->type_fees_libelle = $objp_fees->libelle_type_fees;
+ $this->db->free($resql);
+ }
- // Select des informations du projet
- $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
- $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
- $sql .= " WHERE p.rowid = ".$projet_id;
- $resql = $this->db->query($sql);
- if ($resql) {
- $objp_projet = $this->db->fetch_object($resql);
- $this->line->projet_ref = $objp_projet->ref_projet;
- $this->line->projet_title = $objp_projet->title_projet;
- $this->db->free($resql);
- }
+ // Select des informations du projet
+ $sql = "SELECT p.ref as ref_projet, p.title as title_projet";
+ $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
+ $sql .= " WHERE p.rowid = ".$projet_id;
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $objp_projet = $this->db->fetch_object($resql);
+ $this->line->projet_ref = $objp_projet->ref_projet;
+ $this->line->projet_title = $objp_projet->title_projet;
+ $this->db->free($resql);
+ }
$this->applyOffset();
$this->checkRules();
- $result = $this->line->update($user);
- if ($result > 0)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->error = $this->line->error;
- $this->errors = $this->line->errors;
- $this->db->rollback();
- return -2;
- }
- }
- }
+ $result = $this->line->update($user);
+ if ($result > 0)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->error = $this->line->error;
+ $this->errors = $this->line->errors;
+ $this->db->rollback();
+ return -2;
+ }
+ }
+ }
- /**
- * deleteline
- *
- * @param int $rowid Row id
- * @param User $fuser User
- * @return int <0 if KO, >0 if OK
- */
- public function deleteline($rowid, $fuser = '')
- {
- $this->db->begin();
+ /**
+ * deleteline
+ *
+ * @param int $rowid Row id
+ * @param User $fuser User
+ * @return int <0 if KO, >0 if OK
+ */
+ public function deleteline($rowid, $fuser = '')
+ {
+ $this->db->begin();
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
- $sql .= ' WHERE rowid = '.$rowid;
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element_line;
+ $sql .= ' WHERE rowid = '.$rowid;
- dol_syslog(get_class($this)."::deleteline sql=".$sql);
- $result = $this->db->query($sql);
- if (!$result)
- {
- $this->error = $this->db->error();
- dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
- $this->db->rollback();
- return -1;
- }
+ dol_syslog(get_class($this)."::deleteline sql=".$sql);
+ $result = $this->db->query($sql);
+ if (!$result)
+ {
+ $this->error = $this->db->error();
+ dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR);
+ $this->db->rollback();
+ return -1;
+ }
- $this->db->commit();
+ $this->db->commit();
- return 1;
- }
+ return 1;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * periode_existe
- *
- * @param User $fuser User
- * @param integer $date_debut Start date
- * @param integer $date_fin End date
- * @return int <0 if KO, >0 if OK
- */
- public function periode_existe($fuser, $date_debut, $date_fin)
- {
- // phpcs:enable
- $sql = "SELECT rowid, date_debut, date_fin";
- $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
- $sql .= " WHERE fk_user_author = '{$fuser->id}'";
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * periode_existe
+ *
+ * @param User $fuser User
+ * @param integer $date_debut Start date
+ * @param integer $date_fin End date
+ * @return int <0 if KO, >0 if OK
+ */
+ public function periode_existe($fuser, $date_debut, $date_fin)
+ {
+ // phpcs:enable
+ $sql = "SELECT rowid, date_debut, date_fin";
+ $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
+ $sql .= " WHERE fk_user_author = '{$fuser->id}'";
- dol_syslog(get_class($this)."::periode_existe sql=".$sql);
- $result = $this->db->query($sql);
- if ($result) {
- $num_rows = $this->db->num_rows($result); $i = 0;
+ dol_syslog(get_class($this)."::periode_existe sql=".$sql);
+ $result = $this->db->query($sql);
+ if ($result) {
+ $num_rows = $this->db->num_rows($result); $i = 0;
- if ($num_rows > 0)
- {
- $date_d_form = $date_debut;
- $date_f_form = $date_fin;
+ if ($num_rows > 0)
+ {
+ $date_d_form = $date_debut;
+ $date_f_form = $date_fin;
- $existe = false;
+ $existe = false;
- while ($i < $num_rows)
- {
- $objp = $this->db->fetch_object($result);
+ while ($i < $num_rows)
+ {
+ $objp = $this->db->fetch_object($result);
- $date_d_req = $this->db->jdate($objp->date_debut); // 3
- $date_f_req = $this->db->jdate($objp->date_fin); // 4
+ $date_d_req = $this->db->jdate($objp->date_debut); // 3
+ $date_f_req = $this->db->jdate($objp->date_fin); // 4
- if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true;
+ if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true;
- $i++;
- }
+ $i++;
+ }
- if ($existe) return 1;
- else return 0;
- } else {
- return 0;
- }
- } else {
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR);
- return -1;
- }
- }
+ if ($existe) return 1;
+ else return 0;
+ } else {
+ return 0;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::periode_existe Error ".$this->error, LOG_ERR);
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Return list of people with permission to validate expense reports.
- * Search for permission "approve expense report"
- *
- * @return array Array of user ids
- */
- public function fetch_users_approver_expensereport()
- {
- // phpcs:enable
- $users_validator = array();
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return list of people with permission to validate expense reports.
+ * Search for permission "approve expense report"
+ *
+ * @return array Array of user ids
+ */
+ public function fetch_users_approver_expensereport()
+ {
+ // phpcs:enable
+ $users_validator = array();
- $sql = "SELECT DISTINCT ur.fk_user";
- $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
- $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
- $sql .= "UNION";
- $sql .= " SELECT DISTINCT ugu.fk_user";
- $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
- $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
- //print $sql;
+ $sql = "SELECT DISTINCT ur.fk_user";
+ $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
+ $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
+ $sql .= "UNION";
+ $sql .= " SELECT DISTINCT ugu.fk_user";
+ $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
+ $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'expensereport' AND rd.perms = 'approve'"; // Permission 'Approve';
+ //print $sql;
- dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
- $result = $this->db->query($sql);
- if ($result)
- {
- $num_rows = $this->db->num_rows($result); $i = 0;
- while ($i < $num_rows)
- {
- $objp = $this->db->fetch_object($result);
- array_push($users_validator, $objp->fk_user);
- $i++;
- }
- return $users_validator;
- } else {
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
- return -1;
- }
- }
+ dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql);
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ $num_rows = $this->db->num_rows($result); $i = 0;
+ while ($i < $num_rows)
+ {
+ $objp = $this->db->fetch_object($result);
+ array_push($users_validator, $objp->fk_user);
+ $i++;
+ }
+ return $users_validator;
+ } else {
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::fetch_users_approver_expensereport Error ".$this->error, LOG_ERR);
+ return -1;
+ }
+ }
- /**
- * Create a document onto disk accordign to template module.
- *
- * @param string $modele Force le mnodele a utiliser ('' 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;
+ /**
+ * Create a document onto disk accordign to template module.
+ *
+ * @param string $modele Force le mnodele a utiliser ('' 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;
- $langs->load("trips");
+ $langs->load("trips");
- if (!dol_strlen($modele)) {
- $modele = 'standard';
+ if (!dol_strlen($modele)) {
+ $modele = 'standard';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
- } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) {
- $modele = $conf->global->EXPENSEREPORT_ADDON_PDF;
- }
- }
+ if ($this->modelpdf) {
+ $modele = $this->modelpdf;
+ } elseif (!empty($conf->global->EXPENSEREPORT_ADDON_PDF)) {
+ $modele = $conf->global->EXPENSEREPORT_ADDON_PDF;
+ }
+ }
- $modelpath = "core/modules/expensereport/doc/";
+ $modelpath = "core/modules/expensereport/doc/";
- return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
- }
+ return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
- /**
- * List of types
- *
- * @param int $active Active or not
- * @return array
- */
- public function listOfTypes($active = 1)
- {
- global $langs;
- $ret = array();
- $sql = "SELECT id, code, label";
- $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
- $sql .= " WHERE active = ".$active;
- dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
- $result = $this->db->query($sql);
- if ($result)
- {
- $num = $this->db->num_rows($result);
- $i = 0;
- while ($i < $num)
- {
- $obj = $this->db->fetch_object($result);
- $ret[$obj->code] = (($langs->trans($obj->code) != $obj->code) ? $langs->trans($obj->code) : $obj->label);
- $i++;
- }
- } else {
- dol_print_error($this->db);
- }
- return $ret;
- }
+ /**
+ * List of types
+ *
+ * @param int $active Active or not
+ * @return array
+ */
+ public function listOfTypes($active = 1)
+ {
+ global $langs;
+ $ret = array();
+ $sql = "SELECT id, code, label";
+ $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees";
+ $sql .= " WHERE active = ".$active;
+ dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG);
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ $num = $this->db->num_rows($result);
+ $i = 0;
+ while ($i < $num)
+ {
+ $obj = $this->db->fetch_object($result);
+ $ret[$obj->code] = (($langs->trans($obj->code) != $obj->code) ? $langs->trans($obj->code) : $obj->label);
+ $i++;
+ }
+ } else {
+ dol_print_error($this->db);
+ }
+ return $ret;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Charge indicateurs this->nb pour le tableau de bord
- *
- * @return int <0 if KO, >0 if OK
- */
- public function load_state_board()
- {
- // phpcs:enable
- global $conf, $user;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Charge indicateurs this->nb pour le tableau de bord
+ *
+ * @return int <0 if KO, >0 if OK
+ */
+ public function load_state_board()
+ {
+ // phpcs:enable
+ global $conf, $user;
- $this->nb = array();
+ $this->nb = array();
- $sql = "SELECT count(ex.rowid) as nb";
- $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
- $sql .= " WHERE ex.fk_statut > 0";
- $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
+ $sql = "SELECT count(ex.rowid) as nb";
+ $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
+ $sql .= " WHERE ex.fk_statut > 0";
+ $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
if (empty($user->rights->expensereport->readall))
{
$userchildids = $user->getAllChildIds(1);
@@ -2235,145 +2235,145 @@ class ExpenseReport extends CommonObject
$sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))";
}
- $resql = $this->db->query($sql);
- if ($resql) {
- while ($obj = $this->db->fetch_object($resql)) {
- $this->nb["expensereports"] = $obj->nb;
- }
- $this->db->free($resql);
- return 1;
- } else {
- dol_print_error($this->db);
- $this->error = $this->db->error();
- return -1;
- }
- }
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ while ($obj = $this->db->fetch_object($resql)) {
+ $this->nb["expensereports"] = $obj->nb;
+ }
+ $this->db->free($resql);
+ return 1;
+ } else {
+ dol_print_error($this->db);
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
- *
- * @param User $user Objet user
- * @param string $option 'topay' or 'toapprove'
- * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
- */
- public function load_board($user, $option = 'topay')
- {
- // phpcs:enable
- global $conf, $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
+ *
+ * @param User $user Objet user
+ * @param string $option 'topay' or 'toapprove'
+ * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
+ */
+ public function load_board($user, $option = 'topay')
+ {
+ // phpcs:enable
+ global $conf, $langs;
- if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe
+ if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe
- $now = dol_now();
+ $now = dol_now();
- $sql = "SELECT ex.rowid, ex.date_valid";
- $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
- if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = 2";
- else $sql .= " WHERE ex.fk_statut = 5";
- $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
- if (empty($user->rights->expensereport->readall))
- {
+ $sql = "SELECT ex.rowid, ex.date_valid";
+ $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex";
+ if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = 2";
+ else $sql .= " WHERE ex.fk_statut = 5";
+ $sql .= " AND ex.entity IN (".getEntity('expensereport').")";
+ if (empty($user->rights->expensereport->readall))
+ {
$userchildids = $user->getAllChildIds(1);
$sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")";
$sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))";
}
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $langs->load("trips");
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $langs->load("trips");
- $response = new WorkboardResponse();
- if ($option == 'toapprove')
- {
- $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
- $response->label = $langs->trans("ExpenseReportsToApprove");
- $response->labelShort = $langs->trans("ToApprove");
- $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=2';
- } else {
- $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
- $response->label = $langs->trans("ExpenseReportsToPay");
- $response->labelShort = $langs->trans("StatusToPay");
- $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=5';
- }
- $response->img = img_object('', "trip");
+ $response = new WorkboardResponse();
+ if ($option == 'toapprove')
+ {
+ $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24;
+ $response->label = $langs->trans("ExpenseReportsToApprove");
+ $response->labelShort = $langs->trans("ToApprove");
+ $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=2';
+ } else {
+ $response->warning_delay = $conf->expensereport->payment->warning_delay / 60 / 60 / 24;
+ $response->label = $langs->trans("ExpenseReportsToPay");
+ $response->labelShort = $langs->trans("StatusToPay");
+ $response->url = DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&statut=5';
+ }
+ $response->img = img_object('', "trip");
- while ($obj = $this->db->fetch_object($resql))
- {
- $response->nbtodo++;
+ while ($obj = $this->db->fetch_object($resql))
+ {
+ $response->nbtodo++;
- if ($option == 'toapprove')
- {
- if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
- $response->nbtodolate++;
- }
- } else {
- if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
- $response->nbtodolate++;
- }
- }
- }
+ if ($option == 'toapprove')
+ {
+ if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) {
+ $response->nbtodolate++;
+ }
+ } else {
+ if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->payment->warning_delay)) {
+ $response->nbtodolate++;
+ }
+ }
+ }
- return $response;
- } else {
- dol_print_error($this->db);
- $this->error = $this->db->error();
- return -1;
- }
- }
+ return $response;
+ } else {
+ dol_print_error($this->db);
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- /**
- * Return if an expense report is late or not
- *
- * @param string $option 'topay' or 'toapprove'
- * @return boolean True if late, False if not late
- */
- public function hasDelay($option)
- {
- global $conf;
+ /**
+ * Return if an expense report is late or not
+ *
+ * @param string $option 'topay' or 'toapprove'
+ * @return boolean True if late, False if not late
+ */
+ public function hasDelay($option)
+ {
+ global $conf;
- // Only valid expenses reports
- if ($option == 'toapprove' && $this->status != 2) return false;
- if ($option == 'topay' && $this->status != 5) return false;
+ // Only valid expenses reports
+ if ($option == 'toapprove' && $this->status != 2) return false;
+ if ($option == 'topay' && $this->status != 5) return false;
- $now = dol_now();
- if ($option == 'toapprove')
- {
- return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay);
- } else return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay);
- }
+ $now = dol_now();
+ if ($option == 'toapprove')
+ {
+ return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->approve->warning_delay);
+ } else return ($this->datevalid ? $this->datevalid : $this->date_valid) < ($now - $conf->expensereport->payment->warning_delay);
+ }
- /**
- * Return if an expensereport was dispatched into bookkeeping
- *
- * @return int <0 if KO, 0=no, 1=yes
- */
- public function getVentilExportCompta()
- {
- $alreadydispatched = 0;
+ /**
+ * Return if an expensereport was dispatched into bookkeeping
+ *
+ * @return int <0 if KO, 0=no, 1=yes
+ */
+ public function getVentilExportCompta()
+ {
+ $alreadydispatched = 0;
- $type = 'expense_report';
+ $type = 'expense_report';
- $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id;
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $obj = $this->db->fetch_object($resql);
- if ($obj)
- {
- $alreadydispatched = $obj->nb;
- }
- } else {
- $this->error = $this->db->lasterror();
- return -1;
- }
+ $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id;
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $obj = $this->db->fetch_object($resql);
+ if ($obj)
+ {
+ $alreadydispatched = $obj->nb;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
- if ($alreadydispatched)
- {
- return 1;
- }
- return 0;
- }
+ if ($alreadydispatched)
+ {
+ return 1;
+ }
+ return 0;
+ }
/**
* Return amount of payments already done
@@ -2409,174 +2409,174 @@ class ExpenseReport extends CommonObject
*/
class ExpenseReportLine
{
- /**
- * @var DoliDB Database handler.
- */
- public $db;
+ /**
+ * @var DoliDB Database handler.
+ */
+ public $db;
- /**
+ /**
* @var string Error code (or message)
*/
public $error = '';
- /**
+ /**
* @var int ID
*/
public $rowid;
- public $comments;
- public $qty;
- public $value_unit;
- public $date;
+ public $comments;
+ public $qty;
+ public $value_unit;
+ public $date;
- /**
- * @var int ID
- */
- public $fk_c_type_fees;
+ /**
+ * @var int ID
+ */
+ public $fk_c_type_fees;
- /**
- * @var int ID
- */
- public $fk_c_exp_tax_cat;
+ /**
+ * @var int ID
+ */
+ public $fk_c_exp_tax_cat;
- /**
- * @var int ID
- */
- public $fk_projet;
+ /**
+ * @var int ID
+ */
+ public $fk_projet;
- /**
- * @var int ID
- */
- public $fk_expensereport;
+ /**
+ * @var int ID
+ */
+ public $fk_expensereport;
- public $type_fees_code;
- public $type_fees_libelle;
+ public $type_fees_code;
+ public $type_fees_libelle;
- public $projet_ref;
- public $projet_title;
+ public $projet_ref;
+ public $projet_title;
- public $vatrate;
- public $total_ht;
- public $total_tva;
- public $total_ttc;
+ public $vatrate;
+ public $total_ht;
+ public $total_tva;
+ public $total_ttc;
- /**
- * @var int ID into llx_ecm_files table to link line to attached file
- */
- public $fk_ecm_files;
+ /**
+ * @var int ID into llx_ecm_files table to link line to attached file
+ */
+ public $fk_ecm_files;
- /**
- * Constructor
- *
- * @param DoliDB $db Handlet database
- */
- public function __construct($db)
- {
- $this->db = $db;
- }
+ /**
+ * Constructor
+ *
+ * @param DoliDB $db Handlet database
+ */
+ public function __construct($db)
+ {
+ $this->db = $db;
+ }
- /**
- * Fetch record for expense report detailed line
- *
- * @param int $rowid Id of object to load
- * @return int <0 if KO, >0 if OK
- */
- public function fetch($rowid)
- {
- $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,';
- $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,';
- $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,';
- $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref';
- $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde';
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here.
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid';
- $sql .= ' WHERE fde.rowid = '.$rowid;
+ /**
+ * Fetch record for expense report detailed line
+ *
+ * @param int $rowid Id of object to load
+ * @return int <0 if KO, >0 if OK
+ */
+ public function fetch($rowid)
+ {
+ $sql = 'SELECT fde.rowid, fde.fk_expensereport, fde.fk_c_type_fees, fde.fk_c_exp_tax_cat, fde.fk_projet as fk_project, fde.date,';
+ $sql .= ' fde.tva_tx as vatrate, fde.vat_src_code, fde.comments, fde.qty, fde.value_unit, fde.total_ht, fde.total_tva, fde.total_ttc, fde.fk_ecm_files,';
+ $sql .= ' ctf.code as type_fees_code, ctf.label as type_fees_libelle,';
+ $sql .= ' pjt.rowid as projet_id, pjt.title as projet_title, pjt.ref as projet_ref';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det as fde';
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON fde.fk_c_type_fees=ctf.id'; // Sometimes type of expense report has been removed, so we use a left join here.
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as pjt ON fde.fk_projet=pjt.rowid';
+ $sql .= ' WHERE fde.rowid = '.$rowid;
- $result = $this->db->query($sql);
+ $result = $this->db->query($sql);
- if ($result)
- {
- $objp = $this->db->fetch_object($result);
+ if ($result)
+ {
+ $objp = $this->db->fetch_object($result);
- $this->rowid = $objp->rowid;
- $this->id = $objp->rowid;
- $this->ref = $objp->ref;
- $this->fk_expensereport = $objp->fk_expensereport;
- $this->comments = $objp->comments;
- $this->qty = $objp->qty;
- $this->date = $objp->date;
- $this->dates = $this->db->jdate($objp->date);
- $this->value_unit = $objp->value_unit;
- $this->fk_c_type_fees = $objp->fk_c_type_fees;
- $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
- $this->fk_projet = $objp->fk_project; // deprecated
- $this->fk_project = $objp->fk_project;
- $this->type_fees_code = $objp->type_fees_code;
- $this->type_fees_libelle = $objp->type_fees_libelle;
- $this->projet_ref = $objp->projet_ref;
- $this->projet_title = $objp->projet_title;
- $this->vatrate = $objp->vatrate;
- $this->vat_src_code = $objp->vat_src_code;
- $this->total_ht = $objp->total_ht;
- $this->total_tva = $objp->total_tva;
- $this->total_ttc = $objp->total_ttc;
- $this->fk_ecm_files = $objp->fk_ecm_files;
+ $this->rowid = $objp->rowid;
+ $this->id = $objp->rowid;
+ $this->ref = $objp->ref;
+ $this->fk_expensereport = $objp->fk_expensereport;
+ $this->comments = $objp->comments;
+ $this->qty = $objp->qty;
+ $this->date = $objp->date;
+ $this->dates = $this->db->jdate($objp->date);
+ $this->value_unit = $objp->value_unit;
+ $this->fk_c_type_fees = $objp->fk_c_type_fees;
+ $this->fk_c_exp_tax_cat = $objp->fk_c_exp_tax_cat;
+ $this->fk_projet = $objp->fk_project; // deprecated
+ $this->fk_project = $objp->fk_project;
+ $this->type_fees_code = $objp->type_fees_code;
+ $this->type_fees_libelle = $objp->type_fees_libelle;
+ $this->projet_ref = $objp->projet_ref;
+ $this->projet_title = $objp->projet_title;
+ $this->vatrate = $objp->vatrate;
+ $this->vat_src_code = $objp->vat_src_code;
+ $this->total_ht = $objp->total_ht;
+ $this->total_tva = $objp->total_tva;
+ $this->total_ttc = $objp->total_ttc;
+ $this->fk_ecm_files = $objp->fk_ecm_files;
- $this->db->free($result);
- } else {
- dol_print_error($this->db);
- }
- }
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
- /**
- * insert
- *
- * @param int $notrigger 1=No trigger
- * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object
- * @return int <0 if KO, >0 if OK
- */
- public function insert($notrigger = 0, $fromaddline = false)
- {
- global $langs, $user, $conf;
+ /**
+ * insert
+ *
+ * @param int $notrigger 1=No trigger
+ * @param bool $fromaddline false=keep default behavior, true=exclude the update_price() of parent object
+ * @return int <0 if KO, >0 if OK
+ */
+ public function insert($notrigger = 0, $fromaddline = false)
+ {
+ global $langs, $user, $conf;
- $error = 0;
+ $error = 0;
- dol_syslog("ExpenseReportLine::Insert rang=".$this->rang, LOG_DEBUG);
+ dol_syslog("ExpenseReportLine::Insert rang=".$this->rang, LOG_DEBUG);
- // Clean parameters
- $this->comments = trim($this->comments);
- if (!$this->value_unit_HT) $this->value_unit_HT = 0;
- $this->qty = price2num($this->qty);
- $this->vatrate = price2num($this->vatrate);
+ // Clean parameters
+ $this->comments = trim($this->comments);
+ if (!$this->value_unit_HT) $this->value_unit_HT = 0;
+ $this->qty = price2num($this->qty);
+ $this->vatrate = price2num($this->vatrate);
if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0;
- $this->db->begin();
+ $this->db->begin();
- $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det';
- $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,';
- $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)';
- $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).",";
- $sql .= " ".$this->db->escape($this->fk_c_type_fees).",";
- $sql .= " ".$this->db->escape($this->fk_project > 0 ? $this->fk_project : ($this->fk_projet > 0 ? $this->fk_projet : 'null')).",";
- $sql .= " ".$this->db->escape($this->vatrate).",";
- $sql .= " '".$this->db->escape($this->vat_src_code)."',";
- $sql .= " '".$this->db->escape($this->comments)."',";
- $sql .= " ".$this->db->escape($this->qty).",";
- $sql .= " ".$this->db->escape($this->value_unit).",";
- $sql .= " ".$this->db->escape($this->total_ht).",";
- $sql .= " ".$this->db->escape($this->total_tva).",";
- $sql .= " ".$this->db->escape($this->total_ttc).",";
- $sql .= " '".$this->db->idate($this->date)."',";
+ $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'expensereport_det';
+ $sql .= ' (fk_expensereport, fk_c_type_fees, fk_projet,';
+ $sql .= ' tva_tx, vat_src_code, comments, qty, value_unit, total_ht, total_tva, total_ttc, date, rule_warning_message, fk_c_exp_tax_cat, fk_ecm_files)';
+ $sql .= " VALUES (".$this->db->escape($this->fk_expensereport).",";
+ $sql .= " ".$this->db->escape($this->fk_c_type_fees).",";
+ $sql .= " ".$this->db->escape($this->fk_project > 0 ? $this->fk_project : ($this->fk_projet > 0 ? $this->fk_projet : 'null')).",";
+ $sql .= " ".$this->db->escape($this->vatrate).",";
+ $sql .= " '".$this->db->escape($this->vat_src_code)."',";
+ $sql .= " '".$this->db->escape($this->comments)."',";
+ $sql .= " ".$this->db->escape($this->qty).",";
+ $sql .= " ".$this->db->escape($this->value_unit).",";
+ $sql .= " ".$this->db->escape($this->total_ht).",";
+ $sql .= " ".$this->db->escape($this->total_tva).",";
+ $sql .= " ".$this->db->escape($this->total_ttc).",";
+ $sql .= " '".$this->db->idate($this->date)."',";
$sql .= " '".$this->db->escape($this->rule_warning_message)."',";
$sql .= " ".$this->db->escape($this->fk_c_exp_tax_cat).",";
$sql .= " ".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null');
- $sql .= ")";
+ $sql .= ")";
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det');
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det');
if (!$fromaddline)
{
@@ -2590,21 +2590,21 @@ class ExpenseReportLine
$this->errors = $tmpparent->errors;
}
}
- } else {
+ } else {
$error++;
}
- if (!$error)
- {
- $this->db->commit();
- return $this->id;
- } else {
- $this->error = $this->db->lasterror();
- dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR);
- $this->db->rollback();
- return -2;
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->error = $this->db->lasterror();
+ dol_syslog("ExpenseReportLine::insert Error ".$this->error, LOG_ERR);
+ $this->db->rollback();
+ return -2;
+ }
+ }
/**
* Function to get total amount in expense reports for a same rule
@@ -2646,83 +2646,83 @@ class ExpenseReportLine
return $amount + $this->total_ttc;
}
- /**
- * Update line
- *
- * @param User $user User
- * @return int <0 if KO, >0 if OK
- */
- public function update(User $user)
- {
- global $langs, $conf;
+ /**
+ * Update line
+ *
+ * @param User $user User
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user)
+ {
+ global $langs, $conf;
- $error = 0;
+ $error = 0;
- // Clean parameters
- $this->comments = trim($this->comments);
- $this->vatrate = price2num($this->vatrate);
- $this->value_unit = price2num($this->value_unit);
+ // Clean parameters
+ $this->comments = trim($this->comments);
+ $this->vatrate = price2num($this->vatrate);
+ $this->value_unit = price2num($this->value_unit);
if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0;
- $this->db->begin();
+ $this->db->begin();
- // Update line in database
- $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET";
- $sql .= " comments='".$this->db->escape($this->comments)."'";
- $sql .= ",value_unit=".$this->db->escape($this->value_unit);
- $sql .= ",qty=".$this->db->escape($this->qty);
- $sql .= ",date='".$this->db->idate($this->date)."'";
- $sql .= ",total_ht=".$this->db->escape($this->total_ht)."";
- $sql .= ",total_tva=".$this->db->escape($this->total_tva)."";
- $sql .= ",total_ttc=".$this->db->escape($this->total_ttc)."";
- $sql .= ",tva_tx=".$this->db->escape($this->vatrate);
+ // Update line in database
+ $sql = "UPDATE ".MAIN_DB_PREFIX."expensereport_det SET";
+ $sql .= " comments='".$this->db->escape($this->comments)."'";
+ $sql .= ",value_unit=".$this->db->escape($this->value_unit);
+ $sql .= ",qty=".$this->db->escape($this->qty);
+ $sql .= ",date='".$this->db->idate($this->date)."'";
+ $sql .= ",total_ht=".$this->db->escape($this->total_ht)."";
+ $sql .= ",total_tva=".$this->db->escape($this->total_tva)."";
+ $sql .= ",total_ttc=".$this->db->escape($this->total_ttc)."";
+ $sql .= ",tva_tx=".$this->db->escape($this->vatrate);
$sql .= ",vat_src_code='".$this->db->escape($this->vat_src_code)."'";
- $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'";
+ $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'";
$sql .= ",fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat);
$sql .= ",fk_ecm_files=".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null');
if ($this->fk_c_type_fees) $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees);
- else $sql .= ",fk_c_type_fees=null";
- if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project);
- else $sql .= ",fk_projet=null";
- $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id);
+ else $sql .= ",fk_c_type_fees=null";
+ if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project);
+ else $sql .= ",fk_projet=null";
+ $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id);
- dol_syslog("ExpenseReportLine::update sql=".$sql);
+ dol_syslog("ExpenseReportLine::update sql=".$sql);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $tmpparent = new ExpenseReport($this->db);
- $result = $tmpparent->fetch($this->fk_expensereport);
- if ($result > 0)
- {
- $result = $tmpparent->update_price();
- if ($result < 0)
- {
- $error++;
- $this->error = $tmpparent->error;
- $this->errors = $tmpparent->errors;
- }
- } else {
- $error++;
- $this->error = $tmpparent->error;
- $this->errors = $tmpparent->errors;
- }
- } else {
- $error++;
- dol_print_error($this->db);
- }
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $tmpparent = new ExpenseReport($this->db);
+ $result = $tmpparent->fetch($this->fk_expensereport);
+ if ($result > 0)
+ {
+ $result = $tmpparent->update_price();
+ if ($result < 0)
+ {
+ $error++;
+ $this->error = $tmpparent->error;
+ $this->errors = $tmpparent->errors;
+ }
+ } else {
+ $error++;
+ $this->error = $tmpparent->error;
+ $this->errors = $tmpparent->errors;
+ }
+ } else {
+ $error++;
+ dol_print_error($this->db);
+ }
- if (!$error)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->error = $this->db->lasterror();
- dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR);
- $this->db->rollback();
- return -2;
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->error = $this->db->lasterror();
+ dol_syslog("ExpenseReportLine::update Error ".$this->error, LOG_ERR);
+ $this->db->rollback();
+ return -2;
+ }
+ }
}
@@ -2738,26 +2738,26 @@ class ExpenseReportLine
*/
function select_expensereport_statut($selected = '', $htmlname = 'fk_statut', $useempty = 1, $useshortlabel = 0)
{
- global $db, $langs;
+ global $db, $langs;
- $tmpep = new ExpenseReport($db);
+ $tmpep = new ExpenseReport($db);
- print '';
- if ($useempty) print ' ';
- $arrayoflabels = $tmpep->statuts;
- if ($useshortlabel) $arrayoflabels = $tmpep->statuts_short;
- foreach ($arrayoflabels as $key => $val)
- {
- if ($selected != '' && $selected == $key)
- {
- print '';
- } else {
- print ' ';
- }
- print $langs->trans($val);
- print ' ';
- }
- print ' ';
+ print '';
+ if ($useempty) print ' ';
+ $arrayoflabels = $tmpep->statuts;
+ if ($useshortlabel) $arrayoflabels = $tmpep->statuts_short;
+ foreach ($arrayoflabels as $key => $val)
+ {
+ if ($selected != '' && $selected == $key)
+ {
+ print '';
+ } else {
+ print ' ';
+ }
+ print $langs->trans($val);
+ print ' ';
+ }
+ print ' ';
}
/**
@@ -2771,36 +2771,41 @@ function select_expensereport_statut($selected = '', $htmlname = 'fk_statut', $u
*/
function select_type_fees_id($selected = '', $htmlname = 'type', $showempty = 0, $active = 1)
{
- global $db, $langs, $user;
- $langs->load("trips");
+ global $db, $langs, $user;
+ $langs->load("trips");
- print '';
- if ($showempty)
- {
- print ' ';
- }
+ $out = '';
- $sql = "SELECT c.id, c.code, c.label as type FROM ".MAIN_DB_PREFIX."c_type_fees as c";
- if ($active >= 0) $sql .= " WHERE c.active = ".$active;
- $sql .= " ORDER BY c.label ASC";
- $resql = $db->query($sql);
- if ($resql)
- {
- $num = $db->num_rows($resql);
- $i = 0;
+ $out .= '';
+ if ($showempty)
+ {
+ $out .= 'fetch_object($resql);
- print ' code == $selected || $obj->id == $selected) print ' selected';
- print '>';
- if ($obj->code != $langs->trans($obj->code)) print $langs->trans($obj->code);
- else print $langs->trans($obj->type);
- $i++;
- }
- }
- print ' ';
+ $sql = "SELECT c.id, c.code, c.label as type FROM ".MAIN_DB_PREFIX."c_type_fees as c";
+ if ($active >= 0) $sql .= " WHERE c.active = ".$active;
+ $sql .= " ORDER BY c.label ASC";
+ $resql = $db->query($sql);
+ if ($resql)
+ {
+ $num = $db->num_rows($resql);
+ $i = 0;
+
+ while ($i < $num)
+ {
+ $obj = $db->fetch_object($resql);
+ $out .= 'code == $selected || $obj->id == $selected) $out .= ' selected';
+ $out .= '>';
+ if ($obj->code != $langs->trans($obj->code)) $out .= $langs->trans($obj->code);
+ else $out .= $langs->trans($obj->type);
+ $i++;
+ }
+ }
+ $out .= ' ';
+ $out .= ajax_combobox($htmlname);
+
+ return $out;
}
diff --git a/htdocs/expensereport/payment/card.php b/htdocs/expensereport/payment/card.php
index 3e8da949bff..fd1453b8ae5 100644
--- a/htdocs/expensereport/payment/card.php
+++ b/htdocs/expensereport/payment/card.php
@@ -94,7 +94,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->expensere
$outputlangs->setDefaultLang($_REQUEST['lang_id']);
}
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
- $fac->generateDocument($fac->modelpdf, $outputlangs);
+ $fac->generateDocument($fac->model_pdf, $outputlangs);
}
}
diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php
index f8e34cc5b55..612529b6cc1 100644
--- a/htdocs/fichinter/card.php
+++ b/htdocs/fichinter/card.php
@@ -167,7 +167,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->modelpdf : GETPOST('model', 'alpha'), $outputlangs);
+ $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->model_pdf : GETPOST('model', 'alpha'), $outputlangs);
}
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
@@ -192,7 +192,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->modelpdf : GETPOST('model', 'alpha'), $outputlangs);
+ $result = fichinter_create($db, $object, (!GETPOST('model', 'alpha')) ? $object->model_pdf : GETPOST('model', 'alpha'), $outputlangs);
}
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
@@ -209,7 +209,7 @@ if (empty($reshook))
$object->author = $user->id;
$object->description = GETPOST('description', 'none');
$object->ref = $ref;
- $object->modelpdf = GETPOST('model', 'alpha');
+ $object->model_pdf = GETPOST('model', 'alpha');
$object->note_private = GETPOST('note_private', 'none');
$object->note_public = GETPOST('note_public', 'none');
@@ -506,7 +506,7 @@ if (empty($reshook))
{
$db->commit();
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs);
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs);
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
} else {
@@ -603,7 +603,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs);
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs);
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
@@ -638,7 +638,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs);
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs);
}
/*
@@ -658,7 +658,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs);
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs);
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid);
exit;
@@ -676,7 +676,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs);
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs);
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid);
exit;
@@ -1653,7 +1653,7 @@ if ($action == 'create')
$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
$genallowed = $user->rights->ficheinter->lire;
$delallowed = $user->rights->ficheinter->creer;
- print $formfile->showdocuments('ficheinter', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
+ print $formfile->showdocuments('ficheinter', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
// Show links to link elements
$linktoelem = $form->showLinkToObjectBlock($object, null, array('fichinter'));
diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php
index c6c5fd587e6..bca82177381 100644
--- a/htdocs/fichinter/class/fichinter.class.php
+++ b/htdocs/fichinter/class/fichinter.class.php
@@ -2,7 +2,7 @@
/* Copyright (C) 2002-2003 Rodolphe Quiedeville
* Copyright (C) 2004-2014 Laurent Destailleur
* Copyright (C) 2005-2012 Regis Houssin
- * Copyright (C) 2011-2013 Juanjo Menent
+ * Copyright (C) 2011-2020 Juanjo Menent
* Copyright (C) 2015 Marcos GarcÃa
* Copyright (C) 2015 Charlie Benke
* Copyright (C) 2018 Nicolas ZABOURI
@@ -279,7 +279,7 @@ class Fichinter extends CommonObject
$sql .= ", ".$user->id;
$sql .= ", ".$user->id;
$sql .= ", ".($this->description ? "'".$this->db->escape($this->description)."'" : "null");
- $sql .= ", '".$this->db->escape($this->modelpdf)."'";
+ $sql .= ", '".$this->db->escape($this->model_pdf)."'";
$sql .= ", ".($this->fk_project ? $this->fk_project : 0);
$sql .= ", ".($this->fk_contrat ? $this->fk_contrat : 0);
$sql .= ", ".$this->statut;
@@ -449,7 +449,7 @@ class Fichinter extends CommonObject
$this->note_public = $obj->note_public;
$this->note_private = $obj->note_private;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf;
+ $this->modelpdf = $obj->model_pdf; // deprecated
$this->fk_contrat = $obj->fk_contrat;
$this->user_creation = $obj->fk_user_author;
@@ -765,7 +765,7 @@ class Fichinter extends CommonObject
$result = '';
- $label = ''.$langs->trans("ShowIntervention").' ';
+ $label = img_picto('', $this->picto).' '.$langs->trans("Intervention").' ';
$label .= ''.$langs->trans('Ref').': '.$this->ref;
if (isset($this->status)) {
$label .= ''.$langs->trans("Status").": ".$this->getLibStatut(5);
@@ -1009,6 +1009,9 @@ class Fichinter extends CommonObject
if (!$error)
{
+ // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
+ $this->deleteEcmFiles();
+
// Remove directory with files
$fichinterref = dol_sanitizeFileName($this->ref);
if ($conf->ficheinter->dir_output)
diff --git a/htdocs/fichinter/class/fichinterrec.class.php b/htdocs/fichinter/class/fichinterrec.class.php
index b9e43dae5e0..51bc9e53ff2 100644
--- a/htdocs/fichinter/class/fichinterrec.class.php
+++ b/htdocs/fichinter/class/fichinterrec.class.php
@@ -177,7 +177,7 @@ class FichinterRec extends Fichinter
$sql .= ", null, null";
}
- $sql .= ", ".(!empty($fichintsrc->modelpdf) ? "'".$this->db->escape($fichintsrc->modelpdf)."'" : "''");
+ $sql .= ", ".(!empty($fichintsrc->model_pdf) ? "'".$this->db->escape($fichintsrc->model_pdf)."'" : "''");
// récurrence
$sql .= ", ".(!empty($this->frequency) ? $this->frequency : "null");
diff --git a/htdocs/filefunc.inc.php b/htdocs/filefunc.inc.php
index d9f3d3a14c3..8912fd2a299 100644
--- a/htdocs/filefunc.inc.php
+++ b/htdocs/filefunc.inc.php
@@ -276,8 +276,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
//print memory_get_usage();
-// If password is encoded, we decode it
-if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass))
+// If password is encoded, we decode it. Note: When page is called for install, $dolibarr_main_db_pass may not be defined yet.
+if (!empty($dolibarr_main_db_pass) && preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass))
{
if (preg_match('/crypted:/i', $dolibarr_main_db_pass))
{
diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php
index 3060fd88157..00171264ddb 100644
--- a/htdocs/fourn/class/api_supplier_invoices.class.php
+++ b/htdocs/fourn/class/api_supplier_invoices.class.php
@@ -30,519 +30,519 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
*/
class SupplierInvoices extends DolibarrApi
{
- /**
- *
- * @var array $FIELDS Mandatory fields, checked when create and update object
- */
- static $FIELDS = array(
- 'socid',
- );
+ /**
+ *
+ * @var array $FIELDS Mandatory fields, checked when create and update object
+ */
+ static $FIELDS = array(
+ 'socid',
+ );
- /**
- * @var FactureFournisseur $invoice {@type FactureFournisseur}
- */
- public $invoice;
+ /**
+ * @var FactureFournisseur $invoice {@type FactureFournisseur}
+ */
+ public $invoice;
- /**
- * Constructor
- */
- public function __construct()
- {
- global $db;
- $this->db = $db;
- $this->invoice = new FactureFournisseur($this->db);
- }
+ /**
+ * Constructor
+ */
+ public function __construct()
+ {
+ global $db;
+ $this->db = $db;
+ $this->invoice = new FactureFournisseur($this->db);
+ }
- /**
- * Get properties of a supplier invoice object
- *
- * Return an array with supplier invoice information
- *
- * @param int $id ID of supplier invoice
- * @return array|mixed data without useless information
- *
- * @throws RestException
- */
- public function get($id)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) {
- throw new RestException(401);
- }
+ /**
+ * Get properties of a supplier invoice object
+ *
+ * Return an array with supplier invoice information
+ *
+ * @param int $id ID of supplier invoice
+ * @return array|mixed data without useless information
+ *
+ * @throws RestException
+ */
+ public function get($id)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) {
+ throw new RestException(401);
+ }
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Supplier invoice not found');
- }
-
- if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
-
- $this->invoice->fetchObjectLinked();
- return $this->_cleanObjectDatas($this->invoice);
- }
-
- /**
- * List invoices
- *
- * Get a list of supplier invoices
- *
- * @param string $sortfield Sort field
- * @param string $sortorder Sort order
- * @param int $limit Limit for list
- * @param int $page Page number
- * @param string $thirdparty_ids Thirdparty ids to filter invoices of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
- * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled
- * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
- * @return array Array of invoice objects
- *
- * @throws RestException
- */
- public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '')
- {
- global $db;
-
- $obj_ret = array();
-
- // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
- $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
-
- // If the internal user must only see his customers, force searching by him
- $search_sale = 0;
- if (!DolibarrApiAccess::$user->rights->societe->client->voir) $search_sale = DolibarrApiAccess::$user->id;
-
- $sql = "SELECT t.rowid";
- // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
- if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user";
- $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t";
-
- // We need this table joined to the select in order to filter by sale
- if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-
- $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')';
- if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
- if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
- if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
-
- // Filter by status
- if ($status == 'draft') {
- $sql .= " AND t.fk_statut IN (0)";
- }
- if ($status == 'unpaid') {
- $sql .= " AND t.fk_statut IN (1)";
- }
- if ($status == 'paid') {
- $sql .= " AND t.fk_statut IN (2)";
- }
- if ($status == 'cancelled') {
- $sql .= " AND t.fk_statut IN (3)";
- }
- // Insert sale filter
- if ($search_sale > 0) {
- $sql .= " AND sc.fk_user = ".$search_sale;
- }
- // Add sql filters
- if ($sqlfilters)
- {
- if (!DolibarrApi::_checkFilters($sqlfilters))
- {
- throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
- }
- $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
- $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
- }
-
- $sql .= $db->order($sortfield, $sortorder);
- if ($limit) {
- if ($page < 0)
- {
- $page = 0;
- }
- $offset = $limit * $page;
-
- $sql .= $db->plimit($limit + 1, $offset);
- }
-
- $result = $db->query($sql);
- if ($result) {
- $i = 0;
- $num = $db->num_rows($result);
- $min = min($num, ($limit <= 0 ? $num : $limit));
- while ($i < $min)
- {
- $obj = $db->fetch_object($result);
- $invoice_static = new FactureFournisseur($db);
- if ($invoice_static->fetch($obj->rowid)) {
- $obj_ret[] = $this->_cleanObjectDatas($invoice_static);
- }
- $i++;
- }
- } else {
- throw new RestException(503, 'Error when retrieve supplier invoice list : '.$db->lasterror());
- }
- if (!count($obj_ret)) {
- throw new RestException(404, 'No supplier invoice found');
- }
- return $obj_ret;
- }
-
- /**
- * Create supplier invoice object
- *
- * @param array $request_data Request datas
- *
- * @return int ID of supplier invoice
- *
- * @throws RestException 401
- * @throws RestException 500
- */
- public function post($request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
- throw new RestException(401, "Insuffisant rights");
- }
- // Check mandatory fields
- $result = $this->_validate($request_data);
-
- foreach ($request_data as $field => $value) {
- $this->invoice->$field = $value;
- }
- if (!array_key_exists('date', $request_data)) {
- $this->invoice->date = dol_now();
- }
-
- if ($this->invoice->create(DolibarrApiAccess::$user) < 0) {
- throw new RestException(500, "Error creating order", array_merge(array($this->invoice->error), $this->invoice->errors));
- }
- return $this->invoice->id;
- }
-
- /**
- * Update supplier invoice
- *
- * @param int $id Id of supplier invoice to update
- * @param array $request_data Datas
- *
- * @return int
- *
- * @throws RestException 401
- * @throws RestException 404
- */
- public function put($id, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
- throw new RestException(401);
- }
-
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Supplier invoice not found');
- }
-
- if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
-
- foreach ($request_data as $field => $value) {
- if ($field == 'id') continue;
- $this->invoice->$field = $value;
- }
-
- if ($this->invoice->update($id, DolibarrApiAccess::$user))
- return $this->get($id);
-
- return false;
- }
-
- /**
- * Delete supplier invoice
- *
- * @param int $id Supplier invoice ID
- *
- * @return array
- *
- * @throws RestException 401
- * @throws RestException 404
- * @throws RestException 500
- */
- public function delete($id)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->supprimer) {
- throw new RestException(401);
- }
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Supplier invoice not found');
- }
-
- if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
-
- if ($this->invoice->delete(DolibarrApiAccess::$user) < 0)
- {
- throw new RestException(500);
- }
-
- return array(
- 'success' => array(
- 'code' => 200,
- 'message' => 'Supplier invoice deleted'
- )
- );
- }
-
- /**
- * Validate an invoice
- *
- * @param int $id Invoice ID
- * @param int $idwarehouse Warehouse ID
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- *
- * @url POST {id}/validate
- *
- * @return array
- *
- * @throws RestException 304
- * @throws RestException 401
- * @throws RestException 404
- * @throws RestException 405
- * @throws RestException 500
- */
- public function validate($id, $idwarehouse = 0, $notrigger = 0)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
- throw new RestException(401);
- }
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Invoice not found');
- }
-
- if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
-
- $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
- if ($result == 0) {
- throw new RestException(304, 'Error nothing done. The invoice is already validated');
- }
- if ($result < 0) {
- throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
- }
-
- return array(
- 'success' => array(
- 'code' => 200,
- 'message' => 'Invoice validated (Ref='.$this->invoice->ref.')'
- )
- );
- }
-
- /**
- * Get list of payments of a given supplier invoice
- *
- * @param int $id Id of SupplierInvoice
- *
- * @url GET {id}/payments
- *
- * @return array
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- * @throws RestException 405
- */
- public function getPayments($id)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) {
- throw new RestException(401);
- }
- if (empty($id)) {
- throw new RestException(400, 'Invoice ID is mandatory');
- }
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Supplier invoice not found');
+ }
if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Invoice not found');
- }
+ $this->invoice->fetchObjectLinked();
+ return $this->_cleanObjectDatas($this->invoice);
+ }
- $result = $this->invoice->getListOfPayments();
- if ($result < 0) {
- throw new RestException(405, $this->invoice->error);
- }
+ /**
+ * List invoices
+ *
+ * Get a list of supplier invoices
+ *
+ * @param string $sortfield Sort field
+ * @param string $sortorder Sort order
+ * @param int $limit Limit for list
+ * @param int $page Page number
+ * @param string $thirdparty_ids Thirdparty ids to filter invoices of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
+ * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled
+ * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
+ * @return array Array of invoice objects
+ *
+ * @throws RestException
+ */
+ public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '')
+ {
+ global $db;
- return $result;
- }
+ $obj_ret = array();
+
+ // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
+ $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
+
+ // If the internal user must only see his customers, force searching by him
+ $search_sale = 0;
+ if (!DolibarrApiAccess::$user->rights->societe->client->voir) $search_sale = DolibarrApiAccess::$user->id;
+
+ $sql = "SELECT t.rowid";
+ // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
+ if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user";
+ $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t";
+
+ // We need this table joined to the select in order to filter by sale
+ if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+
+ $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')';
+ if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
+ if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
+ if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
+
+ // Filter by status
+ if ($status == 'draft') {
+ $sql .= " AND t.fk_statut IN (0)";
+ }
+ if ($status == 'unpaid') {
+ $sql .= " AND t.fk_statut IN (1)";
+ }
+ if ($status == 'paid') {
+ $sql .= " AND t.fk_statut IN (2)";
+ }
+ if ($status == 'cancelled') {
+ $sql .= " AND t.fk_statut IN (3)";
+ }
+ // Insert sale filter
+ if ($search_sale > 0) {
+ $sql .= " AND sc.fk_user = ".$search_sale;
+ }
+ // Add sql filters
+ if ($sqlfilters)
+ {
+ if (!DolibarrApi::_checkFilters($sqlfilters))
+ {
+ throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
+ }
+ $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
+ $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
+ }
+
+ $sql .= $db->order($sortfield, $sortorder);
+ if ($limit) {
+ if ($page < 0)
+ {
+ $page = 0;
+ }
+ $offset = $limit * $page;
+
+ $sql .= $db->plimit($limit + 1, $offset);
+ }
+
+ $result = $db->query($sql);
+ if ($result) {
+ $i = 0;
+ $num = $db->num_rows($result);
+ $min = min($num, ($limit <= 0 ? $num : $limit));
+ while ($i < $min)
+ {
+ $obj = $db->fetch_object($result);
+ $invoice_static = new FactureFournisseur($db);
+ if ($invoice_static->fetch($obj->rowid)) {
+ $obj_ret[] = $this->_cleanObjectDatas($invoice_static);
+ }
+ $i++;
+ }
+ } else {
+ throw new RestException(503, 'Error when retrieve supplier invoice list : '.$db->lasterror());
+ }
+ if (!count($obj_ret)) {
+ throw new RestException(404, 'No supplier invoice found');
+ }
+ return $obj_ret;
+ }
+
+ /**
+ * Create supplier invoice object
+ *
+ * @param array $request_data Request datas
+ *
+ * @return int ID of supplier invoice
+ *
+ * @throws RestException 401
+ * @throws RestException 500
+ */
+ public function post($request_data = null)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
+ throw new RestException(401, "Insuffisant rights");
+ }
+ // Check mandatory fields
+ $result = $this->_validate($request_data);
+
+ foreach ($request_data as $field => $value) {
+ $this->invoice->$field = $value;
+ }
+ if (!array_key_exists('date', $request_data)) {
+ $this->invoice->date = dol_now();
+ }
+
+ if ($this->invoice->create(DolibarrApiAccess::$user) < 0) {
+ throw new RestException(500, "Error creating order", array_merge(array($this->invoice->error), $this->invoice->errors));
+ }
+ return $this->invoice->id;
+ }
+
+ /**
+ * Update supplier invoice
+ *
+ * @param int $id Id of supplier invoice to update
+ * @param array $request_data Datas
+ *
+ * @return int
+ *
+ * @throws RestException 401
+ * @throws RestException 404
+ */
+ public function put($id, $request_data = null)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
+ throw new RestException(401);
+ }
+
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Supplier invoice not found');
+ }
+
+ if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+
+ foreach ($request_data as $field => $value) {
+ if ($field == 'id') continue;
+ $this->invoice->$field = $value;
+ }
+
+ if ($this->invoice->update($id, DolibarrApiAccess::$user))
+ return $this->get($id);
+
+ return false;
+ }
+
+ /**
+ * Delete supplier invoice
+ *
+ * @param int $id Supplier invoice ID
+ *
+ * @return array
+ *
+ * @throws RestException 401
+ * @throws RestException 404
+ * @throws RestException 500
+ */
+ public function delete($id)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->supprimer) {
+ throw new RestException(401);
+ }
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Supplier invoice not found');
+ }
+
+ if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+
+ if ($this->invoice->delete(DolibarrApiAccess::$user) < 0)
+ {
+ throw new RestException(500);
+ }
+
+ return array(
+ 'success' => array(
+ 'code' => 200,
+ 'message' => 'Supplier invoice deleted'
+ )
+ );
+ }
+
+ /**
+ * Validate an invoice
+ *
+ * @param int $id Invoice ID
+ * @param int $idwarehouse Warehouse ID
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ *
+ * @url POST {id}/validate
+ *
+ * @return array
+ *
+ * @throws RestException 304
+ * @throws RestException 401
+ * @throws RestException 404
+ * @throws RestException 405
+ * @throws RestException 500
+ */
+ public function validate($id, $idwarehouse = 0, $notrigger = 0)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
+ throw new RestException(401);
+ }
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Invoice not found');
+ }
+
+ if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+
+ $result = $this->invoice->validate(DolibarrApiAccess::$user, '', $idwarehouse, $notrigger);
+ if ($result == 0) {
+ throw new RestException(304, 'Error nothing done. The invoice is already validated');
+ }
+ if ($result < 0) {
+ throw new RestException(500, 'Error when validating Invoice: '.$this->invoice->error);
+ }
+
+ return array(
+ 'success' => array(
+ 'code' => 200,
+ 'message' => 'Invoice validated (Ref='.$this->invoice->ref.')'
+ )
+ );
+ }
+
+ /**
+ * Get list of payments of a given supplier invoice
+ *
+ * @param int $id Id of SupplierInvoice
+ *
+ * @url GET {id}/payments
+ *
+ * @return array
+ * @throws RestException 400
+ * @throws RestException 401
+ * @throws RestException 404
+ * @throws RestException 405
+ */
+ public function getPayments($id)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) {
+ throw new RestException(401);
+ }
+ if (empty($id)) {
+ throw new RestException(400, 'Invoice ID is mandatory');
+ }
+
+ if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Invoice not found');
+ }
+
+ $result = $this->invoice->getListOfPayments();
+ if ($result < 0) {
+ throw new RestException(405, $this->invoice->error);
+ }
+
+ return $result;
+ }
- /**
- * Add payment line to a specific supplier invoice with the remain to pay as amount.
- *
- * @param int $id Id of invoice
- * @param string $datepaye {@from body} Payment date {@type timestamp}
- * @param int $payment_mode_id {@from body} Payment mode ID (look it up via REST GET to /setup/dictionary/payment_types) {@min 1}
- * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no}
- * @param int $accountid {@from body} Bank account ID (look it up via REST GET to /bankaccounts) {@min 1}
- * @param string $num_payment {@from body} Payment number (optional)
- * @param string $comment {@from body} Note (optional)
- * @param string $chqemetteur {@from body} Payment issuer (mandatory if payment_mode_id corresponds to 'CHQ'-payment type)
- * @param string $chqbank {@from body} Issuer bank name (optional)
- *
- * @url POST {id}/payments
- *
- * @return int Payment ID
- * @throws RestException 400
- * @throws RestException 401
- * @throws RestException 404
- */
- public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
- {
- global $conf;
+ /**
+ * Add payment line to a specific supplier invoice with the remain to pay as amount.
+ *
+ * @param int $id Id of invoice
+ * @param string $datepaye {@from body} Payment date {@type timestamp}
+ * @param int $payment_mode_id {@from body} Payment mode ID (look it up via REST GET to /setup/dictionary/payment_types) {@min 1}
+ * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no}
+ * @param int $accountid {@from body} Bank account ID (look it up via REST GET to /bankaccounts) {@min 1}
+ * @param string $num_payment {@from body} Payment number (optional)
+ * @param string $comment {@from body} Note (optional)
+ * @param string $chqemetteur {@from body} Payment issuer (mandatory if payment_mode_id corresponds to 'CHQ'-payment type)
+ * @param string $chqbank {@from body} Issuer bank name (optional)
+ *
+ * @url POST {id}/payments
+ *
+ * @return int Payment ID
+ * @throws RestException 400
+ * @throws RestException 401
+ * @throws RestException 404
+ */
+ public function addPayment($id, $datepaye, $payment_mode_id, $closepaidinvoices, $accountid, $num_payment = '', $comment = '', $chqemetteur = '', $chqbank = '')
+ {
+ global $conf;
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
- throw new RestException(403);
- }
- if (empty($id)) {
- throw new RestException(400, 'Invoice ID is mandatory');
- }
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
+ throw new RestException(403);
+ }
+ if (empty($id)) {
+ throw new RestException(400, 'Invoice ID is mandatory');
+ }
- if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
+ if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
- if (!empty($conf->banque->enabled)) {
- if (empty($accountid)) {
- throw new RestException(400, 'Bank account ID is mandatory');
- }
- }
+ if (!empty($conf->banque->enabled)) {
+ if (empty($accountid)) {
+ throw new RestException(400, 'Bank account ID is mandatory');
+ }
+ }
- if (empty($payment_mode_id)) {
- throw new RestException(400, 'Payment mode ID is mandatory');
- }
+ if (empty($payment_mode_id)) {
+ throw new RestException(400, 'Payment mode ID is mandatory');
+ }
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Invoice not found');
- }
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Invoice not found');
+ }
- // Calculate amount to pay
- $totalpaye = $this->invoice->getSommePaiement();
- $totaldeposits = $this->invoice->getSumDepositsUsed();
- $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totaldeposits, 'MT');
+ // Calculate amount to pay
+ $totalpaye = $this->invoice->getSommePaiement();
+ $totaldeposits = $this->invoice->getSumDepositsUsed();
+ $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totaldeposits, 'MT');
- $this->db->begin();
+ $this->db->begin();
- $amounts = array();
- $multicurrency_amounts = array();
+ $amounts = array();
+ $multicurrency_amounts = array();
- $resteapayer = price2num($resteapayer, 'MT');
- $amounts[$id] = $resteapayer;
+ $resteapayer = price2num($resteapayer, 'MT');
+ $amounts[$id] = $resteapayer;
- // Multicurrency
- $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
- $multicurrency_amounts[$id] = $newvalue;
+ // Multicurrency
+ $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT');
+ $multicurrency_amounts[$id] = $newvalue;
- // Creation of payment line
- $paiement = new PaiementFourn($this->db);
- $paiement->datepaye = $datepaye;
- $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
- $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
- $paiement->paiementid = $payment_mode_id;
- $paiement->paiementcode = dol_getIdFromCode($this->db, $payment_mode_id, 'c_paiement', 'id', 'code', 1);
- $paiement->oper = $paiement->paiementcode; // For backward compatibility
- $paiement->num_payment = $num_payment;
- $paiement->note_public = $comment;
+ // Creation of payment line
+ $paiement = new PaiementFourn($this->db);
+ $paiement->datepaye = $datepaye;
+ $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id
+ $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching
+ $paiement->paiementid = $payment_mode_id;
+ $paiement->paiementcode = dol_getIdFromCode($this->db, $payment_mode_id, 'c_paiement', 'id', 'code', 1);
+ $paiement->oper = $paiement->paiementcode; // For backward compatibility
+ $paiement->num_payment = $num_payment;
+ $paiement->note_public = $comment;
- $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
- if ($paiement_id < 0)
- {
- $this->db->rollback();
- throw new RestException(400, 'Payment error : '.$paiement->error);
- }
+ $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices
+ if ($paiement_id < 0)
+ {
+ $this->db->rollback();
+ throw new RestException(400, 'Payment error : '.$paiement->error);
+ }
- if (!empty($conf->banque->enabled)) {
- $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
- if ($result < 0)
- {
- $this->db->rollback();
- throw new RestException(400, 'Add payment to bank error : '.$paiement->error);
- }
- }
+ if (!empty($conf->banque->enabled)) {
+ $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank);
+ if ($result < 0)
+ {
+ $this->db->rollback();
+ throw new RestException(400, 'Add payment to bank error : '.$paiement->error);
+ }
+ }
- $this->db->commit();
+ $this->db->commit();
- return $paiement_id;
- }
+ return $paiement_id;
+ }
- /**
- * Get lines of a supplier invoice
- *
- * @param int $id Id of supplier invoice
- *
- * @url GET {id}/lines
- *
- * @return array
- */
- public function getLines($id)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
- throw new RestException(401);
- }
+ /**
+ * Get lines of a supplier invoice
+ *
+ * @param int $id Id of supplier invoice
+ *
+ * @url GET {id}/lines
+ *
+ * @return array
+ */
+ public function getLines($id)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
+ throw new RestException(401);
+ }
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Supplier invoice not found');
- }
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Supplier invoice not found');
+ }
- if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $this->invoice->fetch_lines();
- $result = array();
- foreach ($this->invoice->lines as $line) {
- array_push($result, $this->_cleanObjectDatas($line));
- }
- return $result;
- }
+ if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+ $this->invoice->fetch_lines();
+ $result = array();
+ foreach ($this->invoice->lines as $line) {
+ array_push($result, $this->_cleanObjectDatas($line));
+ }
+ return $result;
+ }
- /**
- * Add a line to given supplier invoice
- *
- * @param int $id Id of supplier invoice to update
- * @param array $request_data supplier invoice line data
- *
- * @url POST {id}/lines
- *
- * @return int|bool
- */
- public function postLine($id, $request_data = null)
- {
- if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
- throw new RestException(401);
- }
+ /**
+ * Add a line to given supplier invoice
+ *
+ * @param int $id Id of supplier invoice to update
+ * @param array $request_data supplier invoice line data
+ *
+ * @url POST {id}/lines
+ *
+ * @return int|bool
+ */
+ public function postLine($id, $request_data = null)
+ {
+ if (!DolibarrApiAccess::$user->rights->fournisseur->facture->creer) {
+ throw new RestException(401);
+ }
- $result = $this->invoice->fetch($id);
- if (!$result) {
- throw new RestException(404, 'Supplier invoice not found');
- }
+ $result = $this->invoice->fetch($id);
+ if (!$result) {
+ throw new RestException(404, 'Supplier invoice not found');
+ }
- if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
- throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
- }
- $request_data = (object) $request_data;
+ if (!DolibarrApi::_checkAccessToResource('fournisseur', $this->invoice->id, 'facture_fourn', 'facture')) {
+ throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
+ }
+ $request_data = (object) $request_data;
- $updateRes = $this->invoice->addline(
- $request_data->description,
- $request_data->pu_ht,
+ $updateRes = $this->invoice->addline(
+ $request_data->description,
+ $request_data->pu_ht,
$request_data->tva_tx,
- $request_data->localtax1_tx,
- $request_data->localtax2_tx,
- $request_data->qty,
+ $request_data->localtax1_tx,
+ $request_data->localtax2_tx,
+ $request_data->qty,
$request_data->fk_product,
$request_data->remise_percent,
$request_data->date_start,
diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php
index 863b8b0c86c..a2130b6135e 100644
--- a/htdocs/fourn/class/fournisseur.commande.class.php
+++ b/htdocs/fourn/class/fournisseur.commande.class.php
@@ -3,7 +3,7 @@
* Copyright (C) 2004-2017 Laurent Destailleur
* Copyright (C) 2005-2012 Regis Houssin
* Copyright (C) 2007 Franky Van Liedekerke
- * Copyright (C) 2010-2014 Juanjo Menent
+ * Copyright (C) 2010-2020 Juanjo Menent
* Copyright (C) 2010-2018 Philippe Grand
* Copyright (C) 2012-2015 Marcos GarcÃa
* Copyright (C) 2013 Florian Henry
@@ -393,7 +393,7 @@ class CommandeFournisseur extends CommonOrder
$this->note_private = $obj->note_private;
$this->note_public = $obj->note_public;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf;
+ $this->modelpdf = $obj->model_pdf; // deprecated
//Incoterms
$this->fk_incoterms = $obj->fk_incoterms;
@@ -519,740 +519,740 @@ class CommandeFournisseur extends CommonOrder
}
$line->date_start = $this->db->jdate($objp->date_start);
- $line->date_end = $this->db->jdate($objp->date_end);
- $line->fk_unit = $objp->fk_unit;
+ $line->date_end = $this->db->jdate($objp->date_end);
+ $line->fk_unit = $objp->fk_unit;
- // Multicurrency
- $line->fk_multicurrency = $objp->fk_multicurrency;
- $line->multicurrency_code = $objp->multicurrency_code;
- $line->multicurrency_subprice = $objp->multicurrency_subprice;
- $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
- $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
- $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
+ // Multicurrency
+ $line->fk_multicurrency = $objp->fk_multicurrency;
+ $line->multicurrency_code = $objp->multicurrency_code;
+ $line->multicurrency_subprice = $objp->multicurrency_subprice;
+ $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
+ $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
+ $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
- $line->special_code = $objp->special_code;
- $line->fk_parent_line = $objp->fk_parent_line;
+ $line->special_code = $objp->special_code;
+ $line->fk_parent_line = $objp->fk_parent_line;
- $line->rang = $objp->rang;
+ $line->rang = $objp->rang;
- // Retreive all extrafield
- // fetch optionals attributes and labels
- $line->fetch_optionals();
+ // Retreive all extrafield
+ // fetch optionals attributes and labels
+ $line->fetch_optionals();
- $this->lines[$i] = $line;
+ $this->lines[$i] = $line;
- $i++;
- }
- $this->db->free($result);
+ $i++;
+ }
+ $this->db->free($result);
- return $num;
- } else {
- $this->error = $this->db->error()." sql=".$sql;
- return -1;
- }
- }
+ return $num;
+ } else {
+ $this->error = $this->db->error()." sql=".$sql;
+ return -1;
+ }
+ }
- /**
- * Validate an order
- *
- * @param User $user Validator User
- * @param int $idwarehouse Id of warehouse to use for stock decrease
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int <0 if KO, >0 if OK
- */
- public function valid($user, $idwarehouse = 0, $notrigger = 0)
- {
- global $langs, $conf;
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ /**
+ * Validate an order
+ *
+ * @param User $user Validator User
+ * @param int $idwarehouse Id of warehouse to use for stock decrease
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function valid($user, $idwarehouse = 0, $notrigger = 0)
+ {
+ global $langs, $conf;
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- $error = 0;
+ $error = 0;
- dol_syslog(get_class($this)."::valid");
- $result = 0;
- if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->commande->creer))
- || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate)))
- {
- $this->db->begin();
+ dol_syslog(get_class($this)."::valid");
+ $result = 0;
+ if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->commande->creer))
+ || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate)))
+ {
+ $this->db->begin();
- // Definition of supplier order numbering model name
- $soc = new Societe($this->db);
- $soc->fetch($this->fourn_id);
+ // Definition of supplier order numbering model name
+ $soc = new Societe($this->db);
+ $soc->fetch($this->fourn_id);
- // Check if object has a temporary ref
- if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
- {
- $num = $this->getNextNumRef($soc);
- } else {
- $num = $this->ref;
- }
- $this->newref = dol_sanitizeFileName($num);
+ // Check if object has a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
+ {
+ $num = $this->getNextNumRef($soc);
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = dol_sanitizeFileName($num);
- $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur";
- $sql .= " SET ref='".$this->db->escape($num)."',";
- $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
- $sql .= " date_valid='".$this->db->idate(dol_now())."',";
- $sql .= " fk_user_valid = ".$user->id;
- $sql .= " WHERE rowid = ".$this->id;
- $sql .= " AND fk_statut = ".self::STATUS_DRAFT;
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur";
+ $sql .= " SET ref='".$this->db->escape($num)."',";
+ $sql .= " fk_statut = ".self::STATUS_VALIDATED.",";
+ $sql .= " date_valid='".$this->db->idate(dol_now())."',";
+ $sql .= " fk_user_valid = ".$user->id;
+ $sql .= " WHERE rowid = ".$this->id;
+ $sql .= " AND fk_statut = ".self::STATUS_DRAFT;
- $resql = $this->db->query($sql);
- if (!$resql)
- {
- dol_print_error($this->db);
- $error++;
- }
+ $resql = $this->db->query($sql);
+ if (!$resql)
+ {
+ dol_print_error($this->db);
+ $error++;
+ }
- if (!$error && !$notrigger)
- {
+ if (!$error && !$notrigger)
+ {
// Call trigger
$result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user);
if ($result < 0) $error++;
// End call triggers
- }
+ }
- if (!$error)
- {
- $this->oldref = $this->ref;
+ 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 = 'fournisseur/commande/".$this->db->escape($this->newref)."'";
- $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
- $resql = $this->db->query($sql);
- if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
+ // 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 = 'fournisseur/commande/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$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->fournisseur->commande->dir_output.'/'.$oldref;
- $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref;
- if (!$error && file_exists($dirsource))
- {
- dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
+ // 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->fournisseur->commande->dir_output.'/'.$oldref;
+ $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref;
+ if (!$error && file_exists($dirsource))
+ {
+ dol_syslog(get_class($this)."::valid 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->fournisseur->commande->dir_output.'/'.$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);
- }
- }
- }
- }
- }
+ if (@rename($dirsource, $dirdest))
+ {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$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);
+ }
+ }
+ }
+ }
+ }
- if (!$error)
- {
- $result = 1;
- $this->statut = self::STATUS_VALIDATED;
- $this->ref = $num;
- }
+ if (!$error)
+ {
+ $result = 1;
+ $this->statut = self::STATUS_VALIDATED;
+ $this->ref = $num;
+ }
- if (!$error)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->error = 'NotAuthorized';
- dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
- return -1;
- }
- }
-
- /**
- * Return label of the status of object
- *
- * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto
- * @return string Label
- */
- public function getLibStatut($mode = 0)
- {
- return $this->LibStatut($this->statut, $mode, $this->billed);
- }
-
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Return label of a status
- *
- * @param int $status Id statut
- * @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
- * @param int $billed 1=Billed
- * @return string Label of status
- */
- public function LibStatut($status, $mode = 0, $billed = 0)
- {
- // phpcs:enable
- global $conf, $langs;
-
- if (empty($this->statuts) || empty($this->statutshort)) {
- $langs->load('orders');
-
- $this->statuts[0] = 'StatusSupplierOrderDraft';
- $this->statuts[1] = 'StatusSupplierOrderValidated';
- $this->statuts[2] = 'StatusSupplierOrderApproved';
- if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusSupplierOrderOnProcess';
- else $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation';
- $this->statuts[4] = 'StatusSupplierOrderReceivedPartially';
- $this->statuts[5] = 'StatusSupplierOrderReceivedAll';
- $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled
- $this->statuts[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled
- $this->statuts[9] = 'StatusSupplierOrderRefused';
-
- // List of language codes for status
- $this->statutshort[0] = 'StatusSupplierOrderDraftShort';
- $this->statutshort[1] = 'StatusSupplierOrderValidatedShort';
- $this->statutshort[2] = 'StatusSupplierOrderApprovedShort';
- $this->statutshort[3] = 'StatusSupplierOrderOnProcessShort';
- $this->statutshort[4] = 'StatusSupplierOrderReceivedPartiallyShort';
- $this->statutshort[5] = 'StatusSupplierOrderReceivedAllShort';
- $this->statutshort[6] = 'StatusSupplierOrderCanceledShort';
- $this->statutshort[7] = 'StatusSupplierOrderCanceledShort';
- $this->statutshort[9] = 'StatusSupplierOrderRefusedShort';
- }
-
- $statustrans = array(
- 0 => 'status0',
- 1 => 'status1b',
- 2 => 'status1',
- 3 => 'status4',
- 4 => 'status4b',
- 5 => 'status6',
- 6 => 'status9',
- 7 => 'status9',
- 9 => 'status9',
- );
-
- $statusClass = 'status0';
- if (!empty($statustrans[$status])) {
- $statusClass = $statustrans[$status];
- }
-
- $billedtext = '';
- if ($billed) {
- $billedtext = ' - '.$langs->trans("Billed");
- }
- if ($status == 5 && $billed) $statusClass = 'status6';
-
- $statusLong = $langs->trans($this->statuts[$status]).$billedtext;
- $statusShort = $langs->trans($this->statutshort[$status]);
-
- return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode);
- }
-
-
- /**
- * Return clicable name (with picto eventually)
- *
- * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
- * @param string $option On what the link points
- * @param int $notooltip 1=Disable tooltip
- * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
- * @param int $addlinktonotes Add link to show notes
- * @return string Chain with URL
- */
- public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
- {
- global $langs, $conf, $user;
-
- $result = '';
- $label = ''.$langs->trans("PurchaseOrder").' ';
- if (!empty($this->ref))
- $label .= ''.$langs->trans('Ref').': '.$this->ref;
- if (!empty($this->ref_supplier))
- $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_supplier;
- if (!empty($this->total_ht))
- $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_tva))
- $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_ttc))
- $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
-
- $picto = 'order';
- $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
-
- if ($option !== 'nolink')
- {
- // Add param to save lastsearch_values or not
- $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
- if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
- if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
- }
-
- $linkclose = '';
- if (empty($notooltip))
- {
- if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
- {
- $label = $langs->trans("ShowOrder");
- $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
- }
- $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
- $linkclose .= ' class="classfortooltip"';
- }
-
- $linkstart = '';
- $linkend = ' ';
-
- $result .= $linkstart;
- if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
- if ($withpicto != 2) $result .= $this->ref;
- $result .= $linkend;
-
- if ($addlinktonotes)
- {
- $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
- if ($txttoshow)
- {
- $notetoshow = $langs->trans("ViewPrivateNote").': '.dol_string_nohtmltag($txttoshow, 1);
- $result .= ' ';
- $result .= '';
- $result .= img_picto('', 'note');
- $result .= ' ';
- //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
- //$result.='';
- $result .= ' ';
- }
- }
-
- return $result;
- }
-
-
- /**
- * Returns the following order reference not used depending on the numbering model activated
- * defined within COMMANDE_SUPPLIER_ADDON_NUMBER
- *
- * @param Societe $soc company object
- * @return string free reference for the invoice
- */
- public function getNextNumRef($soc)
- {
- global $db, $langs, $conf;
- $langs->load("orders");
-
- if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
- {
- $mybool = false;
-
- $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
- $classname = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
-
- // Include file with class
- $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
-
- foreach ($dirmodels as $reldir) {
- $dir = dol_buildpath($reldir."core/modules/supplier_order/");
-
- // Load file with numbering class (if found)
- $mybool |= @include_once $dir.$file;
- }
-
- if ($mybool === false) {
- dol_print_error('', "Failed to include file ".$file);
- return '';
- }
-
- $obj = new $classname();
- $numref = $obj->getNextValue($soc, $this);
-
- if ($numref != "")
- {
- return $numref;
- } else {
- $this->error = $obj->error;
- return -1;
- }
- } else {
- $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
- return -2;
- }
- }
- /**
- * Class invoiced the supplier order
- *
- * @param User $user Object user making the change
- * @return int <0 if KO, >0 if KO
- */
- public function classifyBilled(User $user)
- {
- $error = 0;
- $this->db->begin();
-
- $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1';
- $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
-
- if ($this->db->query($sql))
- {
- if (!$error)
- {
- // Call trigger
- $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
-
- if (!$error)
- {
- $this->billed = 1;
-
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- dol_print_error($this->db);
-
- $this->db->rollback();
+ if (!$error)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->error = 'NotAuthorized';
+ dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
return -1;
- }
- }
+ }
+ }
- /**
- * Approve a supplier order
- *
- * @param User $user Object user
- * @param int $idwarehouse Id of warhouse for stock change
- * @param int $secondlevel 0=Standard approval, 1=Second level approval (used when option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set)
- * @return int <0 if KO, >0 if OK
- */
- public function approve($user, $idwarehouse = 0, $secondlevel = 0)
- {
- global $langs, $conf;
+ /**
+ * Return label of the status of object
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto
+ * @return string Label
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut($this->statut, $mode, $this->billed);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return label of a status
+ *
+ * @param int $status Id statut
+ * @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
+ * @param int $billed 1=Billed
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode = 0, $billed = 0)
+ {
+ // phpcs:enable
+ global $conf, $langs;
+
+ if (empty($this->statuts) || empty($this->statutshort)) {
+ $langs->load('orders');
+
+ $this->statuts[0] = 'StatusSupplierOrderDraft';
+ $this->statuts[1] = 'StatusSupplierOrderValidated';
+ $this->statuts[2] = 'StatusSupplierOrderApproved';
+ if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusSupplierOrderOnProcess';
+ else $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation';
+ $this->statuts[4] = 'StatusSupplierOrderReceivedPartially';
+ $this->statuts[5] = 'StatusSupplierOrderReceivedAll';
+ $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled
+ $this->statuts[7] = 'StatusSupplierOrderCanceled'; // Process running->canceled
+ $this->statuts[9] = 'StatusSupplierOrderRefused';
+
+ // List of language codes for status
+ $this->statutshort[0] = 'StatusSupplierOrderDraftShort';
+ $this->statutshort[1] = 'StatusSupplierOrderValidatedShort';
+ $this->statutshort[2] = 'StatusSupplierOrderApprovedShort';
+ $this->statutshort[3] = 'StatusSupplierOrderOnProcessShort';
+ $this->statutshort[4] = 'StatusSupplierOrderReceivedPartiallyShort';
+ $this->statutshort[5] = 'StatusSupplierOrderReceivedAllShort';
+ $this->statutshort[6] = 'StatusSupplierOrderCanceledShort';
+ $this->statutshort[7] = 'StatusSupplierOrderCanceledShort';
+ $this->statutshort[9] = 'StatusSupplierOrderRefusedShort';
+ }
+
+ $statustrans = array(
+ 0 => 'status0',
+ 1 => 'status1b',
+ 2 => 'status1',
+ 3 => 'status4',
+ 4 => 'status4b',
+ 5 => 'status6',
+ 6 => 'status9',
+ 7 => 'status9',
+ 9 => 'status9',
+ );
+
+ $statusClass = 'status0';
+ if (!empty($statustrans[$status])) {
+ $statusClass = $statustrans[$status];
+ }
+
+ $billedtext = '';
+ if ($billed) {
+ $billedtext = ' - '.$langs->trans("Billed");
+ }
+ if ($status == 5 && $billed) $statusClass = 'status6';
+
+ $statusLong = $langs->trans($this->statuts[$status]).$billedtext;
+ $statusShort = $langs->trans($this->statutshort[$status]);
+
+ return dolGetStatus($statusLong, $statusShort, '', $statusClass, $mode);
+ }
+
+
+ /**
+ * Return clicable name (with picto eventually)
+ *
+ * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
+ * @param string $option On what the link points
+ * @param int $notooltip 1=Disable tooltip
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @param int $addlinktonotes Add link to show notes
+ * @return string Chain with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
+ {
+ global $langs, $conf, $user;
+
+ $result = '';
+ $label = ''.$langs->trans("PurchaseOrder").' ';
+ if (!empty($this->ref))
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+ if (!empty($this->ref_supplier))
+ $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_supplier;
+ if (!empty($this->total_ht))
+ $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_tva))
+ $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_ttc))
+ $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
+
+ $picto = 'order';
+ $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id;
+
+ if ($option !== 'nolink')
+ {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
+ if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+ }
+
+ $linkclose = '';
+ if (empty($notooltip))
+ {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+ {
+ $label = $langs->trans("ShowOrder");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip"';
+ }
+
+ $linkstart = '';
+ $linkend = ' ';
+
+ $result .= $linkstart;
+ if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ if ($withpicto != 2) $result .= $this->ref;
+ $result .= $linkend;
+
+ if ($addlinktonotes)
+ {
+ $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
+ if ($txttoshow)
+ {
+ $notetoshow = $langs->trans("ViewPrivateNote").': '.dol_string_nohtmltag($txttoshow, 1);
+ $result .= ' ';
+ $result .= '';
+ $result .= img_picto('', 'note');
+ $result .= ' ';
+ //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
+ //$result.='';
+ $result .= ' ';
+ }
+ }
+
+ return $result;
+ }
+
+
+ /**
+ * Returns the following order reference not used depending on the numbering model activated
+ * defined within COMMANDE_SUPPLIER_ADDON_NUMBER
+ *
+ * @param Societe $soc company object
+ * @return string free reference for the invoice
+ */
+ public function getNextNumRef($soc)
+ {
+ global $db, $langs, $conf;
+ $langs->load("orders");
+
+ if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER))
+ {
+ $mybool = false;
+
+ $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php';
+ $classname = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER;
+
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/supplier_order/");
+
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
+
+ if ($mybool === false) {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
+
+ $obj = new $classname();
+ $numref = $obj->getNextValue($soc, $this);
+
+ if ($numref != "")
+ {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ return -1;
+ }
+ } else {
+ $this->error = "Error_COMMANDE_SUPPLIER_ADDON_NotDefined";
+ return -2;
+ }
+ }
+ /**
+ * Class invoiced the supplier order
+ *
+ * @param User $user Object user making the change
+ * @return int <0 if KO, >0 if KO
+ */
+ public function classifyBilled(User $user)
+ {
+ $error = 0;
+ $this->db->begin();
+
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1';
+ $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT;
+
+ if ($this->db->query($sql))
+ {
+ if (!$error)
+ {
+ // Call trigger
+ $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+
+ if (!$error)
+ {
+ $this->billed = 1;
+
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ dol_print_error($this->db);
+
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Approve a supplier order
+ *
+ * @param User $user Object user
+ * @param int $idwarehouse Id of warhouse for stock change
+ * @param int $secondlevel 0=Standard approval, 1=Second level approval (used when option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set)
+ * @return int <0 if KO, >0 if OK
+ */
+ public function approve($user, $idwarehouse = 0, $secondlevel = 0)
+ {
+ global $langs, $conf;
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- $error = 0;
+ $error = 0;
- dol_syslog(get_class($this)."::approve");
+ dol_syslog(get_class($this)."::approve");
- if ($user->rights->fournisseur->commande->approuver)
- {
- $now = dol_now();
+ if ($user->rights->fournisseur->commande->approuver)
+ {
+ $now = dol_now();
- $this->db->begin();
+ $this->db->begin();
// Definition of order numbering model name
- $soc = new Societe($this->db);
- $soc->fetch($this->fourn_id);
+ $soc = new Societe($this->db);
+ $soc->fetch($this->fourn_id);
- // Check if object has a temporary ref
- if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
- {
- $num = $this->getNextNumRef($soc);
- } else {
- $num = $this->ref;
- }
- $this->newref = dol_sanitizeFileName($num);
+ // Check if object has a temporary ref
+ if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
+ {
+ $num = $this->getNextNumRef($soc);
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = dol_sanitizeFileName($num);
- // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
+ // Do we have to change status now ? (If double approval is required and first approval, we keep status to 1 = validated)
$movetoapprovestatus = true;
$comment = '';
- $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
+ $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
$sql .= " SET ref='".$this->db->escape($num)."',";
if (empty($secondlevel)) // standard or first level approval
{
- $sql .= " date_approve='".$this->db->idate($now)."',";
- $sql .= " fk_user_approve = ".$user->id;
- if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
- {
- if (empty($this->user_approve_id2))
- {
- $movetoapprovestatus = false; // second level approval not done
- $comment = ' (first level)';
- }
- }
+ $sql .= " date_approve='".$this->db->idate($now)."',";
+ $sql .= " fk_user_approve = ".$user->id;
+ if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
+ {
+ if (empty($this->user_approve_id2))
+ {
+ $movetoapprovestatus = false; // second level approval not done
+ $comment = ' (first level)';
+ }
+ }
} else // request a second level approval
{
- $sql .= " date_approve2='".$this->db->idate($now)."',";
- $sql .= " fk_user_approve2 = ".$user->id;
- if (empty($this->user_approve_id)) $movetoapprovestatus = false; // first level approval not done
- $comment = ' (second level)';
+ $sql .= " date_approve2='".$this->db->idate($now)."',";
+ $sql .= " fk_user_approve2 = ".$user->id;
+ if (empty($this->user_approve_id)) $movetoapprovestatus = false; // first level approval not done
+ $comment = ' (second level)';
}
// If double approval is required and first approval, we keep status to 1 = validated
if ($movetoapprovestatus) $sql .= ", fk_statut = ".self::STATUS_ACCEPTED;
else $sql .= ", fk_statut = ".self::STATUS_VALIDATED;
- $sql .= " WHERE rowid = ".$this->id;
- $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
+ $sql .= " WHERE rowid = ".$this->id;
+ $sql .= " AND fk_statut = ".self::STATUS_VALIDATED;
- if ($this->db->query($sql))
- {
- if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
- {
+ if ($this->db->query($sql))
+ {
+ if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT))
+ {
$result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1);
if ($result < 0 && $result != -2) // -2 means already exists
{
$error++;
}
- }
+ }
- // If stock is incremented on validate order, we must increment it
- if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER))
- {
- require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
- $langs->load("agenda");
+ // If stock is incremented on validate order, we must increment it
+ if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER))
+ {
+ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
+ $langs->load("agenda");
- $cpt = count($this->lines);
- for ($i = 0; $i < $cpt; $i++)
- {
- // Product with reference
- if ($this->lines[$i]->fk_product > 0)
- {
- $this->line = $this->lines[$i];
- $mouvP = new MouvementStock($this->db);
- $mouvP->origin = &$this;
- // We decrement stock of product (and sub-products)
- $up_ht_disc = $this->lines[$i]->subprice;
- if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
- $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref));
- if ($result < 0) { $error++; }
- unset($this->line);
- }
- }
- }
+ $cpt = count($this->lines);
+ for ($i = 0; $i < $cpt; $i++)
+ {
+ // Product with reference
+ if ($this->lines[$i]->fk_product > 0)
+ {
+ $this->line = $this->lines[$i];
+ $mouvP = new MouvementStock($this->db);
+ $mouvP->origin = &$this;
+ // We decrement stock of product (and sub-products)
+ $up_ht_disc = $this->lines[$i]->subprice;
+ if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
+ $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref));
+ if ($result < 0) { $error++; }
+ unset($this->line);
+ }
+ }
+ }
- if (!$error)
- {
+ if (!$error)
+ {
// Call trigger
$result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user);
if ($result < 0) $error++;
// End call triggers
- }
+ }
- if (!$error)
- {
- $this->ref = $this->newref;
+ if (!$error)
+ {
+ $this->ref = $this->newref;
- if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED;
+ if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED;
else $this->statut = self::STATUS_VALIDATED;
- if (empty($secondlevel)) // standard or first level approval
+ if (empty($secondlevel)) // standard or first level approval
{
- $this->date_approve = $now;
- $this->user_approve_id = $user->id;
+ $this->date_approve = $now;
+ $this->user_approve_id = $user->id;
} else // request a second level approval
{
- $this->date_approve2 = $now;
- $this->user_approve_id2 = $user->id;
+ $this->date_approve2 = $now;
+ $this->user_approve_id2 = $user->id;
}
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->db->rollback();
- $this->error = $this->db->lasterror();
- return -1;
- }
- } else {
- dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
- }
- return -1;
- }
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->db->rollback();
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::approve Not Authorized", LOG_ERR);
+ }
+ return -1;
+ }
- /**
- * Refuse an order
- *
- * @param User $user User making action
- * @return int 0 if Ok, <0 if Ko
- */
- public function refuse($user)
- {
- global $conf, $langs;
+ /**
+ * Refuse an order
+ *
+ * @param User $user User making action
+ * @return int 0 if Ok, <0 if Ko
+ */
+ public function refuse($user)
+ {
+ global $conf, $langs;
$error = 0;
- dol_syslog(get_class($this)."::refuse");
- $result = 0;
- if ($user->rights->fournisseur->commande->approuver)
- {
- $this->db->begin();
+ dol_syslog(get_class($this)."::refuse");
+ $result = 0;
+ if ($user->rights->fournisseur->commande->approuver)
+ {
+ $this->db->begin();
- $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED;
- $sql .= " WHERE rowid = ".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED;
+ $sql .= " WHERE rowid = ".$this->id;
- if ($this->db->query($sql))
- {
- $result = 0;
+ if ($this->db->query($sql))
+ {
+ $result = 0;
- if ($error == 0)
- {
+ if ($error == 0)
+ {
// Call trigger
$result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user);
if ($result < 0)
- {
- $error++;
- $this->db->rollback();
- } else $this->db->commit();
+ {
+ $error++;
+ $this->db->rollback();
+ } else $this->db->commit();
// End call triggers
- }
- } else {
- $this->db->rollback();
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::refuse Error -1");
- $result = -1;
- }
- } else {
- dol_syslog(get_class($this)."::refuse Not Authorized");
- }
- return $result;
- }
+ }
+ } else {
+ $this->db->rollback();
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::refuse Error -1");
+ $result = -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::refuse Not Authorized");
+ }
+ return $result;
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Cancel an approved order.
- * The cancellation is done after approval
- *
- * @param User $user User making action
- * @param int $idwarehouse Id warehouse to use for stock change (not used for supplier orders).
- * @return int >0 if Ok, <0 if Ko
- */
- public function Cancel($user, $idwarehouse = -1)
- {
- // phpcs:enable
- global $langs, $conf;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Cancel an approved order.
+ * The cancellation is done after approval
+ *
+ * @param User $user User making action
+ * @param int $idwarehouse Id warehouse to use for stock change (not used for supplier orders).
+ * @return int >0 if Ok, <0 if Ko
+ */
+ public function Cancel($user, $idwarehouse = -1)
+ {
+ // phpcs:enable
+ global $langs, $conf;
- $error = 0;
+ $error = 0;
- //dol_syslog("CommandeFournisseur::Cancel");
- $result = 0;
- if ($user->rights->fournisseur->commande->commander)
- {
- $statut = self::STATUS_CANCELED;
+ //dol_syslog("CommandeFournisseur::Cancel");
+ $result = 0;
+ if ($user->rights->fournisseur->commande->commander)
+ {
+ $statut = self::STATUS_CANCELED;
- $this->db->begin();
+ $this->db->begin();
- $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut;
- $sql .= " WHERE rowid = ".$this->id;
- dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
- if ($this->db->query($sql))
- {
- $result = 0;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut;
+ $sql .= " WHERE rowid = ".$this->id;
+ dol_syslog(get_class($this)."::cancel", LOG_DEBUG);
+ if ($this->db->query($sql))
+ {
+ $result = 0;
// Call trigger
$result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user);
if ($result < 0) $error++;
// End call triggers
- if ($error == 0)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->db->rollback();
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::cancel ".$this->error);
- return -1;
- }
- } else {
- dol_syslog(get_class($this)."::cancel Not Authorized");
- return -1;
- }
- }
+ if ($error == 0)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->db->rollback();
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::cancel ".$this->error);
+ return -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::cancel Not Authorized");
+ return -1;
+ }
+ }
- /**
- * Submit a supplier order to supplier
- *
- * @param User $user User making change
- * @param integer $date Date
- * @param int $methode Method
- * @param string $comment Comment
- * @return int <0 if KO, >0 if OK
- */
- public function commande($user, $date, $methode, $comment = '')
- {
- global $langs;
- dol_syslog(get_class($this)."::commande");
- $error = 0;
- if ($user->rights->fournisseur->commande->commander)
- {
- $this->db->begin();
+ /**
+ * Submit a supplier order to supplier
+ *
+ * @param User $user User making change
+ * @param integer $date Date
+ * @param int $methode Method
+ * @param string $comment Comment
+ * @return int <0 if KO, >0 if OK
+ */
+ public function commande($user, $date, $methode, $comment = '')
+ {
+ global $langs;
+ dol_syslog(get_class($this)."::commande");
+ $error = 0;
+ if ($user->rights->fournisseur->commande->commander)
+ {
+ $this->db->begin();
- $newnoteprivate = $this->note_private;
- if ($comment) $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment);
+ $newnoteprivate = $this->note_private;
+ if ($comment) $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment);
- $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
- $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."', ";
- $sql .= " note_private='".$this->db->escape($newnoteprivate)."'";
- $sql .= " WHERE rowid=".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
+ $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."', ";
+ $sql .= " note_private='".$this->db->escape($newnoteprivate)."'";
+ $sql .= " WHERE rowid=".$this->id;
- dol_syslog(get_class($this)."::commande", LOG_DEBUG);
- if ($this->db->query($sql))
- {
- $this->statut = self::STATUS_ORDERSENT;
- $this->methode_commande_id = $methode;
- $this->date_commande = $date;
- $this->context = array('comments' => $comment);
+ dol_syslog(get_class($this)."::commande", LOG_DEBUG);
+ if ($this->db->query($sql))
+ {
+ $this->statut = self::STATUS_ORDERSENT;
+ $this->methode_commande_id = $methode;
+ $this->date_commande = $date;
+ $this->context = array('comments' => $comment);
- // Call trigger
- $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user);
- if ($result < 0) $error++;
- // End call triggers
- } else {
- $error++;
- $this->error = $this->db->lasterror();
- $this->errors[] = $this->db->lasterror();
- }
+ // Call trigger
+ $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ } else {
+ $error++;
+ $this->error = $this->db->lasterror();
+ $this->errors[] = $this->db->lasterror();
+ }
- if (!$error)
- {
- $this->db->commit();
- } else {
- $this->db->rollback();
- }
- } else {
- $error++;
- $this->error = $langs->trans('NotAuthorized');
- $this->errors[] = $langs->trans('NotAuthorized');
- dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ } else {
+ $this->db->rollback();
+ }
+ } else {
+ $error++;
+ $this->error = $langs->trans('NotAuthorized');
+ $this->errors[] = $langs->trans('NotAuthorized');
+ dol_syslog(get_class($this)."::commande User not Authorized", LOG_WARNING);
+ }
- return ($error ? -1 : 1);
- }
+ return ($error ? -1 : 1);
+ }
- /**
- * Create order with draft status
- *
- * @param User $user User making creation
- * @param int $notrigger Disable all triggers
- * @return int <0 if KO, Id of supplier order if OK
- */
- public function create($user, $notrigger = 0)
- {
- global $langs, $conf, $hookmanager;
+ /**
+ * Create order with draft status
+ *
+ * @param User $user User making creation
+ * @param int $notrigger Disable all triggers
+ * @return int <0 if KO, Id of supplier order if OK
+ */
+ public function create($user, $notrigger = 0)
+ {
+ global $langs, $conf, $hookmanager;
- $this->db->begin();
+ $this->db->begin();
$error = 0;
- $now = dol_now();
+ $now = dol_now();
// $date_commande is deprecated
$date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set
if (empty($date)) $date = $now;
- // Clean parameters
- if (empty($this->source)) $this->source = 0;
+ // Clean parameters
+ if (empty($this->source)) $this->source = 0;
// Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date);
@@ -1264,104 +1264,104 @@ class CommandeFournisseur extends CommonOrder
$this->multicurrency_tx = 1;
}
- // We set order into draft status
- $this->brouillon = 1;
+ // We set order into draft status
+ $this->brouillon = 1;
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
- $sql .= "ref";
- $sql .= ", ref_supplier";
- $sql .= ", note_private";
- $sql .= ", note_public";
- $sql .= ", entity";
- $sql .= ", fk_soc";
- $sql .= ", fk_projet";
- $sql .= ", date_creation";
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur (";
+ $sql .= "ref";
+ $sql .= ", ref_supplier";
+ $sql .= ", note_private";
+ $sql .= ", note_public";
+ $sql .= ", entity";
+ $sql .= ", fk_soc";
+ $sql .= ", fk_projet";
+ $sql .= ", date_creation";
$sql .= ", date_livraison";
- $sql .= ", fk_user_author";
- $sql .= ", fk_statut";
- $sql .= ", source";
- $sql .= ", model_pdf";
- $sql .= ", fk_mode_reglement";
+ $sql .= ", fk_user_author";
+ $sql .= ", fk_statut";
+ $sql .= ", source";
+ $sql .= ", model_pdf";
+ $sql .= ", fk_mode_reglement";
$sql .= ", fk_cond_reglement";
- $sql .= ", fk_account";
+ $sql .= ", fk_account";
$sql .= ", fk_incoterms, location_incoterms";
- $sql .= ", fk_multicurrency";
- $sql .= ", multicurrency_code";
- $sql .= ", multicurrency_tx";
- $sql .= ") ";
- $sql .= " VALUES (";
- $sql .= "''";
- $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
- $sql .= ", '".$this->db->escape($this->note_private)."'";
- $sql .= ", '".$this->db->escape($this->note_public)."'";
- $sql .= ", ".$conf->entity;
- $sql .= ", ".$this->socid;
- $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
- $sql .= ", '".$this->db->idate($now)."'";
+ $sql .= ", fk_multicurrency";
+ $sql .= ", multicurrency_code";
+ $sql .= ", multicurrency_tx";
+ $sql .= ") ";
+ $sql .= " VALUES (";
+ $sql .= "''";
+ $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
+ $sql .= ", '".$this->db->escape($this->note_private)."'";
+ $sql .= ", '".$this->db->escape($this->note_public)."'";
+ $sql .= ", ".$conf->entity;
+ $sql .= ", ".$this->socid;
+ $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
+ $sql .= ", '".$this->db->idate($now)."'";
$sql .= ", ".($this->date_livraison ? "'".$this->db->idate($this->date_livraison)."'" : "null");
- $sql .= ", ".$user->id;
- $sql .= ", ".self::STATUS_DRAFT;
- $sql .= ", ".$this->db->escape($this->source);
- $sql .= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'";
- $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
- $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
- $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
- $sql .= ", ".(int) $this->fk_incoterms;
- $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
+ $sql .= ", ".$user->id;
+ $sql .= ", ".self::STATUS_DRAFT;
+ $sql .= ", ".$this->db->escape($this->source);
+ $sql .= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'";
+ $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null');
+ $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null');
+ $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
+ $sql .= ", ".(int) $this->fk_incoterms;
+ $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
$sql .= ", ".(int) $this->fk_multicurrency;
$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
$sql .= ", ".(double) $this->multicurrency_tx;
- $sql .= ")";
+ $sql .= ")";
- dol_syslog(get_class($this)."::create", LOG_DEBUG);
- if ($this->db->query($sql))
- {
- $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur");
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ if ($this->db->query($sql))
+ {
+ $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur");
if ($this->id) {
$num = count($this->lines);
- // insert products details into database
- for ($i = 0; $i < $num; $i++)
- {
- $this->special_code = $this->lines[$i]->special_code; // TODO : remove this in 9.0 and add special_code param to addline()
+ // insert products details into database
+ for ($i = 0; $i < $num; $i++)
+ {
+ $this->special_code = $this->lines[$i]->special_code; // TODO : remove this in 9.0 and add special_code param to addline()
- // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
- $result = $this->addline(
- $this->lines[$i]->desc,
- $this->lines[$i]->subprice,
- $this->lines[$i]->qty,
- $this->lines[$i]->tva_tx,
- $this->lines[$i]->localtax1_tx,
- $this->lines[$i]->localtax2_tx,
- $this->lines[$i]->fk_product,
- 0,
- $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
- $this->lines[$i]->remise_percent,
- 'HT',
- 0,
- $this->lines[$i]->product_type,
- $this->lines[$i]->info_bits,
- false,
- $this->lines[$i]->date_start,
- $this->lines[$i]->date_end,
- $this->lines[$i]->array_options,
- $this->lines[$i]->fk_unit
- );
- if ($result < 0)
- {
- dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functionnal error
- $this->db->rollback();
- return -1;
- }
- }
+ // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set
+ $result = $this->addline(
+ $this->lines[$i]->desc,
+ $this->lines[$i]->subprice,
+ $this->lines[$i]->qty,
+ $this->lines[$i]->tva_tx,
+ $this->lines[$i]->localtax1_tx,
+ $this->lines[$i]->localtax2_tx,
+ $this->lines[$i]->fk_product,
+ 0,
+ $this->lines[$i]->ref_fourn, // $this->lines[$i]->ref_fourn comes from field ref into table of lines. Value may ba a ref that does not exists anymore, so we first try with value of product
+ $this->lines[$i]->remise_percent,
+ 'HT',
+ 0,
+ $this->lines[$i]->product_type,
+ $this->lines[$i]->info_bits,
+ false,
+ $this->lines[$i]->date_start,
+ $this->lines[$i]->date_end,
+ $this->lines[$i]->array_options,
+ $this->lines[$i]->fk_unit
+ );
+ if ($result < 0)
+ {
+ dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functionnal error
+ $this->db->rollback();
+ return -1;
+ }
+ }
- $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
- $sql .= " SET ref='(PROV".$this->id.")'";
- $sql .= " WHERE rowid=".$this->id;
- dol_syslog(get_class($this)."::create", LOG_DEBUG);
- if ($this->db->query($sql))
- {
+ $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur";
+ $sql .= " SET ref='(PROV".$this->id.")'";
+ $sql .= " WHERE rowid=".$this->id;
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ if ($this->db->query($sql))
+ {
// Add link with price request and supplier order
if ($this->id)
{
@@ -1377,82 +1377,82 @@ class CommandeFournisseur extends CommonOrder
{
foreach ($this->linked_objects as $origin => $tmp_origin_id)
{
- if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
- {
- foreach ($tmp_origin_id as $origin_id)
- {
- $ret = $this->add_object_linked($origin, $origin_id);
- if (!$ret)
- {
- dol_print_error($this->db);
- $error++;
- }
- }
- } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
- {
- $origin_id = $tmp_origin_id;
+ if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
+ {
+ foreach ($tmp_origin_id as $origin_id)
+ {
+ $ret = $this->add_object_linked($origin, $origin_id);
+ if (!$ret)
+ {
+ dol_print_error($this->db);
+ $error++;
+ }
+ }
+ } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
+ {
+ $origin_id = $tmp_origin_id;
$ret = $this->add_object_linked($origin, $origin_id);
if (!$ret)
{
dol_print_error($this->db);
$error++;
}
- }
+ }
}
}
}
- if (!$error)
- {
- $result = $this->insertExtraFields();
- if ($result < 0) $error++;
- }
+ if (!$error)
+ {
+ $result = $this->insertExtraFields();
+ if ($result < 0) $error++;
+ }
if (!$error && !$notrigger)
- {
+ {
// Call trigger
$result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user);
if ($result < 0)
- {
- $this->db->rollback();
- return -1;
- }
+ {
+ $this->db->rollback();
+ return -1;
+ }
// End call triggers
- }
+ }
- $this->db->commit();
- return $this->id;
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -2;
- }
- }
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -1;
- }
- }
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -2;
+ }
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Load an object from its id and create a new one in database
- *
+ /**
+ * Load an object from its id and create a new one in database
+ *
* @param User $user User making the clone
* @param int $socid Id of thirdparty
- * @return int New id of clone
- */
- public function createFromClone(User $user, $socid = 0)
- {
- global $conf, $user, $hookmanager;
+ * @return int New id of clone
+ */
+ public function createFromClone(User $user, $socid = 0)
+ {
+ global $conf, $user, $hookmanager;
- $error = 0;
+ $error = 0;
$this->db->begin();
- // get extrafields so they will be clone
- foreach ($this->lines as $line)
- $line->fetch_optionals();
+ // get extrafields so they will be clone
+ foreach ($this->lines as $line)
+ $line->fetch_optionals();
// Load source object
$objFrom = clone $this;
@@ -1474,85 +1474,85 @@ class CommandeFournisseur extends CommonOrder
// TODO Change product price if multi-prices
}
- $this->id = 0;
- $this->statut = self::STATUS_DRAFT;
+ $this->id = 0;
+ $this->statut = self::STATUS_DRAFT;
- // Clear fields
- $this->user_author_id = $user->id;
- $this->user_valid = '';
- $this->date_creation = '';
- $this->date_validation = '';
- $this->ref_supplier = '';
- $this->user_approve_id = '';
- $this->user_approve_id2 = '';
- $this->date_approve = '';
- $this->date_approve2 = '';
+ // Clear fields
+ $this->user_author_id = $user->id;
+ $this->user_valid = '';
+ $this->date_creation = '';
+ $this->date_validation = '';
+ $this->ref_supplier = '';
+ $this->user_approve_id = '';
+ $this->user_approve_id2 = '';
+ $this->date_approve = '';
+ $this->date_approve2 = '';
- // Create clone
- $this->context['createfromclone'] = 'createfromclone';
- $result = $this->create($user);
- if ($result < 0) $error++;
+ // Create clone
+ $this->context['createfromclone'] = 'createfromclone';
+ $result = $this->create($user);
+ if ($result < 0) $error++;
- if (!$error)
- {
- // Hook of thirdparty module
- if (is_object($hookmanager))
- {
- $parameters = array('objFrom'=>$objFrom);
- $action = '';
- $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
- if ($reshook < 0) $error++;
- }
- }
+ if (!$error)
+ {
+ // Hook of thirdparty module
+ if (is_object($hookmanager))
+ {
+ $parameters = array('objFrom'=>$objFrom);
+ $action = '';
+ $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook < 0) $error++;
+ }
+ }
unset($this->context['createfromclone']);
// End
- if (!$error)
- {
- $this->db->commit();
- return $this->id;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Add order line
- *
- * @param string $desc Description
- * @param float $pu_ht Unit price
- * @param float $qty Quantity
- * @param float $txtva Taux tva
- * @param float $txlocaltax1 Localtax1 tax
- * @param float $txlocaltax2 Localtax2 tax
- * @param int $fk_product Id product
- * @param int $fk_prod_fourn_price Id supplier price
- * @param string $ref_supplier Supplier reference price
- * @param float $remise_percent Remise
- * @param string $price_base_type HT or TTC
- * @param float $pu_ttc Unit price TTC
- * @param int $type Type of line (0=product, 1=service)
- * @param int $info_bits More information
- * @param bool $notrigger Disable triggers
- * @param int $date_start Date start of service
- * @param int $date_end Date end of service
+ /**
+ * Add order line
+ *
+ * @param string $desc Description
+ * @param float $pu_ht Unit price
+ * @param float $qty Quantity
+ * @param float $txtva Taux tva
+ * @param float $txlocaltax1 Localtax1 tax
+ * @param float $txlocaltax2 Localtax2 tax
+ * @param int $fk_product Id product
+ * @param int $fk_prod_fourn_price Id supplier price
+ * @param string $ref_supplier Supplier reference price
+ * @param float $remise_percent Remise
+ * @param string $price_base_type HT or TTC
+ * @param float $pu_ttc Unit price TTC
+ * @param int $type Type of line (0=product, 1=service)
+ * @param int $info_bits More information
+ * @param bool $notrigger Disable triggers
+ * @param int $date_start Date start of service
+ * @param int $date_end Date end of service
* @param array $array_options extrafields array
- * @param string $fk_unit Code of the unit to use. Null to use the default one
+ * @param string $fk_unit Code of the unit to use. Null to use the default one
* @param string $pu_ht_devise Amount in currency
* @param string $origin 'order', ...
* @param int $origin_id Id of origin object
- * @return int <=0 if KO, >0 if OK
- */
+ * @return int <=0 if KO, >0 if OK
+ */
public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $fk_prod_fourn_price = 0, $ref_supplier = '', $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $type = 0, $info_bits = 0, $notrigger = false, $date_start = null, $date_end = null, $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $origin = '', $origin_id = 0)
- {
- global $langs, $mysoc, $conf;
+ {
+ global $langs, $mysoc, $conf;
- $error = 0;
+ $error = 0;
- dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type, $info_bits, $notrigger, $date_start, $date_end, $fk_unit, $pu_ht_devise, $origin, $origin_id");
- include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
+ dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type, $info_bits, $notrigger, $date_start, $date_end, $fk_unit, $pu_ht_devise, $origin, $origin_id");
+ include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
if ($this->statut == self::STATUS_DRAFT)
{
@@ -2025,6 +2025,9 @@ class CommandeFournisseur extends CommonOrder
if (!$error)
{
+ // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
+ $this->deleteEcmFiles();
+
// We remove directory
$ref = dol_sanitizeFileName($this->ref);
if ($conf->fournisseur->commande->dir_output)
@@ -2972,8 +2975,8 @@ class CommandeFournisseur extends CommonOrder
if (!dol_strlen($modele)) {
$modele = 'muscadet';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) {
$modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF;
}
diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php
index 0ce33f639f4..f94cadbca9c 100644
--- a/htdocs/fourn/class/fournisseur.facture.class.php
+++ b/htdocs/fourn/class/fournisseur.facture.class.php
@@ -4,7 +4,7 @@
* Copyright (C) 2004 Christophe Combelles
* Copyright (C) 2005 Marc Barilley
* Copyright (C) 2005-2012 Regis Houssin
- * Copyright (C) 2010-2017 Juanjo Menent
+ * Copyright (C) 2010-2020 Juanjo Menent
* Copyright (C) 2013-2019 Philippe Grand
* Copyright (C) 2013 Florian Henry
* Copyright (C) 2014-2016 Marcos GarcÃa
@@ -368,73 +368,73 @@ class FactureFournisseur extends CommonInvoice
$this->multicurrency_tx = 1;
}
- $this->db->begin();
+ $this->db->begin();
- if (!$remise) $remise = 0;
+ if (!$remise) $remise = 0;
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn (";
$sql .= "ref";
- $sql .= ", ref_supplier";
- $sql .= ", entity";
- $sql .= ", type";
- $sql .= ", libelle";
- $sql .= ", fk_soc";
- $sql .= ", datec";
- $sql .= ", datef";
+ $sql .= ", ref_supplier";
+ $sql .= ", entity";
+ $sql .= ", type";
+ $sql .= ", libelle";
+ $sql .= ", fk_soc";
+ $sql .= ", datec";
+ $sql .= ", datef";
$sql .= ", fk_projet";
$sql .= ", fk_cond_reglement";
$sql .= ", fk_mode_reglement";
- $sql .= ", fk_account";
- $sql .= ", note_private";
- $sql .= ", note_public";
- $sql .= ", fk_user_author";
- $sql .= ", date_lim_reglement";
+ $sql .= ", fk_account";
+ $sql .= ", note_private";
+ $sql .= ", note_public";
+ $sql .= ", fk_user_author";
+ $sql .= ", date_lim_reglement";
$sql .= ", fk_incoterms, location_incoterms";
- $sql .= ", fk_multicurrency";
- $sql .= ", multicurrency_code";
- $sql .= ", multicurrency_tx";
- $sql .= ", fk_facture_source";
- $sql .= ")";
- $sql .= " VALUES (";
+ $sql .= ", fk_multicurrency";
+ $sql .= ", multicurrency_code";
+ $sql .= ", multicurrency_tx";
+ $sql .= ", fk_facture_source";
+ $sql .= ")";
+ $sql .= " VALUES (";
$sql .= "'(PROV)'";
- $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
- $sql .= ", ".$conf->entity;
- $sql .= ", '".$this->db->escape($this->type)."'";
- $sql .= ", '".$this->db->escape($this->label ? $this->label : $this->libelle)."'";
- $sql .= ", ".$this->socid;
- $sql .= ", '".$this->db->idate($now)."'";
- $sql .= ", '".$this->db->idate($this->date)."'";
+ $sql .= ", '".$this->db->escape($this->ref_supplier)."'";
+ $sql .= ", ".$conf->entity;
+ $sql .= ", '".$this->db->escape($this->type)."'";
+ $sql .= ", '".$this->db->escape($this->label ? $this->label : $this->libelle)."'";
+ $sql .= ", ".$this->socid;
+ $sql .= ", '".$this->db->idate($now)."'";
+ $sql .= ", '".$this->db->idate($this->date)."'";
$sql .= ", ".($this->fk_project > 0 ? $this->fk_project : "null");
$sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : "null");
$sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : "null");
- $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
- $sql .= ", '".$this->db->escape($this->note_private)."'";
- $sql .= ", '".$this->db->escape($this->note_public)."'";
- $sql .= ", ".$user->id.",";
- $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null";
+ $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
+ $sql .= ", '".$this->db->escape($this->note_private)."'";
+ $sql .= ", '".$this->db->escape($this->note_public)."'";
+ $sql .= ", ".$user->id.",";
+ $sql .= $this->date_echeance != '' ? "'".$this->db->idate($this->date_echeance)."'" : "null";
$sql .= ", ".(int) $this->fk_incoterms;
- $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
+ $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
$sql .= ", ".(int) $this->fk_multicurrency;
$sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
$sql .= ", ".(double) $this->multicurrency_tx;
- $sql .= ", ".(isset($this->fk_facture_source) ? $this->fk_facture_source : "NULL");
- $sql .= ")";
+ $sql .= ", ".(isset($this->fk_facture_source) ? $this->fk_facture_source : "NULL");
+ $sql .= ")";
- dol_syslog(get_class($this)."::create", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn');
- // Update ref with new one
- $this->ref = '(PROV'.$this->id.')';
- $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
+ // Update ref with new one
+ $this->ref = '(PROV'.$this->id.')';
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
- dol_syslog(get_class($this)."::create", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql) $error++;
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) $error++;
- if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
+ if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
{
$this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
}
@@ -444,115 +444,115 @@ class FactureFournisseur extends CommonInvoice
{
foreach ($this->linked_objects as $origin => $tmp_origin_id)
{
- if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
- {
- foreach ($tmp_origin_id as $origin_id)
- {
- $ret = $this->add_object_linked($origin, $origin_id);
- if (!$ret)
- {
- dol_print_error($this->db);
- $error++;
- }
- }
- } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
- {
- $origin_id = $tmp_origin_id;
- $ret = $this->add_object_linked($origin, $origin_id);
- if (!$ret)
- {
- dol_print_error($this->db);
- $error++;
- }
- }
+ if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
+ {
+ foreach ($tmp_origin_id as $origin_id)
+ {
+ $ret = $this->add_object_linked($origin, $origin_id);
+ if (!$ret)
+ {
+ dol_print_error($this->db);
+ $error++;
+ }
+ }
+ } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
+ {
+ $origin_id = $tmp_origin_id;
+ $ret = $this->add_object_linked($origin, $origin_id);
+ if (!$ret)
+ {
+ dol_print_error($this->db);
+ $error++;
+ }
+ }
}
}
if (count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode)
{
dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
- foreach ($this->lines as $i => $val)
- {
- $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)';
- $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')';
+ foreach ($this->lines as $i => $val)
+ {
+ $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)';
+ $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')';
- $resql_insert = $this->db->query($sql);
- if ($resql_insert)
- {
- $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
+ $resql_insert = $this->db->query($sql);
+ if ($resql_insert)
+ {
+ $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
- $this->updateline(
- $idligne,
- $this->lines[$i]->description,
- $this->lines[$i]->pu_ht,
- $this->lines[$i]->tva_tx.($this->lines[$i]->vat_src_code ? ' ('.$this->lines[$i]->vat_src_code.')' : ''),
- $this->lines[$i]->localtax1_tx,
- $this->lines[$i]->localtax2_tx,
- $this->lines[$i]->qty,
- $this->lines[$i]->fk_product,
- 'HT',
- (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''),
- $this->lines[$i]->product_type,
- $this->lines[$i]->remise_percent,
- false,
- $this->lines[$i]->date_start,
- $this->lines[$i]->date_end,
- $this->lines[$i]->array_options,
- $this->lines[$i]->fk_unit,
- $this->lines[$i]->pu_ht_devise
- );
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -5;
- }
- }
+ $this->updateline(
+ $idligne,
+ $this->lines[$i]->description,
+ $this->lines[$i]->pu_ht,
+ $this->lines[$i]->tva_tx.($this->lines[$i]->vat_src_code ? ' ('.$this->lines[$i]->vat_src_code.')' : ''),
+ $this->lines[$i]->localtax1_tx,
+ $this->lines[$i]->localtax2_tx,
+ $this->lines[$i]->qty,
+ $this->lines[$i]->fk_product,
+ 'HT',
+ (!empty($this->lines[$i]->info_bits) ? $this->lines[$i]->info_bits : ''),
+ $this->lines[$i]->product_type,
+ $this->lines[$i]->remise_percent,
+ false,
+ $this->lines[$i]->date_start,
+ $this->lines[$i]->date_end,
+ $this->lines[$i]->array_options,
+ $this->lines[$i]->fk_unit,
+ $this->lines[$i]->pu_ht_devise
+ );
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -5;
+ }
+ }
} else // If this->lines is an array of invoice line arrays
{
- dol_syslog("There is ".count($this->lines)." lines that are array lines");
- foreach ($this->lines as $i => $val)
- {
- $line = $this->lines[$i];
+ dol_syslog("There is ".count($this->lines)." lines that are array lines");
+ foreach ($this->lines as $i => $val)
+ {
+ $line = $this->lines[$i];
- // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
- //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
- if (!is_object($line)) $line = (object) $line;
+ // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
+ //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
+ if (!is_object($line)) $line = (object) $line;
- $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)';
- $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')';
+ $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)';
+ $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')';
- $resql_insert = $this->db->query($sql);
- if ($resql_insert)
- {
- $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
+ $resql_insert = $this->db->query($sql);
+ if ($resql_insert)
+ {
+ $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det');
- $this->updateline(
- $idligne,
- $line->description,
- $line->pu_ht,
- $line->tva_tx,
- $line->localtax1_tx,
- $line->localtax2_tx,
- $line->qty,
- $line->fk_product,
- 'HT',
- (!empty($line->info_bits) ? $line->info_bits : ''),
- $line->product_type
- );
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -5;
- }
- }
+ $this->updateline(
+ $idligne,
+ $line->description,
+ $line->pu_ht,
+ $line->tva_tx,
+ $line->localtax1_tx,
+ $line->localtax2_tx,
+ $line->qty,
+ $line->fk_product,
+ 'HT',
+ (!empty($line->info_bits) ? $line->info_bits : ''),
+ $line->product_type
+ );
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -5;
+ }
+ }
}
- // Update total price
- $result = $this->update_price();
- if ($result > 0)
- {
+ // Update total price
+ $result = $this->update_price();
+ if ($result > 0)
+ {
// Actions on extra fields
- if (!$error)
+ if (!$error)
{
$result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found
if ($result < 0)
@@ -563,155 +563,155 @@ class FactureFournisseur extends CommonInvoice
if (!$error)
{
- // Call trigger
- $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user);
- if ($result < 0) $error++;
- // End call triggers
+ // Call trigger
+ $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
}
- if (!$error)
- {
- $this->db->commit();
- return $this->id;
- } else {
- $this->db->rollback();
- return -4;
- }
- } else {
- $this->error = $langs->trans('FailedToUpdatePrice');
- $this->db->rollback();
- return -3;
- }
- } else {
- if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
- {
- $this->error = $langs->trans('ErrorRefAlreadyExists');
- $this->db->rollback();
- return -1;
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -2;
- }
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->db->rollback();
+ return -4;
+ }
+ } else {
+ $this->error = $langs->trans('FailedToUpdatePrice');
+ $this->db->rollback();
+ return -3;
+ }
+ } else {
+ if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
+ {
+ $this->error = $langs->trans('ErrorRefAlreadyExists');
+ $this->db->rollback();
+ return -1;
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -2;
+ }
+ }
+ }
- /**
- * Load object in memory from database
- *
- * @param int $id Id supplier invoice
- * @param string $ref Ref supplier invoice
- * @return int <0 if KO, >0 if OK, 0 if not found
- */
- public function fetch($id = '', $ref = '')
- {
- global $langs;
+ /**
+ * Load object in memory from database
+ *
+ * @param int $id Id supplier invoice
+ * @param string $ref Ref supplier invoice
+ * @return int <0 if KO, >0 if OK, 0 if not found
+ */
+ public function fetch($id = '', $ref = '')
+ {
+ global $langs;
- $sql = "SELECT";
- $sql .= " t.rowid,";
+ $sql = "SELECT";
+ $sql .= " t.rowid,";
$sql .= " t.ref,";
- $sql .= " t.ref_supplier,";
- $sql .= " t.entity,";
- $sql .= " t.type,";
- $sql .= " t.fk_soc,";
- $sql .= " t.datec,";
- $sql .= " t.datef,";
- $sql .= " t.tms,";
- $sql .= " t.libelle as label,";
- $sql .= " t.paye,";
- $sql .= " t.amount,";
- $sql .= " t.remise,";
- $sql .= " t.close_code,";
- $sql .= " t.close_note,";
- $sql .= " t.tva,";
- $sql .= " t.localtax1,";
- $sql .= " t.localtax2,";
- $sql .= " t.total_ht,";
- $sql .= " t.total_tva,";
- $sql .= " t.total_ttc,";
- $sql .= " t.fk_statut,";
- $sql .= " t.fk_user_author,";
- $sql .= " t.fk_user_valid,";
- $sql .= " t.fk_facture_source,";
- $sql .= " t.fk_projet as fk_project,";
- $sql .= " t.fk_cond_reglement,";
- $sql .= " t.fk_account,";
- $sql .= " t.fk_mode_reglement,";
- $sql .= " t.date_lim_reglement,";
- $sql .= " t.note_private,";
- $sql .= " t.note_public,";
- $sql .= " t.model_pdf,";
- $sql .= " t.import_key,";
- $sql .= " t.extraparams,";
- $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
- $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,";
- $sql .= ' s.nom as socnom, s.rowid as socid,';
- $sql .= ' t.fk_incoterms, t.location_incoterms,';
- $sql .= " i.libelle as label_incoterms,";
- $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
- $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id";
+ $sql .= " t.ref_supplier,";
+ $sql .= " t.entity,";
+ $sql .= " t.type,";
+ $sql .= " t.fk_soc,";
+ $sql .= " t.datec,";
+ $sql .= " t.datef,";
+ $sql .= " t.tms,";
+ $sql .= " t.libelle as label,";
+ $sql .= " t.paye,";
+ $sql .= " t.amount,";
+ $sql .= " t.remise,";
+ $sql .= " t.close_code,";
+ $sql .= " t.close_note,";
+ $sql .= " t.tva,";
+ $sql .= " t.localtax1,";
+ $sql .= " t.localtax2,";
+ $sql .= " t.total_ht,";
+ $sql .= " t.total_tva,";
+ $sql .= " t.total_ttc,";
+ $sql .= " t.fk_statut,";
+ $sql .= " t.fk_user_author,";
+ $sql .= " t.fk_user_valid,";
+ $sql .= " t.fk_facture_source,";
+ $sql .= " t.fk_projet as fk_project,";
+ $sql .= " t.fk_cond_reglement,";
+ $sql .= " t.fk_account,";
+ $sql .= " t.fk_mode_reglement,";
+ $sql .= " t.date_lim_reglement,";
+ $sql .= " t.note_private,";
+ $sql .= " t.note_public,";
+ $sql .= " t.model_pdf,";
+ $sql .= " t.import_key,";
+ $sql .= " t.extraparams,";
+ $sql .= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,";
+ $sql .= " p.code as mode_reglement_code, p.libelle as mode_reglement_libelle,";
+ $sql .= ' s.nom as socnom, s.rowid as socid,';
+ $sql .= ' t.fk_incoterms, t.location_incoterms,';
+ $sql .= " i.libelle as label_incoterms,";
+ $sql .= ' t.fk_multicurrency, t.multicurrency_code, t.multicurrency_tx, t.multicurrency_total_ht, t.multicurrency_total_tva, t.multicurrency_total_ttc';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as t';
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (t.fk_soc = s.rowid)";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id";
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid';
- if ($id) $sql .= " WHERE t.rowid=".$id;
- if ($ref) $sql .= " WHERE t.ref='".$this->db->escape($ref)."' AND t.entity IN (".getEntity('supplier_invoice').")";
+ if ($id) $sql .= " WHERE t.rowid=".$id;
+ if ($ref) $sql .= " WHERE t.ref='".$this->db->escape($ref)."' AND t.entity IN (".getEntity('supplier_invoice').")";
- dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
- $obj = $this->db->fetch_object($resql);
+ dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ if ($this->db->num_rows($resql))
+ {
+ $obj = $this->db->fetch_object($resql);
- $this->id = $obj->rowid;
- $this->ref = $obj->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility
+ $this->id = $obj->rowid;
+ $this->ref = $obj->ref ? $obj->ref : $obj->rowid; // We take rowid if ref is empty for backward compatibility
- $this->ref_supplier = $obj->ref_supplier;
- $this->entity = $obj->entity;
- $this->type = empty($obj->type) ? self::TYPE_STANDARD : $obj->type;
- $this->fk_soc = $obj->fk_soc;
- $this->datec = $this->db->jdate($obj->datec);
- $this->date = $this->db->jdate($obj->datef);
- $this->datep = $this->db->jdate($obj->datef);
- $this->tms = $this->db->jdate($obj->tms);
- $this->libelle = $obj->label; // deprecated
- $this->label = $obj->label;
- $this->paye = $obj->paye;
- $this->paid = $obj->paye;
- $this->amount = $obj->amount;
- $this->remise = $obj->remise;
- $this->close_code = $obj->close_code;
- $this->close_note = $obj->close_note;
- $this->tva = $obj->tva;
- $this->total_localtax1 = $obj->localtax1;
- $this->total_localtax2 = $obj->localtax2;
- $this->total_ht = $obj->total_ht;
- $this->total_tva = $obj->total_tva;
- $this->total_ttc = $obj->total_ttc;
- $this->fk_statut = $obj->fk_statut;
- $this->statut = $obj->fk_statut;
- $this->fk_user_author = $obj->fk_user_author;
- $this->author = $obj->fk_user_author;
- $this->fk_user_valid = $obj->fk_user_valid;
- $this->fk_facture_source = $obj->fk_facture_source;
- $this->fk_project = $obj->fk_project;
- $this->cond_reglement_id = $obj->fk_cond_reglement;
- $this->cond_reglement_code = $obj->cond_reglement_code;
- $this->cond_reglement = $obj->cond_reglement_libelle;
- $this->cond_reglement_doc = $obj->cond_reglement_libelle;
- $this->fk_account = $obj->fk_account;
- $this->mode_reglement_id = $obj->fk_mode_reglement;
- $this->mode_reglement_code = $obj->mode_reglement_code;
- $this->mode_reglement = $obj->mode_reglement_libelle;
- $this->date_echeance = $this->db->jdate($obj->date_lim_reglement);
- $this->note = $obj->note_private; // deprecated
- $this->note_private = $obj->note_private;
- $this->note_public = $obj->note_public;
- $this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf;
- $this->import_key = $obj->import_key;
+ $this->ref_supplier = $obj->ref_supplier;
+ $this->entity = $obj->entity;
+ $this->type = empty($obj->type) ? self::TYPE_STANDARD : $obj->type;
+ $this->fk_soc = $obj->fk_soc;
+ $this->datec = $this->db->jdate($obj->datec);
+ $this->date = $this->db->jdate($obj->datef);
+ $this->datep = $this->db->jdate($obj->datef);
+ $this->tms = $this->db->jdate($obj->tms);
+ $this->libelle = $obj->label; // deprecated
+ $this->label = $obj->label;
+ $this->paye = $obj->paye;
+ $this->paid = $obj->paye;
+ $this->amount = $obj->amount;
+ $this->remise = $obj->remise;
+ $this->close_code = $obj->close_code;
+ $this->close_note = $obj->close_note;
+ $this->tva = $obj->tva;
+ $this->total_localtax1 = $obj->localtax1;
+ $this->total_localtax2 = $obj->localtax2;
+ $this->total_ht = $obj->total_ht;
+ $this->total_tva = $obj->total_tva;
+ $this->total_ttc = $obj->total_ttc;
+ $this->fk_statut = $obj->fk_statut;
+ $this->statut = $obj->fk_statut;
+ $this->fk_user_author = $obj->fk_user_author;
+ $this->author = $obj->fk_user_author;
+ $this->fk_user_valid = $obj->fk_user_valid;
+ $this->fk_facture_source = $obj->fk_facture_source;
+ $this->fk_project = $obj->fk_project;
+ $this->cond_reglement_id = $obj->fk_cond_reglement;
+ $this->cond_reglement_code = $obj->cond_reglement_code;
+ $this->cond_reglement = $obj->cond_reglement_libelle;
+ $this->cond_reglement_doc = $obj->cond_reglement_libelle;
+ $this->fk_account = $obj->fk_account;
+ $this->mode_reglement_id = $obj->fk_mode_reglement;
+ $this->mode_reglement_code = $obj->mode_reglement_code;
+ $this->mode_reglement = $obj->mode_reglement_libelle;
+ $this->date_echeance = $this->db->jdate($obj->date_lim_reglement);
+ $this->note = $obj->note_private; // deprecated
+ $this->note_private = $obj->note_private;
+ $this->note_public = $obj->note_public;
+ $this->model_pdf = $obj->model_pdf;
+ $this->modelpdf = $obj->model_pdf; // deprecated
+ $this->import_key = $obj->import_key;
//Incoterms
$this->fk_incoterms = $obj->fk_incoterms;
@@ -726,112 +726,112 @@ class FactureFournisseur extends CommonInvoice
$this->multicurrency_total_tva = $obj->multicurrency_total_tva;
$this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
- $this->extraparams = (array) json_decode($obj->extraparams, true);
+ $this->extraparams = (array) json_decode($obj->extraparams, true);
- $this->socid = $obj->socid;
- $this->socnom = $obj->socnom;
+ $this->socid = $obj->socid;
+ $this->socnom = $obj->socnom;
- // Retreive all extrafield
- // fetch optionals attributes and labels
- $this->fetch_optionals();
+ // Retreive all extrafield
+ // fetch optionals attributes and labels
+ $this->fetch_optionals();
- if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
+ if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
- $result = $this->fetch_lines();
- if ($result < 0)
- {
- $this->error = $this->db->lasterror();
- return -3;
- }
- } else {
- $this->error = 'Bill with id '.$id.' not found';
- dol_syslog(get_class($this).'::fetch '.$this->error);
- return 0;
- }
+ $result = $this->fetch_lines();
+ if ($result < 0)
+ {
+ $this->error = $this->db->lasterror();
+ return -3;
+ }
+ } else {
+ $this->error = 'Bill with id '.$id.' not found';
+ dol_syslog(get_class($this).'::fetch '.$this->error);
+ return 0;
+ }
- $this->db->free($resql);
- return 1;
- } else {
- $this->error = "Error ".$this->db->lasterror();
- return -1;
- }
- }
+ $this->db->free($resql);
+ return 1;
+ } else {
+ $this->error = "Error ".$this->db->lasterror();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Load this->lines
- *
- * @return int 1 si ok, < 0 si erreur
- */
- public function fetch_lines()
- {
- // phpcs:enable
- $this->lines = array();
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Load this->lines
+ *
+ * @return int 1 si ok, < 0 si erreur
+ */
+ public function fetch_lines()
+ {
+ // phpcs:enable
+ $this->lines = array();
- $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx';
- $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn ';
- $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
- $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
- $sql .= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
- $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
- $sql .= ' WHERE fk_facture_fourn='.$this->id;
- $sql .= ' ORDER BY f.rang, f.rowid';
+ $sql = 'SELECT f.rowid, f.ref as ref_supplier, f.description, f.date_start, f.date_end, f.pu_ht, f.pu_ttc, f.qty, f.remise_percent, f.vat_src_code, f.tva_tx';
+ $sql .= ', f.localtax1_tx, f.localtax2_tx, f.localtax1_type, f.localtax2_type, f.total_localtax1, f.total_localtax2, f.fk_facture_fourn ';
+ $sql .= ', f.total_ht, f.tva as total_tva, f.total_ttc, f.fk_product, f.product_type, f.info_bits, f.rang, f.special_code, f.fk_parent_line, f.fk_unit';
+ $sql .= ', p.rowid as product_id, p.ref as product_ref, p.label as label, p.description as product_desc';
+ $sql .= ', f.fk_multicurrency, f.multicurrency_code, f.multicurrency_subprice, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn_det as f';
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid';
+ $sql .= ' WHERE fk_facture_fourn='.$this->id;
+ $sql .= ' ORDER BY f.rang, f.rowid';
- dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
- $resql_rows = $this->db->query($sql);
- if ($resql_rows)
- {
- $num_rows = $this->db->num_rows($resql_rows);
- if ($num_rows)
- {
- $i = 0;
- while ($i < $num_rows)
- {
- $obj = $this->db->fetch_object($resql_rows);
+ dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
+ $resql_rows = $this->db->query($sql);
+ if ($resql_rows)
+ {
+ $num_rows = $this->db->num_rows($resql_rows);
+ if ($num_rows)
+ {
+ $i = 0;
+ while ($i < $num_rows)
+ {
+ $obj = $this->db->fetch_object($resql_rows);
- $line = new SupplierInvoiceLine($this->db);
+ $line = new SupplierInvoiceLine($this->db);
- $line->id = $obj->rowid;
- $line->rowid = $obj->rowid;
- $line->description = $obj->description;
- $line->date_start = $obj->date_start;
- $line->date_end = $obj->date_end;
+ $line->id = $obj->rowid;
+ $line->rowid = $obj->rowid;
+ $line->description = $obj->description;
+ $line->date_start = $obj->date_start;
+ $line->date_end = $obj->date_end;
- $line->product_ref = $obj->product_ref;
- $line->ref = $obj->product_ref;
- $line->ref_supplier = $obj->ref_supplier;
- $line->libelle = $obj->label;
- $line->label = $obj->label;
- $line->product_desc = $obj->product_desc;
- $line->subprice = $obj->pu_ht;
- $line->pu_ht = $obj->pu_ht;
- $line->pu_ttc = $obj->pu_ttc;
+ $line->product_ref = $obj->product_ref;
+ $line->ref = $obj->product_ref;
+ $line->ref_supplier = $obj->ref_supplier;
+ $line->libelle = $obj->label;
+ $line->label = $obj->label;
+ $line->product_desc = $obj->product_desc;
+ $line->subprice = $obj->pu_ht;
+ $line->pu_ht = $obj->pu_ht;
+ $line->pu_ttc = $obj->pu_ttc;
- $line->vat_src_code = $obj->vat_src_code;
- $line->tva_tx = $obj->tva_tx;
- $line->localtax1_tx = $obj->localtax1_tx;
- $line->localtax2_tx = $obj->localtax2_tx;
- $line->localtax1_type = $obj->localtax1_type;
- $line->localtax2_type = $obj->localtax2_type;
- $line->qty = $obj->qty;
- $line->remise_percent = $obj->remise_percent;
- $line->tva = $obj->total_tva; // deprecated
- $line->total_ht = $obj->total_ht;
- $line->total_ttc = $obj->total_ttc;
- $line->total_tva = $obj->total_tva;
- $line->total_localtax1 = $obj->total_localtax1;
- $line->total_localtax2 = $obj->total_localtax2;
- $line->fk_facture_fourn = $obj->fk_facture_fourn;
- $line->fk_product = $obj->fk_product;
- $line->product_type = $obj->product_type;
- $line->product_label = $obj->label;
- $line->info_bits = $obj->info_bits;
- $line->fk_parent_line = $obj->fk_parent_line;
- $line->special_code = $obj->special_code;
- $line->rang = $obj->rang;
- $line->fk_unit = $obj->fk_unit;
+ $line->vat_src_code = $obj->vat_src_code;
+ $line->tva_tx = $obj->tva_tx;
+ $line->localtax1_tx = $obj->localtax1_tx;
+ $line->localtax2_tx = $obj->localtax2_tx;
+ $line->localtax1_type = $obj->localtax1_type;
+ $line->localtax2_type = $obj->localtax2_type;
+ $line->qty = $obj->qty;
+ $line->remise_percent = $obj->remise_percent;
+ $line->tva = $obj->total_tva; // deprecated
+ $line->total_ht = $obj->total_ht;
+ $line->total_ttc = $obj->total_ttc;
+ $line->total_tva = $obj->total_tva;
+ $line->total_localtax1 = $obj->total_localtax1;
+ $line->total_localtax2 = $obj->total_localtax2;
+ $line->fk_facture_fourn = $obj->fk_facture_fourn;
+ $line->fk_product = $obj->fk_product;
+ $line->product_type = $obj->product_type;
+ $line->product_label = $obj->label;
+ $line->info_bits = $obj->info_bits;
+ $line->fk_parent_line = $obj->fk_parent_line;
+ $line->special_code = $obj->special_code;
+ $line->rang = $obj->rang;
+ $line->fk_unit = $obj->fk_unit;
// Multicurrency
$line->fk_multicurrency = $obj->fk_multicurrency;
@@ -841,121 +841,121 @@ class FactureFournisseur extends CommonInvoice
$line->multicurrency_total_tva = $obj->multicurrency_total_tva;
$line->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
- // Extra fields
+ // Extra fields
$line->fetch_optionals();
$this->lines[$i] = $line;
- $i++;
- }
- }
- $this->db->free($resql_rows);
- return 1;
- } else {
- $this->error = $this->db->error();
- return -3;
- }
- }
+ $i++;
+ }
+ }
+ $this->db->free($resql_rows);
+ return 1;
+ } else {
+ $this->error = $this->db->error();
+ return -3;
+ }
+ }
- /**
- * Update database
- *
- * @param User $user User that modify
- * @param int $notrigger 0=launch triggers after, 1=disable triggers
- * @return int <0 if KO, >0 if OK
- */
- public function update($user = null, $notrigger = 0)
- {
- global $conf, $langs;
- $error = 0;
+ /**
+ * Update database
+ *
+ * @param User $user User that modify
+ * @param int $notrigger 0=launch triggers after, 1=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update($user = null, $notrigger = 0)
+ {
+ global $conf, $langs;
+ $error = 0;
- // Clean parameters
- if (empty($this->type)) $this->type = self::TYPE_STANDARD;
+ // Clean parameters
+ if (empty($this->type)) $this->type = self::TYPE_STANDARD;
if (isset($this->ref)) $this->ref = trim($this->ref);
- if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier);
- if (isset($this->entity)) $this->entity = trim($this->entity);
- if (isset($this->type)) $this->type = trim($this->type);
- if (isset($this->fk_soc)) $this->fk_soc = trim($this->fk_soc);
- if (isset($this->label)) $this->label = trim($this->label);
- if (isset($this->libelle)) $this->libelle = trim($this->libelle); // deprecated
- if (isset($this->paye)) $this->paye = trim($this->paye);
- if (isset($this->amount)) $this->amount = trim($this->amount);
- if (isset($this->remise)) $this->remise = trim($this->remise);
- if (isset($this->close_code)) $this->close_code = trim($this->close_code);
- if (isset($this->close_note)) $this->close_note = trim($this->close_note);
- if (isset($this->tva)) $this->tva = trim($this->tva);
- if (isset($this->localtax1)) $this->localtax1 = trim($this->localtax1);
- if (isset($this->localtax2)) $this->localtax2 = trim($this->localtax2);
- if (empty($this->total_ht)) $this->total_ht = 0;
- if (empty($this->total_tva)) $this->total_tva = 0;
- // if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
- // if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
- if (isset($this->total_ttc)) $this->total_ttc = trim($this->total_ttc);
- if (isset($this->statut)) $this->statut = (int) $this->statut;
- if (isset($this->author)) $this->author = trim($this->author);
- if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid);
- if (isset($this->fk_facture_source)) $this->fk_facture_source = trim($this->fk_facture_source);
- if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project);
- if (isset($this->cond_reglement_id)) $this->cond_reglement_id = trim($this->cond_reglement_id);
- if (isset($this->note_private)) $this->note = trim($this->note_private);
- if (isset($this->note_public)) $this->note_public = trim($this->note_public);
- if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf);
- if (isset($this->import_key)) $this->import_key = trim($this->import_key);
+ if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier);
+ if (isset($this->entity)) $this->entity = trim($this->entity);
+ if (isset($this->type)) $this->type = trim($this->type);
+ if (isset($this->fk_soc)) $this->fk_soc = trim($this->fk_soc);
+ if (isset($this->label)) $this->label = trim($this->label);
+ if (isset($this->libelle)) $this->libelle = trim($this->libelle); // deprecated
+ if (isset($this->paye)) $this->paye = trim($this->paye);
+ if (isset($this->amount)) $this->amount = trim($this->amount);
+ if (isset($this->remise)) $this->remise = trim($this->remise);
+ if (isset($this->close_code)) $this->close_code = trim($this->close_code);
+ if (isset($this->close_note)) $this->close_note = trim($this->close_note);
+ if (isset($this->tva)) $this->tva = trim($this->tva);
+ if (isset($this->localtax1)) $this->localtax1 = trim($this->localtax1);
+ if (isset($this->localtax2)) $this->localtax2 = trim($this->localtax2);
+ if (empty($this->total_ht)) $this->total_ht = 0;
+ if (empty($this->total_tva)) $this->total_tva = 0;
+ // if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1);
+ // if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2);
+ if (isset($this->total_ttc)) $this->total_ttc = trim($this->total_ttc);
+ if (isset($this->statut)) $this->statut = (int) $this->statut;
+ if (isset($this->author)) $this->author = trim($this->author);
+ if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid);
+ if (isset($this->fk_facture_source)) $this->fk_facture_source = trim($this->fk_facture_source);
+ if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project);
+ if (isset($this->cond_reglement_id)) $this->cond_reglement_id = trim($this->cond_reglement_id);
+ if (isset($this->note_private)) $this->note = trim($this->note_private);
+ if (isset($this->note_public)) $this->note_public = trim($this->note_public);
+ if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf);
+ if (isset($this->import_key)) $this->import_key = trim($this->import_key);
- // Check parameters
- // Put here code to add control on parameters values
+ // Check parameters
+ // Put here code to add control on parameters values
- // Update request
- $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
+ // Update request
+ $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn SET";
$sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
- $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
- $sql .= " entity=".(isset($this->entity) ? $this->entity : "null").",";
- $sql .= " type=".(isset($this->type) ? $this->type : "null").",";
- $sql .= " fk_soc=".(isset($this->fk_soc) ? $this->fk_soc : "null").",";
- $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
- $sql .= " datef=".(dol_strlen($this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
- if (dol_strlen($this->tms) != 0) $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
- $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
- $sql .= " paye=".(isset($this->paye) ? $this->paye : "null").",";
- $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").",";
- $sql .= " remise=".(isset($this->remise) ? $this->remise : "null").",";
- $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
- $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
- $sql .= " tva=".(isset($this->tva) ? $this->tva : "null").",";
- $sql .= " localtax1=".(isset($this->localtax1) ? $this->localtax1 : "null").",";
- $sql .= " localtax2=".(isset($this->localtax2) ? $this->localtax2 : "null").",";
- $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
- $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
- $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
- $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
- $sql .= " fk_user_author=".(isset($this->author) ? $this->author : "null").",";
- $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
- $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->fk_facture_source : "null").",";
- $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
- $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
- $sql .= " date_lim_reglement=".(dol_strlen($this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
- $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
- $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
- $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
- $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
- $sql .= " WHERE rowid=".$this->id;
+ $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
+ $sql .= " entity=".(isset($this->entity) ? $this->entity : "null").",";
+ $sql .= " type=".(isset($this->type) ? $this->type : "null").",";
+ $sql .= " fk_soc=".(isset($this->fk_soc) ? $this->fk_soc : "null").",";
+ $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
+ $sql .= " datef=".(dol_strlen($this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').",";
+ if (dol_strlen($this->tms) != 0) $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
+ $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
+ $sql .= " paye=".(isset($this->paye) ? $this->paye : "null").",";
+ $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").",";
+ $sql .= " remise=".(isset($this->remise) ? $this->remise : "null").",";
+ $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
+ $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
+ $sql .= " tva=".(isset($this->tva) ? $this->tva : "null").",";
+ $sql .= " localtax1=".(isset($this->localtax1) ? $this->localtax1 : "null").",";
+ $sql .= " localtax2=".(isset($this->localtax2) ? $this->localtax2 : "null").",";
+ $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
+ $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
+ $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
+ $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
+ $sql .= " fk_user_author=".(isset($this->author) ? $this->author : "null").",";
+ $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
+ $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->fk_facture_source : "null").",";
+ $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
+ $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->cond_reglement_id : "null").",";
+ $sql .= " date_lim_reglement=".(dol_strlen($this->date_echeance) != 0 ? "'".$this->db->idate($this->date_echeance)."'" : 'null').",";
+ $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
+ $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
+ $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
+ $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
+ $sql .= " WHERE rowid=".$this->id;
- $this->db->begin();
+ $this->db->begin();
- dol_syslog(get_class($this)."::update", LOG_DEBUG);
- $resql = $this->db->query($sql);
+ dol_syslog(get_class($this)."::update", LOG_DEBUG);
+ $resql = $this->db->query($sql);
- if (!$resql) {
- $error++;
+ if (!$resql) {
+ $error++;
- if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
- $this->errors[] = $langs->trans('ErrorRefAlreadyExists');
- } else {
- $this->errors[] = "Error ".$this->db->lasterror();
- }
- }
+ if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
+ $this->errors[] = $langs->trans('ErrorRefAlreadyExists');
+ } else {
+ $this->errors[] = "Error ".$this->db->lasterror();
+ }
+ }
if (!$error)
{
@@ -966,162 +966,162 @@ class FactureFournisseur extends CommonInvoice
}
}
- if (!$error)
- {
- if (!$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
- }
+ if (!$error)
+ {
+ if (!$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+ }
- // Commit or rollback
- if ($error)
- {
- foreach ($this->errors as $errmsg)
- {
- dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
- $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
- }
- $this->db->rollback();
- return -1 * $error;
- } else {
- $this->db->commit();
- return 1;
- }
- }
+ // Commit or rollback
+ if ($error)
+ {
+ foreach ($this->errors as $errmsg)
+ {
+ dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
+ $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
+ }
+ $this->db->rollback();
+ return -1 * $error;
+ } else {
+ $this->db->commit();
+ return 1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount)
- *
- * @param int $idremise Id of absolute discount
- * @return int >0 if OK, <0 if KO
- */
- public function insert_discount($idremise)
- {
- // phpcs:enable
- global $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount)
+ *
+ * @param int $idremise Id of absolute discount
+ * @return int >0 if OK, <0 if KO
+ */
+ public function insert_discount($idremise)
+ {
+ // phpcs:enable
+ global $langs;
- include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
- include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
+ include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
+ include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
- $this->db->begin();
+ $this->db->begin();
- $remise = new DiscountAbsolute($this->db);
- $result = $remise->fetch($idremise);
+ $remise = new DiscountAbsolute($this->db);
+ $result = $remise->fetch($idremise);
- if ($result > 0)
- {
- if ($remise->fk_invoice_supplier) // Protection against multiple submission
- {
- $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
- $this->db->rollback();
- return -5;
- }
+ if ($result > 0)
+ {
+ if ($remise->fk_invoice_supplier) // Protection against multiple submission
+ {
+ $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
+ $this->db->rollback();
+ return -5;
+ }
- $facligne = new SupplierInvoiceLine($this->db);
- $facligne->fk_facture_fourn = $this->id;
- $facligne->fk_remise_except = $remise->id;
- $facligne->desc = $remise->description; // Description ligne
- $facligne->vat_src_code = $remise->vat_src_code;
- $facligne->tva_tx = $remise->tva_tx;
- $facligne->subprice = -$remise->amount_ht;
- $facligne->fk_product = 0; // Id produit predefini
- $facligne->product_type = 0;
- $facligne->qty = 1;
- $facligne->remise_percent = 0;
- $facligne->rang = -1;
- $facligne->info_bits = 2;
+ $facligne = new SupplierInvoiceLine($this->db);
+ $facligne->fk_facture_fourn = $this->id;
+ $facligne->fk_remise_except = $remise->id;
+ $facligne->desc = $remise->description; // Description ligne
+ $facligne->vat_src_code = $remise->vat_src_code;
+ $facligne->tva_tx = $remise->tva_tx;
+ $facligne->subprice = -$remise->amount_ht;
+ $facligne->fk_product = 0; // Id produit predefini
+ $facligne->product_type = 0;
+ $facligne->qty = 1;
+ $facligne->remise_percent = 0;
+ $facligne->rang = -1;
+ $facligne->info_bits = 2;
- // Get buy/cost price of invoice that is source of discount
- if ($remise->fk_invoice_supplier_source > 0)
- {
- $srcinvoice = new FactureFournisseur($this->db);
- $srcinvoice->fetch($remise->fk_invoice_supplier_source);
- $totalcostpriceofinvoice = 0;
- include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
- $formmargin = new FormMargin($this->db);
- $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
- $facligne->pa_ht = $arraytmp['pa_total'];
- }
+ // Get buy/cost price of invoice that is source of discount
+ if ($remise->fk_invoice_supplier_source > 0)
+ {
+ $srcinvoice = new FactureFournisseur($this->db);
+ $srcinvoice->fetch($remise->fk_invoice_supplier_source);
+ $totalcostpriceofinvoice = 0;
+ include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
+ $formmargin = new FormMargin($this->db);
+ $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
+ $facligne->pa_ht = $arraytmp['pa_total'];
+ }
- $facligne->total_ht = -$remise->amount_ht;
- $facligne->total_tva = -$remise->amount_tva;
- $facligne->total_ttc = -$remise->amount_ttc;
+ $facligne->total_ht = -$remise->amount_ht;
+ $facligne->total_tva = -$remise->amount_tva;
+ $facligne->total_ttc = -$remise->amount_ttc;
- $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
- $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht;
- $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva;
- $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc;
+ $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
+ $facligne->multicurrency_total_ht = -$remise->multicurrency_total_ht;
+ $facligne->multicurrency_total_tva = -$remise->multicurrency_total_tva;
+ $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc;
- $lineid = $facligne->insert();
- if ($lineid > 0)
- {
- $result = $this->update_price(1);
- if ($result > 0)
- {
- // Create link between discount and invoice line
- $result = $remise->link_to_invoice($lineid, 0, 'supplier');
- if ($result < 0)
- {
- $this->error = $remise->error;
- $this->db->rollback();
- return -4;
- }
+ $lineid = $facligne->insert();
+ if ($lineid > 0)
+ {
+ $result = $this->update_price(1);
+ if ($result > 0)
+ {
+ // Create link between discount and invoice line
+ $result = $remise->link_to_invoice($lineid, 0, 'supplier');
+ if ($result < 0)
+ {
+ $this->error = $remise->error;
+ $this->db->rollback();
+ return -4;
+ }
- $this->db->commit();
- return 1;
- } else {
- $this->error = $facligne->error;
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->error = $facligne->error;
- $this->db->rollback();
- return -2;
- }
- } else {
- $this->db->rollback();
- return -3;
- }
- }
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->error = $facligne->error;
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->error = $facligne->error;
+ $this->db->rollback();
+ return -2;
+ }
+ } else {
+ $this->db->rollback();
+ return -3;
+ }
+ }
- /**
- * Delete invoice from database
- *
- * @param User $user User object
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int <0 if KO, >0 if OK
- */
- public function delete(User $user, $notrigger = 0)
- {
- global $langs, $conf;
+ /**
+ * Delete invoice from database
+ *
+ * @param User $user User object
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = 0)
+ {
+ global $langs, $conf;
- $rowid = $this->id;
+ $rowid = $this->id;
- dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
+ dol_syslog("FactureFournisseur::delete rowid=".$rowid, LOG_DEBUG);
- // TODO Test if there is at least on payment. If yes, refuse to delete.
+ // TODO Test if there is at least on payment. If yes, refuse to delete.
- $error = 0;
- $this->db->begin();
+ $error = 0;
+ $this->db->begin();
- if (!$error && !$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user);
- if ($result < 0)
- {
- $this->db->rollback();
- return -1;
- }
- // Fin appel triggers
- }
+ if (!$error && !$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user);
+ if ($result < 0)
+ {
+ $this->db->rollback();
+ return -1;
+ }
+ // Fin appel triggers
+ }
if (!$error) {
// If invoice was converted into a discount not yet consumed, we remove discount
@@ -1150,27 +1150,27 @@ class FactureFournisseur extends CommonInvoice
}
}
- if (!$error)
- {
- $main = MAIN_DB_PREFIX.'facture_fourn_det';
- $ef = $main."_extrafields";
- $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture_fourn = $rowid)";
- $resqlef = $this->db->query($sqlef);
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';';
- dol_syslog(get_class($this)."::delete", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resqlef && $resql)
- {
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid;
- dol_syslog(get_class($this)."::delete", LOG_DEBUG);
- $resql2 = $this->db->query($sql);
- if (!$resql2) {
- $error++;
- }
- } else {
- $error++;
- }
- }
+ if (!$error)
+ {
+ $main = MAIN_DB_PREFIX.'facture_fourn_det';
+ $ef = $main."_extrafields";
+ $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture_fourn = $rowid)";
+ $resqlef = $this->db->query($sqlef);
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';';
+ dol_syslog(get_class($this)."::delete", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resqlef && $resql)
+ {
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid;
+ dol_syslog(get_class($this)."::delete", LOG_DEBUG);
+ $resql2 = $this->db->query($sql);
+ if (!$resql2) {
+ $error++;
+ }
+ } else {
+ $error++;
+ }
+ }
if (!$error)
{
@@ -1179,437 +1179,440 @@ class FactureFournisseur extends CommonInvoice
if ($res < 0) $error++;
}
- if (!$error)
- {
- // Delete linked object
- $res = $this->deleteObjectLinked();
- if ($res < 0) $error++;
- }
+ if (!$error)
+ {
+ // Delete linked object
+ $res = $this->deleteObjectLinked();
+ if ($res < 0) $error++;
+ }
- if (!$error)
- {
- // We remove directory
- if ($conf->fournisseur->facture->dir_output)
- {
- include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ if (!$error)
+ {
+ // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
+ $this->deleteEcmFiles();
- $ref = dol_sanitizeFileName($this->ref);
- $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref;
- $file = $dir."/".$ref.".pdf";
- if (file_exists($file))
- {
- if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
- {
- $this->error = 'ErrorFailToDeleteFile';
- $error++;
- }
- }
- if (file_exists($dir))
- {
- $res = @dol_delete_dir_recursive($dir);
+ // We remove directory
+ if ($conf->fournisseur->facture->dir_output)
+ {
+ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- if (!$res)
- {
- $this->error = 'ErrorFailToDeleteDir';
- $error++;
- }
- }
- }
- }
+ $ref = dol_sanitizeFileName($this->ref);
+ $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref;
+ $file = $dir."/".$ref.".pdf";
+ if (file_exists($file))
+ {
+ if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
+ {
+ $this->error = 'ErrorFailToDeleteFile';
+ $error++;
+ }
+ }
+ if (file_exists($dir))
+ {
+ $res = @dol_delete_dir_recursive($dir);
- // Remove extrafields
- if (!$error)
- {
- $result = $this->deleteExtraFields();
- if ($result < 0)
- {
- $error++;
- dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
- }
- }
+ if (!$res)
+ {
+ $this->error = 'ErrorFailToDeleteDir';
+ $error++;
+ }
+ }
+ }
+ }
- if (!$error)
- {
- dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
- $this->db->commit();
- return 1;
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -$error;
- }
- }
+ // Remove extrafields
+ if (!$error)
+ {
+ $result = $this->deleteExtraFields();
+ if ($result < 0)
+ {
+ $error++;
+ dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
+ }
+ }
+
+ if (!$error)
+ {
+ dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG);
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -$error;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Tag invoice as a payed invoice
- *
- * @param User $user Object user
- * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet. Not implementd yet.
- * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet. Not implementd yet.
- * @return int <0 si ko, >0 si ok
- */
- public function set_paid($user, $close_code = '', $close_note = '')
- {
- // phpcs:enable
- global $conf, $langs;
- $error = 0;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Tag invoice as a payed invoice
+ *
+ * @param User $user Object user
+ * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet. Not implementd yet.
+ * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet. Not implementd yet.
+ * @return int <0 si ko, >0 si ok
+ */
+ public function set_paid($user, $close_code = '', $close_note = '')
+ {
+ // phpcs:enable
+ global $conf, $langs;
+ $error = 0;
- $this->db->begin();
+ $this->db->begin();
- $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
- $sql .= ' SET paye = 1, fk_statut = '.self::STATUS_CLOSED;
- $sql .= ' WHERE rowid = '.$this->id;
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
+ $sql .= ' SET paye = 1, fk_statut = '.self::STATUS_CLOSED;
+ $sql .= ' WHERE rowid = '.$this->id;
- dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- // Call trigger
- $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user);
- if ($result < 0) $error++;
- // End call triggers
- } else {
- $error++;
- $this->error = $this->db->error();
- dol_print_error($this->db);
- }
+ dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ // Call trigger
+ $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ } else {
+ $error++;
+ $this->error = $this->db->error();
+ dol_print_error($this->db);
+ }
- if (!$error)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
- * Fonction utilisee quand un paiement prelevement est refuse,
- * ou quand une facture annulee et reouverte.
- *
- * @param User $user Object user that change status
- * @return int <0 si ok, >0 si ok
- */
- public function set_unpaid($user)
- {
- // phpcs:enable
- global $conf, $langs;
- $error = 0;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
+ * Fonction utilisee quand un paiement prelevement est refuse,
+ * ou quand une facture annulee et reouverte.
+ *
+ * @param User $user Object user that change status
+ * @return int <0 si ok, >0 si ok
+ */
+ public function set_unpaid($user)
+ {
+ // phpcs:enable
+ global $conf, $langs;
+ $error = 0;
- $this->db->begin();
+ $this->db->begin();
- $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
- $sql .= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
- $sql .= ' WHERE rowid = '.$this->id;
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture_fourn';
+ $sql .= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
+ $sql .= ' WHERE rowid = '.$this->id;
- dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- // Call trigger
- $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user);
- if ($result < 0) $error++;
- // End call triggers
- } else {
- $error++;
- $this->error = $this->db->lasterror();
- dol_syslog("FactureFournisseur::set_unpaid ".$this->error);
- }
+ dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ // Call trigger
+ $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ } else {
+ $error++;
+ $this->error = $this->db->lasterror();
+ dol_syslog("FactureFournisseur::set_unpaid ".$this->error);
+ }
- if (!$error)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Tag invoice as validated + call trigger BILL_VALIDATE
- *
- * @param User $user Object user that validate
- * @param string $force_number Reference to force on invoice
- * @param int $idwarehouse Id of warehouse for stock change
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int <0 if KO, =0 if nothing to do, >0 if OK
- */
- public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0)
- {
- global $conf, $langs;
+ /**
+ * Tag invoice as validated + call trigger BILL_VALIDATE
+ *
+ * @param User $user Object user that validate
+ * @param string $force_number Reference to force on invoice
+ * @param int $idwarehouse Id of warehouse for stock change
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <0 if KO, =0 if nothing to do, >0 if OK
+ */
+ public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0)
+ {
+ global $conf, $langs;
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- $now = dol_now();
+ $now = dol_now();
- $error = 0;
- dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
+ $error = 0;
+ dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
- // Force to have object complete for checks
- $this->fetch_thirdparty();
- $this->fetch_lines();
+ // Force to have object complete for checks
+ $this->fetch_thirdparty();
+ $this->fetch_lines();
- // Check parameters
- if ($this->statut > self::STATUS_DRAFT) // This is to avoid to validate twice (avoid errors on logs and stock management)
- {
- dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
- return 0;
- }
- if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier))
- {
- $langs->load("errors");
- $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
- return -1;
- }
- if (count($this->lines) <= 0)
- {
- $langs->load("errors");
- $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
- return -1;
- }
+ // Check parameters
+ if ($this->statut > self::STATUS_DRAFT) // This is to avoid to validate twice (avoid errors on logs and stock management)
+ {
+ dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
+ return 0;
+ }
+ if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier))
+ {
+ $langs->load("errors");
+ $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf"));
+ return -1;
+ }
+ if (count($this->lines) <= 0)
+ {
+ $langs->load("errors");
+ $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
+ return -1;
+ }
- $this->db->begin();
+ $this->db->begin();
- // Define new ref
- if ($force_number)
- {
- $num = $force_number;
- } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
- {
- $num = $this->getNextNumRef($this->thirdparty);
- } else {
- $num = $this->ref;
- }
- $this->newref = dol_sanitizeFileName($num);
+ // Define new ref
+ if ($force_number)
+ {
+ $num = $force_number;
+ } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life
+ {
+ $num = $this->getNextNumRef($this->thirdparty);
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = dol_sanitizeFileName($num);
- $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
- $sql .= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
- $sql .= " WHERE rowid = ".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
+ $sql .= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
+ $sql .= " WHERE rowid = ".$this->id;
- dol_syslog(get_class($this)."::validate", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
- if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
- {
- require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
- $langs->load("agenda");
+ dol_syslog(get_class($this)."::validate", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur
+ if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
+ {
+ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
+ $langs->load("agenda");
- $cpt = count($this->lines);
- for ($i = 0; $i < $cpt; $i++)
- {
- if ($this->lines[$i]->fk_product > 0)
- {
- $this->line = $this->lines[$i];
- $mouvP = new MouvementStock($this->db);
+ $cpt = count($this->lines);
+ for ($i = 0; $i < $cpt; $i++)
+ {
+ if ($this->lines[$i]->fk_product > 0)
+ {
+ $this->line = $this->lines[$i];
+ $mouvP = new MouvementStock($this->db);
$mouvP->origin = &$this;
- // We increase stock for product
- $up_ht_disc = $this->lines[$i]->pu_ht;
- if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
- if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
- else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
- if ($result < 0) { $error++; }
- unset($this->line);
- }
- }
- }
+ // We increase stock for product
+ $up_ht_disc = $this->lines[$i]->pu_ht;
+ if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU');
+ if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
+ else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num));
+ if ($result < 0) { $error++; }
+ unset($this->line);
+ }
+ }
+ }
- // Triggers call
- if (!$error && empty($notrigger))
- {
- // Call trigger
- $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
+ // Triggers call
+ if (!$error && empty($notrigger))
+ {
+ // Call trigger
+ $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
- if (!$error)
- {
- $this->oldref = $this->ref;
+ 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 = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'";
- $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->ref)."' and entity = ".$conf->entity;
- $resql = $this->db->query($sql);
- if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
+ // 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 = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$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->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref;
- $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref;
- if (!$error && file_exists($dirsource))
- {
- dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
+ // 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->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref;
+ $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$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->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$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);
- }
- }
- }
- }
- }
+ if (@rename($dirsource, $dirdest))
+ {
+ dol_syslog("Rename ok");
+ // Rename docs starting with $oldref with $newref
+ $listoffiles = dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$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 define current statut
- if (!$error)
- {
- $this->ref = $num;
- $this->statut = self::STATUS_VALIDATED;
- //$this->date_validation=$now; this is stored into log table
- }
+ // Set new ref and define current statut
+ if (!$error)
+ {
+ $this->ref = $num;
+ $this->statut = self::STATUS_VALIDATED;
+ //$this->date_validation=$now; this is stored into log table
+ }
- if (!$error)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->error = $this->db->error();
- $this->db->rollback();
- return -1;
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->error = $this->db->error();
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Set draft status
- *
- * @param User $user Object user that modify
- * @param int $idwarehouse Id warehouse to use for stock change.
- * @return int <0 if KO, >0 if OK
- */
- public function setDraft($user, $idwarehouse = -1)
- {
- // phpcs:enable
- global $conf, $langs;
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int $idwarehouse Id warehouse to use for stock change.
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $idwarehouse = -1)
+ {
+ // phpcs:enable
+ global $conf, $langs;
- $error = 0;
+ $error = 0;
- if ($this->statut == self::STATUS_DRAFT)
- {
- dol_syslog(__METHOD__." already draft status", LOG_WARNING);
- return 0;
- }
+ if ($this->statut == self::STATUS_DRAFT)
+ {
+ dol_syslog(__METHOD__." already draft status", LOG_WARNING);
+ return 0;
+ }
- dol_syslog(__METHOD__, LOG_DEBUG);
+ dol_syslog(__METHOD__, LOG_DEBUG);
- $this->db->begin();
+ $this->db->begin();
- $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
- $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
- $sql .= " WHERE rowid = ".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn";
+ $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
+ $sql .= " WHERE rowid = ".$this->id;
- $result = $this->db->query($sql);
- if ($result)
- {
- if (!$error)
- {
- $this->oldcopy = clone $this;
- }
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ if (!$error)
+ {
+ $this->oldcopy = clone $this;
+ }
- // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
- if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
- {
- require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
- $langs->load("agenda");
+ // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente
+ if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
+ {
+ require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
+ $langs->load("agenda");
- $cpt = count($this->lines);
- for ($i = 0; $i < $cpt; $i++)
- {
- if ($this->lines[$i]->fk_product > 0)
- {
- $mouvP = new MouvementStock($this->db);
- $mouvP->origin = &$this;
+ $cpt = count($this->lines);
+ for ($i = 0; $i < $cpt; $i++)
+ {
+ if ($this->lines[$i]->fk_product > 0)
+ {
+ $mouvP = new MouvementStock($this->db);
+ $mouvP->origin = &$this;
// We increase stock for product
if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
- else $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
- }
- }
- }
- // Triggers call
- if (!$error && empty($notrigger))
- {
- // Call trigger
- $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
- if ($error == 0)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->error = $this->db->error();
- $this->db->rollback();
- return -1;
- }
- }
+ else $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
+ }
+ }
+ }
+ // Triggers call
+ if (!$error && empty($notrigger))
+ {
+ // Call trigger
+ $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+ if ($error == 0)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->error = $this->db->error();
+ $this->db->rollback();
+ return -1;
+ }
+ }
- /**
- * Ajoute une ligne de facture (associe a aucun produit/service predefini)
- * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
- * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
- * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,idprod)
- * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue).
- *
- * @param string $desc Description de la ligne
- * @param double $pu Prix unitaire (HT ou TTC selon price_base_type, > 0 even for credit note)
- * @param double $txtva Force Vat rate to use, -1 for auto.
- * @param double $txlocaltax1 LocalTax1 Rate
- * @param double $txlocaltax2 LocalTax2 Rate
- * @param double $qty Quantite
- * @param int $fk_product Product/Service ID predefined
- * @param double $remise_percent Percentage discount of the line
- * @param integer $date_start Date de debut de validite du service
- * @param integer $date_end Date de fin de validite du service
- * @param string $ventil Code de ventilation comptable
- * @param int $info_bits Bits de type de lines
- * @param string $price_base_type HT ou TTC
- * @param int $type Type of line (0=product, 1=service)
- * @param int $rang Position of line
- * @param int $notrigger Disable triggers
+ /**
+ * Ajoute une ligne de facture (associe a aucun produit/service predefini)
+ * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
+ * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
+ * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,idprod)
+ * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue).
+ *
+ * @param string $desc Description de la ligne
+ * @param double $pu Prix unitaire (HT ou TTC selon price_base_type, > 0 even for credit note)
+ * @param double $txtva Force Vat rate to use, -1 for auto.
+ * @param double $txlocaltax1 LocalTax1 Rate
+ * @param double $txlocaltax2 LocalTax2 Rate
+ * @param double $qty Quantite
+ * @param int $fk_product Product/Service ID predefined
+ * @param double $remise_percent Percentage discount of the line
+ * @param integer $date_start Date de debut de validite du service
+ * @param integer $date_end Date de fin de validite du service
+ * @param string $ventil Code de ventilation comptable
+ * @param int $info_bits Bits de type de lines
+ * @param string $price_base_type HT ou TTC
+ * @param int $type Type of line (0=product, 1=service)
+ * @param int $rang Position of line
+ * @param int $notrigger Disable triggers
* @param array $array_options extrafields array
- * @param string $fk_unit Code of the unit to use. Null to use the default one
- * @param int $origin_id id origin document
+ * @param string $fk_unit Code of the unit to use. Null to use the default one
+ * @param int $origin_id id origin document
* @param double $pu_ht_devise Amount in currency
* @param string $ref_supplier Supplier ref
* @param string $special_code Special code
- * @return int >0 if OK, <0 if KO
- */
- public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product = 0, $remise_percent = 0, $date_start = '', $date_end = '', $ventil = 0, $info_bits = '', $price_base_type = 'HT', $type = 0, $rang = -1, $notrigger = false, $array_options = 0, $fk_unit = null, $origin_id = 0, $pu_ht_devise = 0, $ref_supplier = '', $special_code = '')
- {
- global $langs, $mysoc, $conf;
+ * @return int >0 if OK, <0 if KO
+ */
+ public function addline($desc, $pu, $txtva, $txlocaltax1, $txlocaltax2, $qty, $fk_product = 0, $remise_percent = 0, $date_start = '', $date_end = '', $ventil = 0, $info_bits = '', $price_base_type = 'HT', $type = 0, $rang = -1, $notrigger = false, $array_options = 0, $fk_unit = null, $origin_id = 0, $pu_ht_devise = 0, $ref_supplier = '', $special_code = '')
+ {
+ global $langs, $mysoc, $conf;
- dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG);
- include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
+ dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG);
+ include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
if ($this->statut == self::STATUS_DRAFT)
{
@@ -2551,81 +2554,81 @@ class FactureFournisseur extends CommonInvoice
}
}
- /**
- * Load an object from its id and create a new one in database
- *
- * @param User $user User that clone
- * @param int $fromid Id of object to clone
- * @param int $invertdetail Reverse sign of amounts for lines
- * @return int New id of clone
- */
- public function createFromClone(User $user, $fromid, $invertdetail = 0)
- {
- global $langs;
+ /**
+ * Load an object from its id and create a new one in database
+ *
+ * @param User $user User that clone
+ * @param int $fromid Id of object to clone
+ * @param int $invertdetail Reverse sign of amounts for lines
+ * @return int New id of clone
+ */
+ public function createFromClone(User $user, $fromid, $invertdetail = 0)
+ {
+ global $langs;
- $error = 0;
+ $error = 0;
- $object = new FactureFournisseur($this->db);
+ $object = new FactureFournisseur($this->db);
$this->db->begin();
- // Load source object
- $object->fetch($fromid);
- $object->id = 0;
- $object->statut = self::STATUS_DRAFT;
+ // Load source object
+ $object->fetch($fromid);
+ $object->id = 0;
+ $object->statut = self::STATUS_DRAFT;
- $object->fetch_thirdparty(); // We need it to recalculate VAT localtaxes according to main sale taxes and vendor
+ $object->fetch_thirdparty(); // We need it to recalculate VAT localtaxes according to main sale taxes and vendor
- // Clear fields
- $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier);
- $object->author = $user->id;
- $object->user_valid = '';
- $object->fk_facture_source = 0;
- $object->date_creation = '';
- $object->date_validation = '';
- $object->date = (empty($this->date) ? '' : $this->date);
- $object->date_echeance = '';
- $object->ref_client = '';
- $object->close_code = '';
- $object->close_note = '';
+ // Clear fields
+ $object->ref_supplier = (empty($this->ref_supplier) ? $langs->trans("CopyOf").' '.$object->ref_supplier : $this->ref_supplier);
+ $object->author = $user->id;
+ $object->user_valid = '';
+ $object->fk_facture_source = 0;
+ $object->date_creation = '';
+ $object->date_validation = '';
+ $object->date = (empty($this->date) ? '' : $this->date);
+ $object->date_echeance = '';
+ $object->ref_client = '';
+ $object->close_code = '';
+ $object->close_note = '';
- // Loop on each line of new invoice
- foreach ($object->lines as $i => $line)
- {
- if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts
- {
- unset($object->lines[$i]);
- }
- }
+ // Loop on each line of new invoice
+ foreach ($object->lines as $i => $line)
+ {
+ if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts
+ {
+ unset($object->lines[$i]);
+ }
+ }
- // Create clone
- $object->context['createfromclone'] = 'createfromclone';
- $result = $object->create($user);
+ // Create clone
+ $object->context['createfromclone'] = 'createfromclone';
+ $result = $object->create($user);
- // Other options
- if ($result < 0)
- {
- $this->error = $object->error;
- $this->errors = $object->errors;
- $error++;
- }
+ // Other options
+ if ($result < 0)
+ {
+ $this->error = $object->error;
+ $this->errors = $object->errors;
+ $error++;
+ }
- if (!$error)
- {
- }
+ if (!$error)
+ {
+ }
- unset($object->context['createfromclone']);
+ unset($object->context['createfromclone']);
- // End
- if (!$error)
- {
- $this->db->commit();
- return $object->id;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ // End
+ if (!$error)
+ {
+ $this->db->commit();
+ return $object->id;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
/**
* Create a document onto disk according to template model.
diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php
index 6222329af16..67133ed97b2 100644
--- a/htdocs/fourn/class/paiementfourn.class.php
+++ b/htdocs/fourn/class/paiementfourn.class.php
@@ -119,7 +119,6 @@ class PaiementFourn extends Paiement
$this->entity = $obj->entity;
$this->date = $this->db->jdate($obj->dp);
$this->datepaye = $this->db->jdate($obj->dp);
- $this->num_paiement = $obj->num_payment;
$this->num_payment = $obj->num_payment;
$this->bank_account = $obj->fk_account;
$this->fk_account = $obj->fk_account;
@@ -207,7 +206,7 @@ class PaiementFourn extends Paiement
$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn (';
$sql .= 'ref, entity, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, fk_user_author, fk_bank)';
$sql .= " VALUES ('".$this->db->escape($ref)."', ".$conf->entity.", '".$this->db->idate($now)."',";
- $sql .= " '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->db->escape($this->num_paiement)."', '".$this->db->escape($this->note)."', ".$user->id.", 0)";
+ $sql .= " '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', ".$user->id.", 0)";
$resql = $this->db->query($sql);
if ($resql)
@@ -256,7 +255,7 @@ class PaiementFourn extends Paiement
$outputlangs->setDefaultLang($newlang);
}
$ret = $invoice->fetch($facid); // Reload to get new records
- $result = $invoice->generateDocument($invoice->modelpdf, $outputlangs);
+ $result = $invoice->generateDocument($invoice->model_pdf, $outputlangs);
if ($result < 0) {
setEventMessages($invoice->error, $invoice->errors, 'errors');
$error++;
diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php
index bf36f29b4b9..137ddafc79d 100644
--- a/htdocs/fourn/commande/card.php
+++ b/htdocs/fourn/commande/card.php
@@ -601,7 +601,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -776,7 +776,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -813,7 +813,7 @@ if (empty($reshook))
}
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
$ret = $object->fetch($object->id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
} else {
$error++;
@@ -852,7 +852,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -918,7 +918,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
} else {
$error++;
@@ -975,7 +975,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
$action = '';
} else {
@@ -1936,53 +1936,53 @@ if ($action == 'create')
$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
// Thirdparty
$morehtmlref .= ' '.$langs->trans('ThirdParty');
- if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && !empty($usercancreate) && $action == 'edit_thirdparty') {
- $morehtmlref .= ' : ';
- $morehtmlref .= '';
- }
- if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') {
- if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) {
- $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).' ';
- }
- $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1);
- if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").' )';
- }
+ if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && !empty($usercancreate) && $action == 'edit_thirdparty') {
+ $morehtmlref .= ' : ';
+ $morehtmlref .= '';
+ }
+ if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') {
+ if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) {
+ $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).' ';
+ }
+ $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1);
+ if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherOrders").' )';
+ }
// Project
- if (!empty($conf->projet->enabled)) {
- $langs->load("projects");
- $morehtmlref .= ' '.$langs->trans('Project').' ';
- if ($usercancreate) {
- if ($action != 'classify')
- $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : ';
- if ($action == 'classify') {
- //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
- $morehtmlref .= '';
- } else {
- $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
- }
- } else {
- if (!empty($object->fk_project)) {
- $proj = new Project($db);
- $proj->fetch($object->fk_project);
- $morehtmlref .= '';
- $morehtmlref .= $proj->ref;
- $morehtmlref .= ' ';
- } else {
- $morehtmlref .= '';
- }
- }
- }
+ if (!empty($conf->projet->enabled)) {
+ $langs->load("projects");
+ $morehtmlref .= ' '.$langs->trans('Project').' ';
+ if ($usercancreate) {
+ if ($action != 'classify')
+ $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : ';
+ if ($action == 'classify') {
+ //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
+ $morehtmlref .= '';
+ } else {
+ $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
+ }
+ } else {
+ if (!empty($object->fk_project)) {
+ $proj = new Project($db);
+ $proj->fetch($object->fk_project);
+ $morehtmlref .= '';
+ $morehtmlref .= $proj->ref;
+ $morehtmlref .= ' ';
+ } else {
+ $morehtmlref .= '';
+ }
+ }
+ }
$morehtmlref .= '';
@@ -2615,7 +2615,7 @@ if ($action == 'create')
$genallowed = $usercanread;
$delallowed = $usercancreate;
- print $formfile->showdocuments('commande_fournisseur', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 0, 0, '', '', '', $object->thirdparty->default_lang);
+ print $formfile->showdocuments('commande_fournisseur', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 0, 0, '', '', '', $object->thirdparty->default_lang);
$somethingshown = $formfile->numoffiles;
// Show links to link elements
diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php
index 707e84cf87c..278896aae9b 100644
--- a/htdocs/fourn/facture/card.php
+++ b/htdocs/fourn/facture/card.php
@@ -212,7 +212,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -259,7 +259,7 @@ if (empty($reshook))
}
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
$ret = $object->fetch($object->id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}*/
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
@@ -309,7 +309,7 @@ if (empty($reshook))
}
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
$ret = $object->fetch($object->id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
}
}
@@ -440,7 +440,7 @@ if (empty($reshook))
}
$ret = $object->fetch($id); // Reload to get new records
- $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
}
}
@@ -1020,7 +1020,7 @@ if (empty($reshook))
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
$outputlangs = $langs;
- $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
if ($result < 0)
{
dol_print_error($db, $object->error, $object->errors);
@@ -1366,7 +1366,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -1470,7 +1470,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -2717,7 +2717,7 @@ if ($action == 'create')
if ($societe->localtax1_assuj == "1") $nbrows++;
if ($societe->localtax2_assuj == "1") $nbrows++;
- $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,';
+ $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
$sql .= ' c.id as paiement_type,';
$sql .= ' pf.amount,';
$sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal';
@@ -2755,7 +2755,7 @@ if ($action == 'create')
$paymentstatic->id = $objp->rowid;
$paymentstatic->datepaye = $db->jdate($objp->dp);
$paymentstatic->ref = ($objp->ref ? $objp->ref : $objp->rowid);
- $paymentstatic->num_paiement = $objp->num_paiement;
+ $paymentstatic->num_payment = $objp->num_payment;
$paymentstatic->payment_code = $objp->payment_code;
print '';
@@ -2764,7 +2764,7 @@ if ($action == 'create')
print '';
print ''.dol_print_date($db->jdate($objp->dp), 'day').' ';
print '';
- print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_paiement;
+ print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_payment;
print ' ';
if (!empty($conf->banque->enabled))
{
@@ -3196,7 +3196,7 @@ if ($action == 'create')
$urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id;
$genallowed = $usercanread;
$delallowed = $usercancreate;
- $modelpdf = (!empty($object->modelpdf) ? $object->modelpdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF));
+ $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF));
print $formfile->showdocuments('facture_fournisseur', $subdir, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang);
$somethingshown = $formfile->numoffiles;
diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php
index d5212582420..65b8936a592 100644
--- a/htdocs/fourn/facture/paiement.php
+++ b/htdocs/fourn/facture/paiement.php
@@ -301,9 +301,7 @@ if (empty($reshook))
$paiement->num_payment = GETPOST('num_paiement', 'alphanohtml');
$paiement->note_private = GETPOST('comment', 'alpha');
- $paiement->num_paiement = $paiement->num_payment; // For backward compatibility
$paiement->num_payment = $paiement->num_payment;
- $paiement->note = $paiement->note_private; // For backward compatibility
$paiement->note_private = $paiement->note_private;
if (!$error)
diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php
index 28020e40811..56a007ccbeb 100644
--- a/htdocs/fourn/paiement/card.php
+++ b/htdocs/fourn/paiement/card.php
@@ -367,7 +367,7 @@ if ($result > 0)
$urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id;
$genallowed = $user->rights->fournisseur->facture->lire;
$delallowed = $user->rights->fournisseur->facture->creer;
- $modelpdf = (!empty($object->modelpdf) ? $object->modelpdf : (empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF) ? '' : $conf->global->SUPPLIER_PAYMENT_ADDON_PDF));
+ $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF) ? '' : $conf->global->SUPPLIER_PAYMENT_ADDON_PDF));
print $formfile->showdocuments('supplier_payment', $ref, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang);
$somethingshown = $formfile->numoffiles;
diff --git a/htdocs/fourn/product/list.php b/htdocs/fourn/product/list.php
index 91cd3636bbe..53ef035c151 100644
--- a/htdocs/fourn/product/list.php
+++ b/htdocs/fourn/product/list.php
@@ -127,7 +127,7 @@ if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions =
$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
-$sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type, p.entity,";
+$sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type, p.entity, tosell, tobuy,";
$sql .= " ppf.fk_soc, ppf.ref_fourn, ppf.price as price, ppf.quantity as qty, ppf.unitprice,";
$sql .= " s.rowid as socid, s.nom as name";
// Add fields to SELECT from hooks
@@ -296,6 +296,8 @@ if ($resql)
$productstatic->ref = $objp->ref;
$productstatic->type = $objp->fk_product_type;
$productstatic->entity = $objp->entity;
+ $productstatic->status = $objp->tosell;
+ $productstatic->status_buy = $objp->tobuy;
print $productstatic->getNomUrl(1, 'supplier');
print '';
diff --git a/htdocs/holiday/card.php b/htdocs/holiday/card.php
index 3fb825c06b9..617de720ae5 100644
--- a/htdocs/holiday/card.php
+++ b/htdocs/holiday/card.php
@@ -111,152 +111,152 @@ if (empty($reshook))
header("Location: ".$backtopage);
exit;
}
- $action = '';
+ $action = '';
}
// If create a request
if ($action == 'create')
{
- // If no right to create a request
- if (!$cancreate)
- {
- $error++;
- setEventMessages($langs->trans('CantCreateCP'), null, 'errors');
- $action = 'request';
- }
+ // If no right to create a request
+ if (!$cancreate)
+ {
+ $error++;
+ setEventMessages($langs->trans('CantCreateCP'), null, 'errors');
+ $action = 'request';
+ }
- if (!$error)
- {
- $object = new Holiday($db);
+ if (!$error)
+ {
+ $object = new Holiday($db);
- $db->begin();
+ $db->begin();
- $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'));
- $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'));
- $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1);
- $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1);
- $starthalfday = GETPOST('starthalfday');
- $endhalfday = GETPOST('endhalfday');
- $type = GETPOST('type');
- $halfday = 0;
- if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday = 2;
- elseif ($starthalfday == 'afternoon') $halfday = -1;
- elseif ($endhalfday == 'morning') $halfday = 1;
+ $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'));
+ $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'));
+ $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1);
+ $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1);
+ $starthalfday = GETPOST('starthalfday');
+ $endhalfday = GETPOST('endhalfday');
+ $type = GETPOST('type');
+ $halfday = 0;
+ if ($starthalfday == 'afternoon' && $endhalfday == 'morning') $halfday = 2;
+ elseif ($starthalfday == 'afternoon') $halfday = -1;
+ elseif ($endhalfday == 'morning') $halfday = 1;
- $valideur = GETPOST('valideur', 'int');
- $description = trim(GETPOST('description', 'none'));
+ $valideur = GETPOST('valideur', 'int');
+ $description = trim(GETPOST('description', 'none'));
- // If no type
- if ($type <= 0)
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
- $error++;
- $action = 'create';
- }
+ // If no type
+ if ($type <= 0)
+ {
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
+ $error++;
+ $action = 'create';
+ }
- // If no start date
- if (empty($date_debut))
- {
- setEventMessages($langs->trans("NoDateDebut"), null, 'errors');
- $error++;
- $action = 'create';
- }
- // If no end date
- if (empty($date_fin))
- {
- setEventMessages($langs->trans("NoDateFin"), null, 'errors');
- $error++;
- $action = 'create';
- }
- // If start date after end date
- if ($date_debut > $date_fin)
- {
- setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors');
- $error++;
- $action = 'create';
- }
+ // If no start date
+ if (empty($date_debut))
+ {
+ setEventMessages($langs->trans("NoDateDebut"), null, 'errors');
+ $error++;
+ $action = 'create';
+ }
+ // If no end date
+ if (empty($date_fin))
+ {
+ setEventMessages($langs->trans("NoDateFin"), null, 'errors');
+ $error++;
+ $action = 'create';
+ }
+ // If start date after end date
+ if ($date_debut > $date_fin)
+ {
+ setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors');
+ $error++;
+ $action = 'create';
+ }
- // Check if there is already holiday for this period
- $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday);
- if (!$verifCP)
- {
- setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
- $error++;
- $action = 'create';
- }
+ // Check if there is already holiday for this period
+ $verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday);
+ if (!$verifCP)
+ {
+ setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
+ $error++;
+ $action = 'create';
+ }
- // If there is no Business Days within request
- $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday);
- if ($nbopenedday < 0.5)
- {
- setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors');
- $error++;
- $action = 'create';
- }
+ // If there is no Business Days within request
+ $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday);
+ if ($nbopenedday < 0.5)
+ {
+ setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors');
+ $error++;
+ $action = 'create';
+ }
- // If no validator designated
- if ($valideur < 1)
- {
- setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors');
- $error++;
- }
+ // If no validator designated
+ if ($valideur < 1)
+ {
+ setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors');
+ $error++;
+ }
- $result = 0;
+ $result = 0;
- if (!$error)
- {
- $object->fk_user = $fuserid;
- $object->description = $description;
- $object->fk_validator = $valideur;
- $object->fk_type = $type;
- $object->date_debut = $date_debut;
- $object->date_fin = $date_fin;
- $object->halfday = $halfday;
+ if (!$error)
+ {
+ $object->fk_user = $fuserid;
+ $object->description = $description;
+ $object->fk_validator = $valideur;
+ $object->fk_type = $type;
+ $object->date_debut = $date_debut;
+ $object->date_fin = $date_fin;
+ $object->halfday = $halfday;
- $result = $object->create($user);
- if ($result <= 0)
- {
- setEventMessages($object->error, $object->errors, 'errors');
- $error++;
- }
- }
+ $result = $object->create($user);
+ if ($result <= 0)
+ {
+ setEventMessages($object->error, $object->errors, 'errors');
+ $error++;
+ }
+ }
- // If no SQL error we redirect to the request card
- if (!$error)
- {
+ // If no SQL error we redirect to the request card
+ if (!$error)
+ {
$db->commit();
- header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
- exit;
- } else {
- $db->rollback();
- }
- }
+ header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
+ exit;
+ } else {
+ $db->rollback();
+ }
+ }
}
if ($action == 'update' && GETPOSTISSET('savevalidator') && !empty($user->rights->holiday->approve))
{
- $object->fetch($id);
+ $object->fetch($id);
- $object->oldcopy = dol_clone($object);
+ $object->oldcopy = dol_clone($object);
- $object->fk_validator = GETPOST('valideur', 'int');
+ $object->fk_validator = GETPOST('valideur', 'int');
- if ($object->fk_validator != $object->oldcopy->fk_validator)
- {
- $verif = $object->update($user);
+ if ($object->fk_validator != $object->oldcopy->fk_validator)
+ {
+ $verif = $object->update($user);
- if ($verif <= 0)
- {
- setEventMessages($object->error, $object->errors, 'warnings');
- $action = 'editvalidator';
- } else {
- header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
- exit;
- }
- }
+ if ($verif <= 0)
+ {
+ setEventMessages($object->error, $object->errors, 'warnings');
+ $action = 'editvalidator';
+ } else {
+ header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
+ exit;
+ }
+ }
- $action = '';
+ $action = '';
}
if ($action == 'update' && !GETPOSTISSET('savevalidator'))
diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php
index ce4c74d786a..d2aa54664cc 100644
--- a/htdocs/holiday/class/holiday.class.php
+++ b/htdocs/holiday/class/holiday.class.php
@@ -1178,7 +1178,11 @@ class Holiday extends CommonObject
$result = '';
- $label = $langs->trans("Show").': '.$this->ref;
+ $label = img_picto('', $this->picto).' '.$langs->trans("Holiday").' ';
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+ if (isset($this->statut)) {
+ $label .= ''.$langs->trans("Status").": ".$this->getLibStatut(5);
+ }
$url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
@@ -1269,20 +1273,22 @@ class Holiday extends CommonObject
$nb = count($name) + 1;
// Select HTML
- $statut = ''."\n";
- $statut .= ' '."\n";
+ $out = ''."\n";
+ $out .= ' '."\n";
// Boucle des statuts
for ($i = 1; $i < $nb; $i++) {
if ($i == $selected) {
- $statut .= ''.$langs->trans($name[$i - 1]).' '."\n";
+ $out .= ''.$langs->trans($name[$i - 1]).' '."\n";
} else {
- $statut .= ''.$langs->trans($name[$i - 1]).' '."\n";
+ $out .= ''.$langs->trans($name[$i - 1]).' '."\n";
}
}
- $statut .= ' '."\n";
- print $statut;
+ $out .= ' '."\n";
+ $out .= ajax_combobox($htmlname);
+
+ print $out;
}
/**
diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php
index 5a4f782deac..e5d20b9f12f 100644
--- a/htdocs/holiday/list.php
+++ b/htdocs/holiday/list.php
@@ -106,7 +106,7 @@ $search_month_end = GETPOST('search_month_end', 'int');
$search_year_end = GETPOST('search_year_end', 'int');
$search_employee = GETPOST('search_employee', 'int');
$search_valideur = GETPOST('search_valideur', 'int');
-$search_statut = GETPOST('search_statut', 'int');
+$search_status = GETPOST('search_status', 'int');
$search_type = GETPOST('search_type', 'int');
// Initialize technical objects
@@ -182,7 +182,7 @@ if (empty($reshook))
$search_year_end = "";
$search_employee = "";
$search_valideur = "";
- $search_statut = "";
+ $search_status = "";
$search_type = '';
$toselect = '';
$search_array_options = array();
@@ -253,7 +253,7 @@ $sql .= " cp.description,";
$sql .= " cp.date_debut,";
$sql .= " cp.date_fin,";
$sql .= " cp.halfday,";
-$sql .= " cp.statut,";
+$sql .= " cp.statut as status,";
$sql .= " cp.fk_validator,";
$sql .= " cp.date_valid,";
$sql .= " cp.fk_user_valid,";
@@ -268,7 +268,7 @@ $sql .= " uu.firstname as user_firstname,";
$sql .= " uu.admin as user_admin,";
$sql .= " uu.email as user_email,";
$sql .= " uu.login as user_login,";
-$sql .= " uu.statut as user_statut,";
+$sql .= " uu.statut as user_status,";
$sql .= " uu.photo as user_photo,";
$sql .= " ua.lastname as validator_lastname,";
@@ -276,7 +276,7 @@ $sql .= " ua.firstname as validator_firstname,";
$sql .= " ua.admin as validator_admin,";
$sql .= " ua.email as validator_email,";
$sql .= " ua.login as validator_login,";
-$sql .= " ua.statut as validator_statut,";
+$sql .= " ua.statut as validator_status,";
$sql .= " ua.photo as validator_photo";
// Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) {
@@ -314,8 +314,8 @@ if (!empty($search_type) && $search_type != -1) {
$sql .= ' AND cp.fk_type IN ('.$db->escape($search_type).')';
}
// Status
-if (!empty($search_statut) && $search_statut != -1) {
- $sql .= " AND cp.statut = '".$db->escape($search_statut)."'\n";
+if (!empty($search_status) && $search_status != -1) {
+ $sql .= " AND cp.statut = '".$db->escape($search_status)."'\n";
}
if (empty($user->rights->holiday->read_all)) $sql .= ' AND cp.fk_user IN ('.join(',', $childids).')';
@@ -371,7 +371,7 @@ if ($resql)
if ($search_employee > 0) $param .= '&search_employee='.urlencode($search_employee);
if ($search_valideur > 0) $param .= '&search_valideur='.urlencode($search_valideur);
if ($search_type > 0) $param .= '&search_type='.urlencode($search_type);
- if ($search_statut > 0) $param .= '&search_statut='.urlencode($search_statut);
+ if ($search_status > 0) $param .= '&search_status='.urlencode($search_status);
// Add $param from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
@@ -504,7 +504,7 @@ if ($resql)
}
print '';
- print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, $include, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200');
+ print $form->select_dolusers($search_employee, "search_employee", 1, "", $disabled, $include, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth150');
print ' ';
}
@@ -519,7 +519,7 @@ if ($resql)
$valideurobjects = $validator->listUsersForGroup($excludefilter);
$valideurarray = array();
foreach ($valideurobjects as $val) $valideurarray[$val->id] = $val->id;
- print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth200');
+ print $form->select_dolusers($search_valideur, "search_valideur", 1, "", 0, $valideurarray, '', 0, 0, 0, $morefilter, 0, '', 'maxwidth150');
print '';
} else {
print ' ';
@@ -541,7 +541,7 @@ if ($resql)
//$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')':'');
$arraytypeleaves[$val['rowid']] = $labeltoshow;
}
- print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1);
+ print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1, 0, 0, '', 0, 0, 0, '', '', 1);
}
print '';
}
@@ -599,7 +599,7 @@ if ($resql)
if (!empty($arrayfields['cp.statut']['checked']))
{
print '';
- $object->selectStatutCP($search_statut, 'search_statut');
+ $object->selectStatutCP($search_status, 'search_status');
print ' ';
}
@@ -616,7 +616,7 @@ if ($resql)
if (!empty($arrayfields['cp.fk_user']['checked'])) print_liste_field_titre($arrayfields['cp.fk_user']['label'], $_SERVER["PHP_SELF"], "cp.fk_user", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['cp.fk_validator']['checked'])) print_liste_field_titre($arrayfields['cp.fk_validator']['label'], $_SERVER["PHP_SELF"], "cp.fk_validator", "", $param, '', $sortfield, $sortorder);
if (!empty($arrayfields['cp.fk_type']['checked'])) print_liste_field_titre($arrayfields['cp.fk_type']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
- if (!empty($arrayfields['duration']['checked'])) print_liste_field_titre($arrayfields['duration']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right ');
+ if (!empty($arrayfields['duration']['checked'])) print_liste_field_titre($arrayfields['duration']['label'], $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'right maxwidth100');
if (!empty($arrayfields['cp.date_debut']['checked'])) print_liste_field_titre($arrayfields['cp.date_debut']['label'], $_SERVER["PHP_SELF"], "cp.date_debut", "", $param, '', $sortfield, $sortorder, 'center ');
if (!empty($arrayfields['cp.date_fin']['checked'])) print_liste_field_titre($arrayfields['cp.date_fin']['label'], $_SERVER["PHP_SELF"], "cp.date_fin", "", $param, '', $sortfield, $sortorder, 'center ');
// Extra fields
@@ -656,6 +656,7 @@ if ($resql)
// Leave request
$holidaystatic->id = $obj->rowid;
$holidaystatic->ref = ($obj->ref ? $obj->ref : $obj->rowid);
+ $holidaystatic->statut = $obj->status;
// User
$userstatic->id = $obj->fk_user;
@@ -664,7 +665,7 @@ if ($resql)
$userstatic->admin = $obj->user_admin;
$userstatic->email = $obj->user_email;
$userstatic->login = $obj->user_login;
- $userstatic->statut = $obj->user_statut;
+ $userstatic->statut = $obj->user_status;
$userstatic->photo = $obj->user_photo;
// Validator
@@ -674,7 +675,7 @@ if ($resql)
$approbatorstatic->admin = $obj->validator_admin;
$approbatorstatic->email = $obj->validator_email;
$approbatorstatic->login = $obj->validator_login;
- $approbatorstatic->statut = $obj->validator_statut;
+ $approbatorstatic->statut = $obj->validator_status;
$approbatorstatic->photo = $obj->validator_photo;
$date = $obj->date_create;
@@ -694,12 +695,12 @@ if ($resql)
}
if (!empty($arrayfields['cp.fk_user']['checked']))
{
- print ''.$userstatic->getNomUrl(-1, 'leave').' ';
+ print ''.$userstatic->getNomUrl(-1, 'leave').' ';
if (!$i) $totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.fk_validator']['checked']))
{
- print ''.$approbatorstatic->getNomUrl(-1).' ';
+ print ''.$approbatorstatic->getNomUrl(-1).' ';
if (!$i) $totalarray['nbfield']++;
}
if (!empty($arrayfields['cp.fk_type']['checked']))
@@ -722,7 +723,7 @@ if ($resql)
{
print '';
print dol_print_date($db->jdate($obj->date_debut), 'day');
- print ' ('.$langs->trans($listhalfday[$starthalfday]).') ';
+ print ' ('.$langs->trans($listhalfday[$starthalfday]).') ';
print ' ';
if (!$i) $totalarray['nbfield']++;
}
@@ -730,7 +731,7 @@ if ($resql)
{
print '';
print dol_print_date($db->jdate($obj->date_fin), 'day');
- print ' ('.$langs->trans($listhalfday[$endhalfday]).') ';
+ print ' ('.$langs->trans($listhalfday[$endhalfday]).') ';
print ' ';
if (!$i) $totalarray['nbfield']++;
}
@@ -755,7 +756,7 @@ if ($resql)
}
if (!empty($arrayfields['cp.statut']['checked']))
{
- print ''.$holidaystatic->LibStatut($obj->statut, 5).' ';
+ print ''.$holidaystatic->getLibStatut(5).' ';
if (!$i) $totalarray['nbfield']++;
}
diff --git a/htdocs/imports/class/import.class.php b/htdocs/imports/class/import.class.php
index 12dfc5d19e9..72d1eb16f66 100644
--- a/htdocs/imports/class/import.class.php
+++ b/htdocs/imports/class/import.class.php
@@ -171,7 +171,7 @@ class Import
// Sql request to run after import
$this->array_import_run_sql_after[$i] = (isset($module->import_run_sql_after_array[$r]) ? $module->import_run_sql_after_array[$r] : '');
// Module
- $this->array_import_module[$i] = $module;
+ $this->array_import_module[$i] = array('position_of_profile'=>($module->module_position.'-'.$module->import_code[$r]), 'module'=>$module);
dol_syslog("Import loaded for module ".$modulename." with index ".$i.", dataset=".$module->import_code[$r].", nb of fields=".count($module->import_fields_array[$r]));
$i++;
diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php
index 1ca191f5124..d886796f7b0 100644
--- a/htdocs/imports/import.php
+++ b/htdocs/imports/import.php
@@ -346,17 +346,17 @@ if ($step == 1 || !$datatoimport)
if (count($objimport->array_import_module))
{
- $sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'module_position', 'asc', 0, 0, 1);
+ $sortedarrayofmodules = dol_sort_array($objimport->array_import_module, 'position_of_profile', 'asc', 0, 0, 1);
foreach ($sortedarrayofmodules as $key => $value)
{
- //var_dump($objimport->array_import_code[$key]);
+ //var_dump($key.' '.$value['position_of_profile'].' '.$value['import_code'].' '.$objimport->array_import_module[$key]['module']->getName().' '.$objimport->array_import_code[$key]);
print ' ';
- $titleofmodule = $objimport->array_import_module[$key]->getName();
+ $titleofmodule = $objimport->array_import_module[$key]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[$key], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService");
print $titleofmodule;
print ' ';
- print img_object($objimport->array_import_module[$key]->getName(), $objimport->array_import_icon[$key]).' ';
+ print img_object($objimport->array_import_module[$key]['module']->getName(), $objimport->array_import_icon[$key]).' ';
print $objimport->array_import_label[$key];
print ' ';
if ($objimport->array_import_perms[$key])
@@ -400,7 +400,7 @@ if ($step == 2 && $datatoimport)
// Module
print ' '.$langs->trans("Module").' ';
print '';
- $titleofmodule = $objimport->array_import_module[0]->getName();
+ $titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService");
print $titleofmodule;
@@ -409,7 +409,7 @@ if ($step == 2 && $datatoimport)
// Lot de donnees a importer
print ' '.$langs->trans("DatasetToImport").' ';
print '';
- print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' ';
+ print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' ';
print $objimport->array_import_label[0];
print ' ';
@@ -490,7 +490,7 @@ if ($step == 3 && $datatoimport)
// Module
print ''.$langs->trans("Module").' ';
print '';
- $titleofmodule = $objimport->array_import_module[0]->getName();
+ $titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService");
print $titleofmodule;
@@ -499,7 +499,7 @@ if ($step == 3 && $datatoimport)
// Lot de donnees a importer
print ' '.$langs->trans("DatasetToImport").' ';
print '';
- print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' ';
+ print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' ';
print $objimport->array_import_label[0];
print ' ';
@@ -773,7 +773,7 @@ if ($step == 4 && $datatoimport)
// Module
print ''.$langs->trans("Module").' ';
print '';
- $titleofmodule = $objimport->array_import_module[0]->getName();
+ $titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService");
print $titleofmodule;
@@ -782,7 +782,7 @@ if ($step == 4 && $datatoimport)
// Lot de donnees a importer
print ' '.$langs->trans("DatasetToImport").' ';
print '';
- print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' ';
+ print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' ';
print $objimport->array_import_label[0];
print ' ';
@@ -1239,7 +1239,7 @@ if ($step == 5 && $datatoimport)
// Module
print ''.$langs->trans("Module").' ';
print '';
- $titleofmodule = $objimport->array_import_module[0]->getName();
+ $titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService");
print $titleofmodule;
@@ -1248,7 +1248,7 @@ if ($step == 5 && $datatoimport)
// Lot de donnees a importer
print ' '.$langs->trans("DatasetToImport").' ';
print '';
- print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' ';
+ print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' ';
print $objimport->array_import_label[0];
print ' ';
@@ -1662,7 +1662,7 @@ if ($step == 6 && $datatoimport)
// Module
print ''.$langs->trans("Module").' ';
print '';
- $titleofmodule = $objimport->array_import_module[0]->getName();
+ $titleofmodule = $objimport->array_import_module[0]['module']->getName();
// Special cas for import common to module/services
if (in_array($objimport->array_import_code[0], array('produit_supplierprices', 'produit_multiprice', 'produit_languages'))) $titleofmodule = $langs->trans("ProductOrService");
print $titleofmodule;
@@ -1671,7 +1671,7 @@ if ($step == 6 && $datatoimport)
// Lot de donnees a importer
print ' '.$langs->trans("DatasetToImport").' ';
print '';
- print img_object($objimport->array_import_module[0]->getName(), $objimport->array_import_icon[0]).' ';
+ print img_object($objimport->array_import_module[0]['module']->getName(), $objimport->array_import_icon[0]).' ';
print $objimport->array_import_label[0];
print ' ';
diff --git a/htdocs/imports/index.php b/htdocs/imports/index.php
index 365df6086f4..bc68b53cfd0 100644
--- a/htdocs/imports/index.php
+++ b/htdocs/imports/index.php
@@ -45,69 +45,18 @@ llxHeader('', $langs->trans("ImportArea"), 'EN:Module_Imports_En|FR:Module_Impor
print load_fiche_titre($langs->trans("ImportArea"));
print $langs->trans("FormatedImportDesc1").' ';
-//print $langs->trans("FormatedImportDesc2").' ';
print ' ';
-//print '';
-
-
-// List of import set
-/*
-print '
';
-print '
';
-print '';
-print ''.$langs->trans("Module").' ';
-print ''.$langs->trans("ImportableDatas").' ';
-//print ' ';
-print ' ';
-
-if (count($import->array_import_code))
-{
- foreach ($import->array_import_code as $key => $value)
- {
- print '';
- print img_object($import->array_import_module[$key]->getName(),$import->array_import_module[$key]->picto).' ';
- print $import->array_import_module[$key]->getName();
- print ' ';
- $string=$langs->trans($import->array_import_label[$key]);
- print ($string!=$import->array_import_label[$key]?$string:$import->array_import_label[$key]);
- print ' ';
- // print '';
- // print ''.img_picto($langs->trans("NewImport"),'filenew').' ';
- // print ' ';
- print ' ';
-
- }
-}
-else
-{
- print ''.$langs->trans("NoImportableData").' ';
-}
-print '
';
-print '
';
-print '
';
-*/
-
print '
';
if (count($import->array_import_code))
{
- //if ($user->rights->import->run)
- //{
print dolGetButtonTitle($langs->trans('NewImport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/imports/import.php?leftmenu=import');
- //}
- //else
- //{
- // print '
'.$langs->trans("NewImport").' ';
- //}
}
print '
';
print '
';
-//print '
';
-
-
// List of available import format
print '
';
print '
';
@@ -136,8 +85,6 @@ print '
';
print '
';
-//print '
';
-
// End of page
llxFooter();
$db->close();
diff --git a/htdocs/index.php b/htdocs/index.php
index 307b356d522..87f33851b92 100644
--- a/htdocs/index.php
+++ b/htdocs/index.php
@@ -294,7 +294,10 @@ if (empty($user->socid) && empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS))
$boxstatItem = '';
$class = $classes[$val];
// Search in cache if load_state_board is already realized
- if (!isset($boardloaded[$class]) || !is_object($boardloaded[$class]))
+ $classkeyforcache = $class;
+ if ($classkeyforcache == 'ProductService') $classkeyforcache = 'Product'; // ProductService use same load_state_board than Product
+
+ if (!isset($boardloaded[$classkeyforcache]) || !is_object($boardloaded[$classkeyforcache]))
{
include_once $includes[$val]; // Loading a class cost around 1Mb
@@ -302,7 +305,7 @@ if (empty($user->socid) && empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS))
$board->load_state_board();
$boardloaded[$class] = $board;
} else {
- $board = $boardloaded[$class];
+ $board = $boardloaded[$classkeyforcache];
}
$langs->load(empty($langfile[$val]) ? $val : $langfile[$val]);
@@ -450,14 +453,14 @@ if (empty($conf->global->MAIN_DISABLE_GLOBAL_WORKBOARD)) {
if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->approve) {
include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
$board = new ExpenseReport($db);
- $dashboardlines[$board->element . '_toapprove'] = $board->load_board($user, 'toapprove');
+ $dashboardlines[$board->element.'_toapprove'] = $board->load_board($user, 'toapprove');
}
// Number of expense reports to pay
if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->to_paid) {
include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
$board = new ExpenseReport($db);
- $dashboardlines[$board->element . '_topay'] = $board->load_board($user, 'topay');
+ $dashboardlines[$board->element.'_topay'] = $board->load_board($user, 'topay');
}
// Number of holidays to approve
diff --git a/htdocs/install/mysql/data/llx_c_tva.sql b/htdocs/install/mysql/data/llx_c_tva.sql
index e44a1d42995..831097ebf48 100644
--- a/htdocs/install/mysql/data/llx_c_tva.sql
+++ b/htdocs/install/mysql/data/llx_c_tva.sql
@@ -295,13 +295,14 @@ insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (21
insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (2132, 213, '5','0','VAT 5%',1);
-- TUNISIA (id country=10)
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (101,10, '0','0','VAT Rate 0', 1, 1, '4', 0, 0);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (102,10, '12','0','VAT 12%',1, 1, '4', 0, 0);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (103,10, '18','0','VAT 18%',1, 1, '4', 0, 0);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (104,10, '7.5','0','VAT 6% Majoré à 25% (7.5%)',1, 1, '4', 0, 0);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (105,10, '15','0','VAT 12% Majoré à 25% (15%)',1, 1, '4', 0, 0);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (106,10, '22.5','0','VAT 18% Majoré à 25% (22.5%)',1, 1, '4', 0, 0);
-insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (107,10, '6','0','VAT 6%', 1, 1, '4', 0, 0);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (101,10, '0','0','VAT Rate 0',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (102,10, '12','0','VAT 12%',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (103,10, '18','0','VAT 18%',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (104,10, '7.5','0','VAT 6% Majoré à 25% (7.5%)',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (105,10, '15','0','VAT 12% Majoré à 25% (15%)',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (106,10, '22.5','0','VAT 18% Majoré à 25% (22.5%)',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (107,10, '6','0','VAT 6%', 1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active,localtax1,localtax1_type,localtax2,localtax2_type) values (107,10,'18.18','0','VAT 18%+FODEC', 1, 1, '4', 0, 0);
-- UKRAINE (id country=226)
INSERT INTO llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (2261,226, '0','0','VAT Rate 0',1);
diff --git a/htdocs/install/mysql/migration/12.0.0-13.0.0.sql b/htdocs/install/mysql/migration/12.0.0-13.0.0.sql
index a3c0b78510c..e3a1d1807bc 100644
--- a/htdocs/install/mysql/migration/12.0.0-13.0.0.sql
+++ b/htdocs/install/mysql/migration/12.0.0-13.0.0.sql
@@ -318,3 +318,7 @@ ALTER TABLE llx_facturedet ADD COLUMN ref_ext varchar(255) AFTER multicurrency_t
ALTER TABLE llx_c_ticket_category ADD COLUMN fk_parent integer DEFAULT 0 NOT NULL;
ALTER TABLE llx_c_ticket_category ADD COLUMN force_severity varchar(32) NULL;
+ALTER TABLE llx_expensereport_ik ADD COLUMN ikoffset double DEFAULT 0 NOT NULL;
+
+ALTER TABLE llx_paiement ADD COLUMN ref_ext varchar(255) AFTER ref;
+
diff --git a/htdocs/install/mysql/tables/llx_c_ticket_category.sql b/htdocs/install/mysql/tables/llx_c_ticket_category.sql
index 1e98de92d3b..58126633ce1 100644
--- a/htdocs/install/mysql/tables/llx_c_ticket_category.sql
+++ b/htdocs/install/mysql/tables/llx_c_ticket_category.sql
@@ -24,7 +24,7 @@ create table llx_c_ticket_category
label varchar(128) NOT NULL,
active integer DEFAULT 1,
use_default integer DEFAULT 1,
- fk_parent integer DEFAULT 0 NOT NULL; -- Parent group
+ fk_parent integer DEFAULT 0 NOT NULL, -- Parent group
force_severity varchar(32) NULL, -- To force the severity if we choosed this category
description varchar(255)
)ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_expensereport_ik.sql b/htdocs/install/mysql/tables/llx_expensereport_ik.sql
index 3e767a8c396..ddc7fa4d3c7 100644
--- a/htdocs/install/mysql/tables/llx_expensereport_ik.sql
+++ b/htdocs/install/mysql/tables/llx_expensereport_ik.sql
@@ -25,6 +25,6 @@ CREATE TABLE IF NOT EXISTS llx_expensereport_ik (
fk_c_exp_tax_cat integer DEFAULT 0 NOT NULL,
fk_range integer DEFAULT 0 NOT NULL,
coef double DEFAULT 0 NOT NULL,
- ikoffset double DEFAULT 0 NOT NULL,
+ ikoffset double DEFAULT 0 NOT NULL,
active integer DEFAULT 1
)ENGINE=innodb;
diff --git a/htdocs/install/mysql/tables/llx_paiement.sql b/htdocs/install/mysql/tables/llx_paiement.sql
index d19d38312a4..dabe261798b 100644
--- a/htdocs/install/mysql/tables/llx_paiement.sql
+++ b/htdocs/install/mysql/tables/llx_paiement.sql
@@ -22,6 +22,7 @@ create table llx_paiement
(
rowid integer AUTO_INCREMENT PRIMARY KEY,
ref varchar(30) NULL, -- payment reference number
+ ref_ext varchar(255) NULL, -- payment external reference
entity integer DEFAULT 1 NOT NULL, -- Multi company id
datec datetime, -- date de creation
tms timestamp,
diff --git a/htdocs/install/mysql/tables/llx_product_attribute.sql b/htdocs/install/mysql/tables/llx_product_attribute.sql
index c81d122d9bb..362c104b95c 100644
--- a/htdocs/install/mysql/tables/llx_product_attribute.sql
+++ b/htdocs/install/mysql/tables/llx_product_attribute.sql
@@ -23,7 +23,7 @@ CREATE TABLE llx_product_attribute
(
rowid INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
ref VARCHAR(255) NOT NULL,
- ref_ext VARCHAR(255) NOT NULL,
+ ref_ext VARCHAR(255) NULL,
label VARCHAR(255) NOT NULL,
rang INT DEFAULT 0 NOT NULL,
entity INT DEFAULT 1 NOT NULL
diff --git a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.key.sql b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.key.sql
index 93fb231dc35..eae967704b4 100644
--- a/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.key.sql
+++ b/htdocs/install/mysql/tables/llx_recruitment_recruitmentcandidature.key.sql
@@ -23,5 +23,5 @@ ALTER TABLE llx_recruitment_recruitmentcandidature ADD INDEX idx_recruitment_rec
ALTER TABLE llx_recruitment_recruitmentcandidature ADD UNIQUE INDEX uk_recruitmentcandidature_email_msgid(email_msgid);
---ALTER TABLE llx_recruitment_recruitmentcandidature ADD CONSTRAINT llx_mymodule_myobject_fk_field FOREIGN KEY (fk_field) REFERENCES llx_mymodule_myotherobject(rowid);
+-- ALTER TABLE llx_recruitment_recruitmentcandidature ADD CONSTRAINT llx_mymodule_myobject_fk_field FOREIGN KEY (fk_field) REFERENCES llx_mymodule_myotherobject(rowid);
diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang
index 5e59996a2c5..464823810b2 100644
--- a/htdocs/langs/en_US/accountancy.lang
+++ b/htdocs/langs/en_US/accountancy.lang
@@ -89,6 +89,8 @@ SubledgerAccount=Subledger account
SubledgerAccountLabel=Subledger account label
ShowAccountingAccount=Show accounting account
ShowAccountingJournal=Show accounting journal
+ShowAccountingAccountInBookKeeping=Show accounting account in ledger
+ShowAccountingAccountInBookKeepingByAccount=Show accounting account in ledger by account
AccountAccountingSuggest=Accounting account suggested
MenuDefaultAccounts=Default accounts
MenuBankAccounts=Bank accounts
@@ -170,6 +172,8 @@ ACCOUNTING_ACCOUNT_SUSPENSE=Accounting account of wait
DONATION_ACCOUNTINGACCOUNT=Accounting account to register donations
ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT=Accounting account to register subscriptions
+ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT=Accounting account by default to register customer deposit
+
ACCOUNTING_PRODUCT_BUY_ACCOUNT=Accounting account by default for the bought products (used if not defined in the product sheet)
ACCOUNTING_PRODUCT_BUY_INTRA_ACCOUNT=Accounting account by default for the bought products in EEC (used if not defined in the product sheet)
ACCOUNTING_PRODUCT_BUY_EXPORT_ACCOUNT=Accounting account by default for the bought products and imported out of EEC (used if not defined in the product sheet)
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index 7bf73f8e458..c830abf0b45 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -479,7 +479,10 @@ ModuleCompanyCodeCustomerDigitaria=%s followed by the truncated customer name by
ModuleCompanyCodeSupplierDigitaria=%s followed by the truncated supplier name by the number of characters: %s for the supplier accounting code.
Use3StepsApproval=By default, Purchase Orders need to be created and approved by 2 different users (one step/user to create and one step/user to approve. Note that if user has both permission to create and approve, one step/user will be enough). You can ask with this option to introduce a third step/user approval, if amount is higher than a dedicated value (so 3 steps will be necessary: 1=validation, 2=first approval and 3=second approval if amount is enough). Set this to empty if one approval (2 steps) is enough, set it to a very low value (0.1) if a second approval (3 steps) is always required.
UseDoubleApproval=Use a 3 steps approval when amount (without tax) is higher than...
-WarningPHPMail=WARNING: It is often better to setup outgoing emails to use the email server of your provider instead of the default setup. Some email providers (like Yahoo) do not allow you to send an email from another server than their own server. Your current setup uses the server of the application to send email and not the server of your email provider, so some recipients (the one compatible with the restrictive DMARC protocol), will ask your email provider if they can accept your email and some email providers (like Yahoo) may respond "no" because the server is not theirs, so few of your sent Emails may not be accepted (be careful also of your email provider's sending quota). If your Email provider (like Yahoo) has this restriction, you must change Email setup to choose the other method "SMTP server" and enter the SMTP server and credentials provided by your Email provider.
+WarningPHPMail=WARNING: The setup to send emails from the application is using the default generic setup. It is often better to setup outgoing emails to use the email server of your Email Service Provider instead of the default setup for several reasons:
+WarningPHPMailA=- Using the server of the Email Service Provider increase the trustability of your email, so it increase the deliverablity without being flagging as SPAM
+WarningPHPMailB=- Some Email Service Providers (like Yahoo) do not allow you to send an email from another server than their own server. Your current setup uses the server of the application to send email and not the server of your email provider, so some recipients (the one compatible with the restrictive DMARC protocol), will ask your email provider if they can accept your email and some email providers (like Yahoo) may respond "no" because the server is not theirs, so few of your sent Emails may not be accepted for delivery (be careful also of your email provider's sending quota).
+WarningPHPMailC=- Using the SMTP server of your own Email Service Provider to send emails is also interesting so all emails sent from application will also be saved into your "Sent" directory of your mailbox.
WarningPHPMail2=If your email SMTP provider need to restrict email client to some IP addresses (very rare), this is the IP address of the mail user agent (MUA) for your ERP CRM application: %s .
WarningPHPMailSPF=If the domain name in your sender email address is protected by SPF (ask you email provider), you must include the following IPs in the SPF record of the DNS of your domain: %s .
ClickToShowDescription=Click to show description
@@ -672,7 +675,7 @@ Module63000Name=Resources
Module63000Desc=Manage resources (printers, cars, rooms, ...) for allocating to events
Permission11=Read customer invoices
Permission12=Create/modify customer invoices
-Permission13=Unvalidate customer invoices
+Permission13=Invalidate customer invoices
Permission14=Validate customer invoices
Permission15=Send customer invoices by email
Permission16=Create payments for customer invoices
@@ -689,6 +692,7 @@ Permission32=Create/modify products
Permission34=Delete products
Permission36=See/manage hidden products
Permission38=Export products
+Permission39=Ignore minimum price
Permission41=Read projects and tasks (shared project and projects I'm contact for). Can also enter time consumed, for me or my hierarchy, on assigned tasks (Timesheet)
Permission42=Create/modify projects (shared project and projects I'm contact for). Can also create tasks and assign users to project and tasks
Permission44=Delete projects (shared project and projects I'm contact for)
@@ -697,6 +701,9 @@ Permission61=Read interventions
Permission62=Create/modify interventions
Permission64=Delete interventions
Permission67=Export interventions
+Permission68=Send interventions by email
+Permission69=Validate interventions
+Permission70=Invalidate interventions
Permission71=Read members
Permission72=Create/modify members
Permission74=Delete members
@@ -719,6 +726,7 @@ Permission95=Read reports
Permission101=Read sendings
Permission102=Create/modify sendings
Permission104=Validate sendings
+Permission105=Send sendings by email
Permission106=Export sendings
Permission109=Delete sendings
Permission111=Read financial accounts
@@ -844,6 +852,9 @@ Permission561=Read payment orders by credit transfer
Permission562=Create/modify payment order by credit transfer
Permission563=Send/Transmit payment order by credit transfer
Permission564=Record Debits/Rejections of credit transfer
+Permission601=Read stickers
+Permission602=Create/modify stickers
+Permission609=Delete stickers
Permission650=Read Bills of Materials
Permission651=Create/Update Bills of Materials
Permission652=Delete Bills of Materials
@@ -885,7 +896,9 @@ Permission1185=Approve purchase orders
Permission1186=Order purchase orders
Permission1187=Acknowledge receipt of purchase orders
Permission1188=Delete purchase orders
+Permission1189=Check/Uncheck a supplier order reception
Permission1190=Approve (second approval) purchase orders
+Permission1191=Export supplier orders and their attributes
Permission1201=Get result of an export
Permission1202=Create/Modify an export
Permission1231=Read vendor invoices
@@ -899,6 +912,8 @@ Permission1251=Run mass imports of external data into database (data load)
Permission1321=Export customer invoices, attributes and payments
Permission1322=Reopen a paid bill
Permission1421=Export sales orders and attributes
+Permission1521=Read documents
+Permission1522=Delete documents
Permission2401=Read actions (events or tasks) linked to his user account (if owner of event or just assigned to)
Permission2402=Create/modify actions (events or tasks) linked to his user account (if owner of event)
Permission2403=Delete actions (events or tasks) linked to his user account (if owner of event)
@@ -933,9 +948,13 @@ Permission23001=Read Scheduled job
Permission23002=Create/update Scheduled job
Permission23003=Delete Scheduled job
Permission23004=Execute Scheduled job
-Permission50101=Use Point of Sale
+Permission50101=Use Point of Sale (SimplePOS)
+Permission50151=Use Point of Sale (TakePOS)
Permission50201=Read transactions
Permission50202=Import transactions
+Permission50330=Read objects of Zapier
+Permission50331=Create/Update objects of Zapier
+Permission50332=Delete objects of Zapier
Permission50401=Bind products and invoices with accounting accounts
Permission50411=Read operations in ledger
Permission50412=Write/Edit operations in ledger
@@ -959,6 +978,14 @@ Permission63001=Read resources
Permission63002=Create/modify resources
Permission63003=Delete resources
Permission63004=Link resources to agenda events
+Permission64001=Allow direct printing
+Permission67000=Allow printing of receipts
+Permission941601=Read receipts
+Permission941602=Create and modify receipts
+Permission941603=Validate receipts
+Permission941604=Send receipts by email
+Permission941605=Export receipts
+Permission941606=Delete receipts
DictionaryCompanyType=Third-party types
DictionaryCompanyJuridicalType=Third-party legal entities
DictionaryProspectLevel=Prospect potential level for companies
@@ -1795,7 +1822,6 @@ TypePaymentDesc=0:Customer payment type, 1:Vendor payment type, 2:Both customers
IncludePath=Include path (defined into variable %s)
ExpenseReportsSetup=Setup of module Expense Reports
TemplatePDFExpenseReports=Document templates to generate expense report document
-ExpenseReportsIkSetup=Setup of module Expense Reports - Milles index
ExpenseReportsRulesSetup=Setup of module Expense Reports - Rules
ExpenseReportNumberingModules=Expense reports numbering module
NoModueToManageStockIncrease=No module able to manage automatic stock increase has been activated. Stock increase will be done on manual input only.
@@ -2031,3 +2057,4 @@ TemplateAdded=Template added
TemplateUpdated=Template updated
TemplateDeleted=Template deleted
MailToSendEventPush=Template for event reminder emails
+SwitchThisForABetterSecurity=Switching this value to 1 is recommended for more security
diff --git a/htdocs/langs/en_US/boxes.lang b/htdocs/langs/en_US/boxes.lang
index ab89bc10c4b..14db79809bc 100644
--- a/htdocs/langs/en_US/boxes.lang
+++ b/htdocs/langs/en_US/boxes.lang
@@ -104,3 +104,4 @@ BoxTitleLastCustomerShipments=Latest %s customer shipments
NoRecordedShipments=No recorded customer shipment
# Pages
AccountancyHome=Accountancy
+ValidatedProjects=Validated projects
diff --git a/htdocs/langs/en_US/cashdesk.lang b/htdocs/langs/en_US/cashdesk.lang
index 40691eb70e7..549646ab110 100644
--- a/htdocs/langs/en_US/cashdesk.lang
+++ b/htdocs/langs/en_US/cashdesk.lang
@@ -121,4 +121,5 @@ GiftReceiptButton=Add a "Gift receipt" button
GiftReceipt=Gift receipt
ModuleReceiptPrinterMustBeEnabled=Module Receipt printer must have been enabled first
AllowDelayedPayment=Allow delayed payment
-PrintPaymentMethodOnReceipts=Print payment method on tickets|receipts
\ No newline at end of file
+PrintPaymentMethodOnReceipts=Print payment method on tickets|receipts
+WeighingScale=Weighing scale
\ No newline at end of file
diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang
index a5139813014..d259d073cb8 100644
--- a/htdocs/langs/en_US/mails.lang
+++ b/htdocs/langs/en_US/mails.lang
@@ -125,12 +125,13 @@ TagMailtoEmail=Recipient Email (including html "mailto:" link)
NoEmailSentBadSenderOrRecipientEmail=No email sent. Bad sender or recipient email. Verify user profile.
# Module Notifications
Notifications=Notifications
-NoNotificationsWillBeSent=No email notifications are planned for this event and company
-ANotificationsWillBeSent=1 notification will be sent by email
-SomeNotificationsWillBeSent=%s notifications will be sent by email
-AddNewNotification=Activate a new email notification target/event
-ListOfActiveNotifications=List all active targets/events for email notification
-ListOfNotificationsDone=List all email notifications sent
+NotificationsAuto=Notifications Auto.
+NoNotificationsWillBeSent=No automtic email notifications are planned for this event type and company
+ANotificationsWillBeSent=1 automatic notification will be sent by email
+SomeNotificationsWillBeSent=%s automatic notifications will be sent by email
+AddNewNotification=Activate a new automatic email notification target/event
+ListOfActiveNotifications=List all active targets/events for automatic email notification
+ListOfNotificationsDone=List all automatic email notifications sent
MailSendSetupIs=Configuration of email sending has been setup to '%s'. This mode can't be used to send mass emailing.
MailSendSetupIs2=You must first go, with an admin account, into menu %sHome - Setup - EMails%s to change parameter '%s' to use mode '%s'. With this mode, you can enter setup of the SMTP server provided by your Internet Service Provider and use Mass emailing feature.
MailSendSetupIs3=If you have any questions on how to setup your SMTP server, you can ask to %s.
@@ -165,7 +166,7 @@ NoContactLinkedToThirdpartieWithCategoryFound=No contact/address with a category
OutGoingEmailSetup=Outgoing email setup
InGoingEmailSetup=Incoming email setup
OutGoingEmailSetupForEmailing=Outgoing email setup (for module %s)
-DefaultOutgoingEmailSetup=Default outgoing email setup
+DefaultOutgoingEmailSetup=Same configuration than the global Outgoing email setup
Information=Information
ContactsWithThirdpartyFilter=Contacts with third-party filter
Unanswered=Unanswered
diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang
index 2bdb3d2b6f6..a2c314bc7cc 100644
--- a/htdocs/langs/en_US/main.lang
+++ b/htdocs/langs/en_US/main.lang
@@ -511,6 +511,7 @@ Draft=Draft
Drafts=Drafts
StatusInterInvoiced=Invoiced
Validated=Validated
+ValidatedToProduce=Validated (To produce)
Opened=Open
OpenAll=Open (All)
ClosedAll=Closed (All)
@@ -1010,6 +1011,7 @@ SearchIntoCustomerShipments=Customer shipments
SearchIntoExpenseReports=Expense reports
SearchIntoLeaves=Leave
SearchIntoTickets=Tickets
+SearchIntoMiscPayments=Miscellaneous payments
CommentLink=Comments
NbComments=Number of comments
CommentPage=Comments space
@@ -1085,4 +1087,4 @@ MODIFYInDolibarr=Record %s modified
DELETEInDolibarr=Record %s deleted
VALIDATEInDolibarr=Record %s validated
APPROVEDInDolibarr=Record %s approved
-DefaultMailModel=Default Mail Model
\ No newline at end of file
+DefaultMailModel=Default Mail Model
diff --git a/htdocs/langs/en_US/members.lang b/htdocs/langs/en_US/members.lang
index 2f126b11fdf..a48a584c5c1 100644
--- a/htdocs/langs/en_US/members.lang
+++ b/htdocs/langs/en_US/members.lang
@@ -168,6 +168,7 @@ MembersStatisticsByState=Members statistics by state/province
MembersStatisticsByTown=Members statistics by town
MembersStatisticsByRegion=Members statistics by region
NbOfMembers=Number of members
+NbOfActiveMembers=Number of still active members
NoValidatedMemberYet=No validated members found
MembersByCountryDesc=This screen show you statistics on members by countries. Graphic depends however on Google online graph service and is available only if an internet connection is is working.
MembersByStateDesc=This screen show you statistics on members by state/provinces/canton.
diff --git a/htdocs/langs/en_US/mrp.lang b/htdocs/langs/en_US/mrp.lang
index 74877a97297..f4c6eb9246a 100644
--- a/htdocs/langs/en_US/mrp.lang
+++ b/htdocs/langs/en_US/mrp.lang
@@ -75,4 +75,6 @@ ProductsToConsume=Products to consume
ProductsToProduce=Products to produce
UnitCost=Unit cost
TotalCost=Total cost
-BOMTotalCost=The cost to produce this BOM based on cost of each quantity and product to consume (use Cost price if defined, else Average Weighted Price if defined, else the Best purchase price)
\ No newline at end of file
+BOMTotalCost=The cost to produce this BOM based on cost of each quantity and product to consume (use Cost price if defined, else Average Weighted Price if defined, else the Best purchase price)
+GoOnTabProductionToProduceFirst=You must first have started the production to close a Manufacturing Order (See tab '%s'). But you can Cancel it.
+
\ No newline at end of file
diff --git a/htdocs/langs/en_US/other.lang b/htdocs/langs/en_US/other.lang
index 0448672a577..59a0069cd7d 100644
--- a/htdocs/langs/en_US/other.lang
+++ b/htdocs/langs/en_US/other.lang
@@ -261,7 +261,7 @@ ContactCreatedByEmailCollector=Contact/address created by email collector from e
ProjectCreatedByEmailCollector=Project created by email collector from email MSGID %s
TicketCreatedByEmailCollector=Ticket created by email collector from email MSGID %s
OpeningHoursFormatDesc=Use a - to separate opening and closing hours. Use a space to enter different ranges. Example: 8-12 14-18
-
+
##### Export #####
ExportsArea=Exports area
AvailableFormats=Available formats
diff --git a/htdocs/langs/en_US/projects.lang b/htdocs/langs/en_US/projects.lang
index 670fff06f03..f5f6bf3dd9d 100644
--- a/htdocs/langs/en_US/projects.lang
+++ b/htdocs/langs/en_US/projects.lang
@@ -76,12 +76,12 @@ MyActivities=My tasks/activities
MyProjects=My projects
MyProjectsArea=My projects Area
DurationEffective=Effective duration
-ProgressDeclared=Declared progress
+ProgressDeclared=Declared real progress
TaskProgressSummary=Task progress
CurentlyOpenedTasks=Curently open tasks
-TheReportedProgressIsLessThanTheCalculatedProgressionByX=The declared progress is less %s than the calculated progression
-TheReportedProgressIsMoreThanTheCalculatedProgressionByX=The declared progress is more %s than the calculated progression
-ProgressCalculated=Calculated progress
+TheReportedProgressIsLessThanTheCalculatedProgressionByX=The declared real progress is less %s than the progress on consumption
+TheReportedProgressIsMoreThanTheCalculatedProgressionByX=The declared real progress is more %s than the progress on consumption
+ProgressCalculated=Progress on consumption
WhichIamLinkedTo=which I'm linked to
WhichIamLinkedToProject=which I'm linked to project
Time=Time
diff --git a/htdocs/langs/en_US/trips.lang b/htdocs/langs/en_US/trips.lang
index 654f14d6bf7..de31172e9d7 100644
--- a/htdocs/langs/en_US/trips.lang
+++ b/htdocs/langs/en_US/trips.lang
@@ -110,7 +110,7 @@ ExpenseReportPayment=Expense report payment
ExpenseReportsToApprove=Expense reports to approve
ExpenseReportsToPay=Expense reports to pay
ConfirmCloneExpenseReport=Are you sure you want to clone this expense report ?
-ExpenseReportsIk=Expense report milles index
+ExpenseReportsIk=Configuration of mileage charges
ExpenseReportsRules=Expense report rules
ExpenseReportIkDesc=You can modify the calculation of kilometers expense by category and range who they are previously defined. d is the distance in kilometers
ExpenseReportRulesDesc=You can create or update any rules of calculation. This part will be used when user will create a new expense report
@@ -145,7 +145,7 @@ nolimitbyEX_DAY=by day (no limitation)
nolimitbyEX_MON=by month (no limitation)
nolimitbyEX_YEA=by year (no limitation)
nolimitbyEX_EXP=by line (no limitation)
-CarCategory=Category of car
+CarCategory=Vehicle category
ExpenseRangeOffset=Offset amount: %s
RangeIk=Mileage range
AttachTheNewLineToTheDocument=Attach the line to an uploaded document
diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang
index 6cace7f78fd..d7842084c17 100644
--- a/htdocs/langs/fr_FR/admin.lang
+++ b/htdocs/langs/fr_FR/admin.lang
@@ -479,7 +479,7 @@ ModuleCompanyCodeCustomerDigitaria=%s suivi du nom de client tronqué du nombre
ModuleCompanyCodeSupplierDigitaria=%s suivi du nom du fournisseur tronqué du nombre de caractères: %s pour le code comptable fournisseur.
Use3StepsApproval=Par défaut, les commandes fournisseurs nécessitent d'être créées et approuvées par 2 utilisateurs différents (une étape/utilisateur pour créer et une étape/utilisateur pour approuver. Notez que si un utilisateur à les deux permissions, ces deux actions sont effectuées en une seule fois). Cette option ajoute la nécessité d'une approbation par une troisième étape/utilisateur, si le montant de la commande est supérieur au montant d'une valeur définie (soit 3 étapes nécessaire: 1 =Validation, 2=Première approbation et 3=seconde approbation si le montant l'exige). Laissez le champ vide si une seule approbation (2 étapes) est suffisante, placez une valeur très faible (0.1) si une deuxième approbation (3 étapes) est toujours exigée.
UseDoubleApproval=Activer l'approbation en trois étapes si le montant HT est supérieur à ...
-WarningPHPMail=Attention : Il est préférable de configurer les emails sortant pour utiliser le serveur email de votre fournisseur plutôt que la configuration par défaut. Certains fournisseurs email (comme Yahoo) ne permettent pas l'envoi d'e-mails depuis un autre serveur que le leur si l'adresse d'envoi utilisée est une adresse autre que la leur. Votre configuration actuelle utilise le serveur de l'application pour l'envoi d'e-mails et non le serveur de votre fournisseur de messagerie, aussi certains destinataires (ceux compatibles avec le protocole restrictif DMARC) demanderont au fournisseur d'email si ils peuvent accepter l'email et certains fournisseurs (comme Yahoo) peuvent répondre "non" car le serveur utilisé pour l'envoi n'est pas un serveur appartenant au fournisseur, aussi certains de vos emails envoyés peuvent ne pas etre accepté (faites attention aussi aux quotas de votre fournisseur d'email). SI votre fournisseur d'email (comme Yahoo) impose cette restriction, vous devrez modifier votre configuration et opter pour l'autre méthode d'envoi "SMTP server" et saisir les identifiants SMTP de votre compte fournis par votre fournisseur d'e-mail (à demander à votre fournisseur d'e-mail)
+WarningPHPMail=Attention : La configuration d'envoi d'email utilise une configuration par défaut. Il est préférable de configurer les emails sortant pour utiliser le serveur email de votre fournisseur plutôt que la configuration par défaut pour plusieurs raisons:
WarningPHPMail2=Si votre fournisseur de messagerie SMTP a besoin de restreindre le client de messagerie à certaines adresses IP (très rare), voici l'adresse IP du mail user agent (MUA) de votre application CRM ERP : %s .
WarningPHPMailSPF=Si le nom de domaine de votre adresse e-mail d'expéditeur est protégé par SPF (demandez à votre fournisseur d'e-mail), vous devez inclure les adresses IP suivantes dans l'enregistrement SPF du DNS de votre domaine: %s .
ClickToShowDescription=Cliquer pour afficher la description
diff --git a/htdocs/langs/fr_FR/bills.lang b/htdocs/langs/fr_FR/bills.lang
index 5fdf44538e1..5da6bda8133 100644
--- a/htdocs/langs/fr_FR/bills.lang
+++ b/htdocs/langs/fr_FR/bills.lang
@@ -212,7 +212,7 @@ AmountOfBillsByMonthHT=Montant de factures par mois (HT)
UseSituationInvoices=Autoriser les factures de situation
UseSituationInvoicesCreditNote=Autoriser les avoirs de factures de situation
Retainedwarranty=Retenue de garantie
-AllowedInvoiceForRetainedWarranty=Garantie conservée utilisable sur les types de factures suivants
+AllowedInvoiceForRetainedWarranty=Rendre la retenue de garantie utilisable sur les types de factures suivants
RetainedwarrantyDefaultPercent=Pourcentage par défaut de la retenue de garantie
RetainedwarrantyOnlyForSituation=Rendre la "retenue de garantie" disponible uniquement pour les factures de situation
RetainedwarrantyOnlyForSituationFinal=Sur les factures de situation, la déduction globale pour "retenue de garantie" n'est appliquée que sur la facture de situation finale
diff --git a/htdocs/livraison/card.php b/htdocs/livraison/card.php
index 544593dc16c..51351605494 100644
--- a/htdocs/livraison/card.php
+++ b/htdocs/livraison/card.php
@@ -143,7 +143,7 @@ if ($action == 'add')
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -681,7 +681,7 @@ if ($action == 'create') // Create. Seems to no be used
$genallowed = $user->rights->expedition->livraison->lire;
$delallowed = $user->rights->expedition->livraison->creer;
- print $formfile->showdocuments('livraison', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
+ print $formfile->showdocuments('livraison', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
/*
* Linked object block (of linked shipment)
diff --git a/htdocs/livraison/class/livraison.class.php b/htdocs/livraison/class/livraison.class.php
index 7baf41ee51e..c612dbf6fe2 100644
--- a/htdocs/livraison/class/livraison.class.php
+++ b/htdocs/livraison/class/livraison.class.php
@@ -59,6 +59,11 @@ class Livraison extends CommonObject
*/
public $table_element_line = "livraisondet";
+ /**
+ * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
+ */
+ public $picto = 'sending';
+
public $brouillon;
public $socid;
public $ref_customer;
@@ -315,7 +320,7 @@ class Livraison extends CommonObject
$this->note_private = $obj->note_private;
$this->note_public = $obj->note_public;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf;
+ $this->modelpdf = $obj->model_pdf; // deprecated
$this->origin = $obj->origin; // May be 'shipping'
$this->origin_id = $obj->origin_id; // May be id of shipping
@@ -716,9 +721,9 @@ class Livraison extends CommonObject
global $langs;
$result = '';
- $picto = 'sending';
- $label = $langs->trans("ShowReceiving").': '.$this->ref;
+ $label = img_picto('', $this->picto).' '.$langs->trans("ShowReceiving").' : ';
+ $label .= ''.$langs->trans("Status").' : '.$this->ref;
$url = DOL_URL_ROOT.'/livraison/card.php?id='.$this->id;
@@ -734,7 +739,7 @@ class Livraison extends CommonObject
$linkstart = '';
$linkend = ' ';
- if ($withpicto) $result .= ($linkstart.img_object($label, $picto, 'class="classfortooltip"').$linkend);
+ if ($withpicto) $result .= ($linkstart.img_object($label, $this->picto, 'class="classfortooltip"').$linkend);
if ($withpicto && $withpicto != 2) $result .= ' ';
$result .= $linkstart.$this->ref.$linkend;
return $result;
@@ -1043,8 +1048,8 @@ class Livraison extends CommonObject
if (!dol_strlen($modele)) {
$modele = 'typhon';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->LIVRAISON_ADDON_PDF)) {
$modele = $conf->global->LIVRAISON_ADDON_PDF;
}
diff --git a/htdocs/loan/class/paymentloan.class.php b/htdocs/loan/class/paymentloan.class.php
index 2d9501ea549..9c5c1b559ad 100644
--- a/htdocs/loan/class/paymentloan.class.php
+++ b/htdocs/loan/class/paymentloan.class.php
@@ -41,63 +41,63 @@ class PaymentLoan extends CommonObject
*/
public $table_element = 'payment_loan';
- /**
- * @var string String with name of icon for PaymentLoan
- */
- public $picto = 'money-bill-alt';
+ /**
+ * @var string String with name of icon for PaymentLoan
+ */
+ public $picto = 'money-bill-alt';
- /**
- * @var int Loan ID
- */
- public $fk_loan;
+ /**
+ * @var int Loan ID
+ */
+ public $fk_loan;
- /**
- * @var string Create date
- */
- public $datec = '';
+ /**
+ * @var string Create date
+ */
+ public $datec = '';
- public $tms = '';
+ public $tms = '';
- /**
- * @var string Payment date
- */
- public $datep = '';
+ /**
+ * @var string Payment date
+ */
+ public $datep = '';
- public $amounts = array(); // Array of amounts
+ public $amounts = array(); // Array of amounts
- public $amount_capital; // Total amount of payment
+ public $amount_capital; // Total amount of payment
- public $amount_insurance;
+ public $amount_insurance;
- public $amount_interest;
+ public $amount_interest;
- /**
- * @var int Payment mode ID
- */
- public $fk_typepayment;
+ /**
+ * @var int Payment mode ID
+ */
+ public $fk_typepayment;
- /**
- * @var int Payment ID
- */
- public $num_payment;
+ /**
+ * @var int Payment ID
+ */
+ public $num_payment;
- /**
- * @var int Bank ID
- */
- public $fk_bank;
+ /**
+ * @var int Bank ID
+ */
+ public $fk_bank;
- /**
- * @var int User ID
- */
- public $fk_user_creat;
+ /**
+ * @var int User ID
+ */
+ public $fk_user_creat;
- /**
- * @var int user ID
- */
- public $fk_user_modif;
+ /**
+ * @var int user ID
+ */
+ public $fk_user_modif;
- public $type_code;
- public $type_label;
+ public $type_code;
+ public $type_label;
/**
@@ -367,23 +367,23 @@ class PaymentLoan extends CommonObject
if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
}
- // Set loan unpaid if loan has no other payment
- if (!$error)
- {
- require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
- $loan = new Loan($this->db);
- $loan->fetch($this->fk_loan);
- $sum_payment = $loan->getSumPayment();
- if ($sum_payment == 0)
- {
- dol_syslog(get_class($this)."::delete : set loan to unpaid", LOG_DEBUG);
- if ($loan->set_unpaid($user) < 1)
- {
- $error++;
- dol_print_error($this->db);
- }
- }
- }
+ // Set loan unpaid if loan has no other payment
+ if (!$error)
+ {
+ require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
+ $loan = new Loan($this->db);
+ $loan->fetch($this->fk_loan);
+ $sum_payment = $loan->getSumPayment();
+ if ($sum_payment == 0)
+ {
+ dol_syslog(get_class($this)."::delete : set loan to unpaid", LOG_DEBUG);
+ if ($loan->set_unpaid($user) < 1)
+ {
+ $error++;
+ dol_print_error($this->db);
+ }
+ }
+ }
//if (! $error)
//{
@@ -435,7 +435,7 @@ class PaymentLoan extends CommonObject
global $conf;
$error = 0;
- $this->db->begin();
+ $this->db->begin();
if (!empty($conf->banque->enabled))
{
@@ -448,9 +448,9 @@ class PaymentLoan extends CommonObject
if ($mode == 'payment_loan') $total = -$total;
// Insert payment into llx_bank
- $bank_line_id = $acc->addline(
+ $bank_line_id = $acc->addline(
$this->datep,
- $this->fk_typepayment, // Payment mode ID or code ("CHQ or VIR for example")
+ $this->fk_typepayment, // Payment mode ID or code ("CHQ or VIR for example")
$label,
$total,
$this->num_payment,
@@ -498,36 +498,36 @@ class PaymentLoan extends CommonObject
}
- // Set loan payment started if no set
- if (!$error)
- {
- require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
- $loan = new Loan($this->db);
- $loan->fetch($fk_loan);
- if ($loan->paid == $loan::STATUS_UNPAID)
- {
- dol_syslog(get_class($this)."::addPaymentToBank : set loan payment to started", LOG_DEBUG);
- if ($loan->set_started($user) < 1)
- {
- $error++;
- dol_print_error($this->db);
- }
- }
- }
+ // Set loan payment started if no set
+ if (!$error)
+ {
+ require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
+ $loan = new Loan($this->db);
+ $loan->fetch($fk_loan);
+ if ($loan->paid == $loan::STATUS_UNPAID)
+ {
+ dol_syslog(get_class($this)."::addPaymentToBank : set loan payment to started", LOG_DEBUG);
+ if ($loan->set_started($user) < 1)
+ {
+ $error++;
+ dol_print_error($this->db);
+ }
+ }
+ }
if (!$error)
{
- $this->db->commit();
+ $this->db->commit();
return 1;
}
else {
- $this->db->rollback();
+ $this->db->rollback();
return -1;
}
}
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Update link between loan's payment and the line generate in llx_bank
*
@@ -536,14 +536,14 @@ class PaymentLoan extends CommonObject
*/
public function update_fk_bank($id_bank)
{
- // phpcs:enable
+ // phpcs:enable
$sql = "UPDATE ".MAIN_DB_PREFIX."payment_loan SET fk_bank = ".$id_bank." WHERE rowid = ".$this->id;
dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG);
$result = $this->db->query($sql);
if ($result)
{
- $this->fk_bank = $id_bank;
+ $this->fk_bank = $id_bank;
return 1;
} else {
$this->error = $this->db->error();
@@ -556,9 +556,9 @@ class PaymentLoan extends CommonObject
*
* @param int $withpicto 0=No picto, 1=Include picto into link, 2=No picto
* @param int $maxlen Max length label
- * @param int $notooltip 1=Disable tooltip
- * @param string $moretitle Add more text to title tooltip
- * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @param int $notooltip 1=Disable tooltip
+ * @param string $moretitle Add more text to title tooltip
+ * @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, $maxlen = 0, $notooltip = 0, $moretitle = '', $save_lastsearch_value = -1)
diff --git a/htdocs/loan/payment/card.php b/htdocs/loan/payment/card.php
index 4001037f887..9b4da35e5d1 100644
--- a/htdocs/loan/payment/card.php
+++ b/htdocs/loan/payment/card.php
@@ -95,7 +95,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->loan->wri
$outputlangs->setDefaultLang($_REQUEST['lang_id']);
}
if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
- $fac->generateDocument($fac->modelpdf, $outputlangs);
+ $fac->generateDocument($fac->model_pdf, $outputlangs);
}
}
diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php
index 0e656c7514b..ed5aedd67ce 100644
--- a/htdocs/main.inc.php
+++ b/htdocs/main.inc.php
@@ -1800,7 +1800,8 @@ function top_menu_user($hideloginname = 0, $urllogout = '')
if ($user->datepreviouslogin) {
$btnUser .= ' '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser').' ';
}
- $btnUser .= ' '.$langs->trans("Version").' '.$appli.'
+ //$btnUser .= ' '.$langs->trans("Version").' '.$appli.' ';
+ $btnUser .= '
diff --git a/htdocs/modulebuilder/template/class/myobject.class.php b/htdocs/modulebuilder/template/class/myobject.class.php
index 89b4b4bd5ea..edf757d96b0 100644
--- a/htdocs/modulebuilder/template/class/myobject.class.php
+++ b/htdocs/modulebuilder/template/class/myobject.class.php
@@ -99,7 +99,7 @@ class MyObject extends CommonObject
* @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, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'noteditable'=>0, 'default'=>'', 'notnull'=> 1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>20),
'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'searchall'=>1, 'css'=>'minwidth200', 'help'=>'Help text', 'showoncombobox'=>1),
@@ -735,7 +735,7 @@ class MyObject extends CommonObject
$result = '';
- $label = ''.$langs->trans("MyObject").' ';
+ $label = img_picto('', $this->picto).' '.$langs->trans("MyObject").' ';
$label .= ' ';
$label .= ''.$langs->trans('Ref').': '.$this->ref;
if (isset($this->status)) {
@@ -1020,8 +1020,8 @@ class MyObject extends CommonObject
if (!dol_strlen($modele)) {
$modele = 'standard_myobject';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->MYOBJECT_ADDON_PDF)) {
$modele = $conf->global->MYOBJECT_ADDON_PDF;
}
diff --git a/htdocs/modulebuilder/template/myobject_list.php b/htdocs/modulebuilder/template/myobject_list.php
index bd737aa2336..333c7dce45a 100644
--- a/htdocs/modulebuilder/template/myobject_list.php
+++ b/htdocs/modulebuilder/template/myobject_list.php
@@ -122,7 +122,7 @@ foreach ($object->fields as $key => $val)
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
}
-// Definition of fields for list
+// Definition of array of fields for columns
$arrayfields = array();
foreach ($object->fields as $key => $val)
{
@@ -516,7 +516,7 @@ while ($i < ($limit ? min($num, $limit) : $num))
if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
- if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right';
+ if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status'))) $cssforfield .= ($cssforfield ? ' ' : '').'right';
//if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
if (!empty($arrayfields['t.'.$key]['checked']))
diff --git a/htdocs/mrp/class/mo.class.php b/htdocs/mrp/class/mo.class.php
index 404a3329133..c0d6658cab7 100644
--- a/htdocs/mrp/class/mo.class.php
+++ b/htdocs/mrp/class/mo.class.php
@@ -987,7 +987,7 @@ class Mo extends CommonObject
$result = '';
- $label = ''.$langs->trans("MO").' ';
+ $label = img_picto('', $this->picto).' '.$langs->trans("MO").' ';
$label .= ' ';
$label .= ''.$langs->trans('Ref').': '.$this->ref;
if (isset($this->status)) {
@@ -1064,7 +1064,7 @@ class Mo extends CommonObject
global $langs;
//$langs->load("mrp");
$this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
- $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Validated').' ('.$langs->trans("ToProduce").')';
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('ValidatedToProduce');
$this->labelStatus[self::STATUS_INPROGRESS] = $langs->trans('InProgress');
$this->labelStatus[self::STATUS_PRODUCED] = $langs->trans('StatusMOProduced');
$this->labelStatus[self::STATUS_CANCELED] = $langs->trans('Canceled');
@@ -1191,8 +1191,8 @@ class Mo extends CommonObject
//$modele = 'standard';
$modele = ''; // Remove this once a pdf_standard.php exists.
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->MO_ADDON_PDF)) {
$modele = $conf->global->MO_ADDON_PDF;
}
diff --git a/htdocs/mrp/mo_card.php b/htdocs/mrp/mo_card.php
index 19ec10daf3b..49b29b7048b 100644
--- a/htdocs/mrp/mo_card.php
+++ b/htdocs/mrp/mo_card.php
@@ -1,5 +1,5 @@
+/* Copyright (C) 2017-2020 Laurent Destailleur
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,26 +21,6 @@
* \brief Page to create/edit/view mo
*/
-//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db
-//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user
-//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
-//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies
-
-
// Load Dolibarr environment
require '../main.inc.php';
@@ -187,7 +167,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$object->generateDocument($model, $outputlangs, 0, 0, 0);
@@ -653,8 +633,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
{
if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS)
{
- // TODO If production is already > 1, show only close, else show cancel
- print 'id.'&action=confirm_produced&confirm=yes">'.$langs->trans("Close").' '."\n";
+ $arrayproduced = $object->fetchLinesLinked('produced', 0);
+ $nbProduced = 0;
+ foreach ($arrayproduced as $lineproduced) {
+ $nbProduced += $lineproduced['qty'];
+ }
+ if ($nbProduced > 0) { // If production has started, we can close it
+ print 'id.'&action=confirm_produced&confirm=yes">'.$langs->trans("Close").' '."\n";
+ } else {
+ print 'transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").' '."\n";
+ }
print 'id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").' '."\n";
}
@@ -694,7 +682,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
$genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content
$delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card
- print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang);
+ print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang);
// Show links to link elements
$linktoelem = $form->showLinkToObjectBlock($object, null, array('mo'));
diff --git a/htdocs/mrp/mo_list.php b/htdocs/mrp/mo_list.php
index 14d5c673f1a..57efff54bc0 100644
--- a/htdocs/mrp/mo_list.php
+++ b/htdocs/mrp/mo_list.php
@@ -21,25 +21,6 @@
* \brief List page for mo
*/
-//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db
-//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user
-//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data
-//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
-//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session)
-//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', '1'); // The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("XFRAMEOPTIONS_ALLOWALL")) define('XFRAMEOPTIONS_ALLOWALL', '1'); // Do not add the HTTP header 'X-Frame-Options: SAMEORIGIN' but 'X-Frame-Options: ALLOWALL'
-
// Load Dolibarr environment
require '../main.inc.php';
diff --git a/htdocs/mrp/mo_movements.php b/htdocs/mrp/mo_movements.php
index e281d45ee74..754a83c4770 100644
--- a/htdocs/mrp/mo_movements.php
+++ b/htdocs/mrp/mo_movements.php
@@ -21,26 +21,6 @@
* \brief Page to show tock movements of a MO
*/
-//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db
-//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user
-//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
-//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies
-
-
// Load Dolibarr environment
require '../main.inc.php';
diff --git a/htdocs/mrp/mo_production.php b/htdocs/mrp/mo_production.php
index a5503147f0c..e86fdc8348d 100644
--- a/htdocs/mrp/mo_production.php
+++ b/htdocs/mrp/mo_production.php
@@ -1,5 +1,5 @@
+/* Copyright (C) 2019-2020 Laurent Destailleur
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,26 +21,6 @@
* \brief Page to make production on a MO
*/
-//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Do not create database handler $db
-//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Do not load object $user
-//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); // Do not load object $mysoc
-//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Do not load object $langs
-//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check injection attack on GET parameters
-//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check injection attack on POST parameters
-//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
-//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
-//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data
-//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
-//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
-//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
-//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too.
-//if (! defined('NOIPCHECK')) define('NOIPCHECK','1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
-//if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT','auto'); // Force lang to a particular value
-//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE','aloginmodule'); // Force authentication handler
-//if (! defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN',1); // The main.inc.php does not make a redirect if not logged, instead show simple error message
-//if (! defined("FORCECSP")) define('FORCECSP','none'); // Disable all Content Security Policies
-
-
// Load Dolibarr environment
require '../main.inc.php';
@@ -274,7 +254,7 @@ if (empty($reshook))
setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Warehouse"), $tmpproduct->ref), null, 'errors');
$error++;
}
- if ($tmpproduct->status_batch && (!GETPOST('batchtoproduce-'.$line->id.'-'.$i))) {
+ if (!empty($conf->productbatch->enabled) && $tmpproduct->status_batch && (!GETPOST('batchtoproduce-'.$line->id.'-'.$i))) {
$langs->load("errors");
setEventMessages($langs->trans("ErrorFieldRequiredForProduct", $langs->transnoentitiesnoconv("Batch"), $tmpproduct->ref), null, 'errors');
$error++;
@@ -400,7 +380,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$object->generateDocument($model, $outputlangs, 0, 0, 0);
@@ -623,8 +603,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
{
if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS)
{
- // TODO If production is already > 1, show only close, else show cancel
- print 'id.'&action=confirm_produced&confirm=yes">'.$langs->trans("Close").' '."\n";
+ $arrayproduced = $object->fetchLinesLinked('produced', 0);
+ $nbProduced = 0;
+ foreach ($arrayproduced as $lineproduced) {
+ $nbProduced += $lineproduced['qty'];
+ }
+ if ($nbProduced > 0) { // If production has started, we can close it
+ print 'id.'&action=confirm_produced&confirm=yes">'.$langs->trans("Close").' '."\n";
+ } else {
+ print 'transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").' '."\n";
+ }
print 'id.'&action=confirm_close&confirm=yes">'.$langs->trans("Cancel").' '."\n";
}
@@ -693,7 +681,10 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '';
print '
';
- $newlinetext = '
id.'&action=addconsumeline">'.$langs->trans("AddNewConsumeLines").' ';
+ $newlinetext = '';
+ if ($action != 'consumeorproduce' && $action != 'consumeandproduceall') {
+ $newlinetext = '
id.'&action=addconsumeline">'.$langs->trans("AddNewConsumeLines").' ';
+ }
print load_fiche_titre($langs->trans('Consumption'), '', '', 0, '', '', $newlinetext);
print '
';
@@ -824,7 +815,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
$i = 1;
print ''."\n";
print '
';
- print ''.$langs->trans("ToConsume").' ';
+ print ''.$langs->trans("ToConsume").' ';
$preselected = (GETPOSTISSET('qty-'.$line->id.'-'.$i) ? GETPOST('qty-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyconsumed));
if ($action == 'consumeorproduce' && !GETPOSTISSET('qty-'.$line->id.'-'.$i)) $preselected = 0;
print ' ';
@@ -972,8 +963,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
}
if (in_array($action, array('consumeorproduce', 'consumeandproduceall'))) {
+ print ''."\n";
print ' ';
- print ''.$langs->trans("ToProduce").' ';
+ print ''.$langs->trans("ToProduce").' ';
$preselected = (GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i) ? GETPOST('qtytoproduce-'.$line->id.'-'.$i) : max(0, $line->qty - $alreadyproduced));
if ($action == 'consumeorproduce' && !GETPOSTISSET('qtytoproduce-'.$line->id.'-'.$i)) $preselected = 0;
print ' ';
diff --git a/htdocs/opensurvey/card.php b/htdocs/opensurvey/card.php
index 2f9b8babfed..2d714deeb2c 100644
--- a/htdocs/opensurvey/card.php
+++ b/htdocs/opensurvey/card.php
@@ -49,8 +49,8 @@ $object = new Opensurveysondage($db);
$result = $object->fetch(0, $numsondage);
if ($result <= 0)
{
- dol_print_error($db, $object->error);
- exit;
+ dol_print_error($db, $object->error);
+ exit;
}
$expiredate = dol_mktime(0, 0, 0, GETPOST('expiremonth'), GETPOST('expireday'), GETPOST('expireyear'));
@@ -67,112 +67,112 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e
if (empty($reshook))
{
- if ($cancel) $action = '';
+ if ($cancel) $action = '';
- // Delete
- if ($action == 'delete_confirm')
- {
- // Security check
- if (!$user->rights->opensurvey->write) accessforbidden();
+ // Delete
+ if ($action == 'delete_confirm')
+ {
+ // Security check
+ if (!$user->rights->opensurvey->write) accessforbidden();
- $result = $object->delete($user, '', $numsondage);
+ $result = $object->delete($user, '', $numsondage);
- header('Location: '.dol_buildpath('/opensurvey/list.php', 1));
- exit();
- }
+ header('Location: '.dol_buildpath('/opensurvey/list.php', 1));
+ exit();
+ }
- // Close
- if ($action == 'close')
- {
- $object->status = Opensurveysondage::STATUS_CLOSED;
- $object->update($user);
- }
+ // Close
+ if ($action == 'close')
+ {
+ $object->status = Opensurveysondage::STATUS_CLOSED;
+ $object->update($user);
+ }
- // Reopend
- if ($action == 'reopen')
- {
- $object->status = Opensurveysondage::STATUS_VALIDATED;
- $object->update($user);
- }
+ // Reopend
+ if ($action == 'reopen')
+ {
+ $object->status = Opensurveysondage::STATUS_VALIDATED;
+ $object->update($user);
+ }
- // Update
- if ($action == 'update')
- {
- // Security check
- if (!$user->rights->opensurvey->write) accessforbidden();
+ // Update
+ if ($action == 'update')
+ {
+ // Security check
+ if (!$user->rights->opensurvey->write) accessforbidden();
- $error = 0;
+ $error = 0;
- if (!GETPOST('nouveautitre'))
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors');
- $error++;
- $action = 'edit';
- }
+ if (!GETPOST('nouveautitre'))
+ {
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors');
+ $error++;
+ $action = 'edit';
+ }
- if (!$error)
- {
- $object->title = GETPOST('nouveautitre', 'nohtml');
- $object->description = GETPOST('nouveauxcommentaires', 'restricthtml');
- $object->mail_admin = GETPOST('nouvelleadresse', 'alpha');
- $object->date_fin = $expiredate;
- $object->allow_comments = GETPOST('cancomment', 'alpha') == 'on' ? 1 : 0;
- $object->allow_spy = GETPOST('canseeothersvote', 'alpha') == 'on' ? 1 : 0;
- $object->mailsonde = GETPOST('mailsonde', 'alpha') == 'on' ? true : false;
+ if (!$error)
+ {
+ $object->title = GETPOST('nouveautitre', 'nohtml');
+ $object->description = GETPOST('nouveauxcommentaires', 'restricthtml');
+ $object->mail_admin = GETPOST('nouvelleadresse', 'alpha');
+ $object->date_fin = $expiredate;
+ $object->allow_comments = GETPOST('cancomment', 'alpha') == 'on' ? 1 : 0;
+ $object->allow_spy = GETPOST('canseeothersvote', 'alpha') == 'on' ? 1 : 0;
+ $object->mailsonde = GETPOST('mailsonde', 'alpha') == 'on' ? true : false;
- $res = $object->update($user);
- if ($res < 0)
- {
- setEventMessages($object->error, $object->errors, 'errors');
- $action = 'edit';
- }
- }
- }
+ $res = $object->update($user);
+ if ($res < 0)
+ {
+ setEventMessages($object->error, $object->errors, 'errors');
+ $action = 'edit';
+ }
+ }
+ }
- // Add comment
- if (GETPOST('ajoutcomment'))
- {
- $error = 0;
+ // Add comment
+ if (GETPOST('ajoutcomment'))
+ {
+ $error = 0;
- if (!GETPOST('comment'))
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors');
- }
- if (!GETPOST('commentuser'))
- {
- $error++;
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("User")), null, 'errors');
- }
+ if (!GETPOST('comment'))
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Comment")), null, 'errors');
+ }
+ if (!GETPOST('commentuser'))
+ {
+ $error++;
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("User")), null, 'errors');
+ }
- if (!$error)
- {
- $comment = GETPOST("comment");
- $comment_user = GETPOST('commentuser');
+ if (!$error)
+ {
+ $comment = GETPOST("comment");
+ $comment_user = GETPOST('commentuser');
- $resql = $object->addComment($comment, $comment_user);
+ $resql = $object->addComment($comment, $comment_user);
- if (!$resql)
- {
- setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors');
- }
- }
- }
+ if (!$resql)
+ {
+ setEventMessages($langs->trans('ErrorInsertingComment'), null, 'errors');
+ }
+ }
+ }
- // Delete comment
- $idcomment = GETPOST('deletecomment', 'int');
- if ($idcomment)
- {
- // Security check
- if (!$user->rights->opensurvey->write) accessforbidden();
+ // Delete comment
+ $idcomment = GETPOST('deletecomment', 'int');
+ if ($idcomment)
+ {
+ // Security check
+ if (!$user->rights->opensurvey->write) accessforbidden();
- $resql = $object->deleteComment($idcomment);
- }
+ $resql = $object->deleteComment($idcomment);
+ }
- if ($action == 'edit') {
- // Security check
- if (!$user->rights->opensurvey->write) accessforbidden();
- }
+ if ($action == 'edit') {
+ // Security check
+ if (!$user->rights->opensurvey->write) accessforbidden();
+ }
}
@@ -302,8 +302,8 @@ print ' ';
print '
'.$langs->trans('ExpireDate').' ';
if ($action == 'edit') print $form->selectDate($expiredate ? $expiredate : $object->date_fin, 'expire', 0, 0, 0, '', 1, 0);
else {
- print dol_print_date($object->date_fin, 'day');
- if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired"));
+ print dol_print_date($object->date_fin, 'day');
+ if ($object->date_fin && $object->date_fin < dol_now() && $object->status == Opensurveysondage::STATUS_VALIDATED) print img_warning($langs->trans("Expired"));
}
print ' ';
@@ -356,19 +356,19 @@ print ''."\n";
print '
';
if ($action != 'edit' && $user->rights->opensurvey->write) {
- //Modify button
- print '
'.$langs->trans("Modify").' ';
+ //Modify button
+ print '
'.$langs->trans("Modify").' ';
- if ($object->status == Opensurveysondage::STATUS_VALIDATED)
- {
- //Close button
- print '
'.$langs->trans("Close").' ';
- }
- if ($object->status == Opensurveysondage::STATUS_CLOSED)
- {
- //Opened button
- print '
'.$langs->trans("ReOpen").' ';
- }
+ if ($object->status == Opensurveysondage::STATUS_VALIDATED)
+ {
+ //Close button
+ print '
'.$langs->trans("Close").' ';
+ }
+ if ($object->status == Opensurveysondage::STATUS_CLOSED)
+ {
+ //Opened button
+ print '
'.$langs->trans("ReOpen").' ';
+ }
//Delete button
print '
'.$langs->trans('Delete').' ';
diff --git a/htdocs/opensurvey/class/opensurveysondage.class.php b/htdocs/opensurvey/class/opensurveysondage.class.php
index 0c2b00735ff..f8f6cb0f885 100644
--- a/htdocs/opensurvey/class/opensurveysondage.class.php
+++ b/htdocs/opensurvey/class/opensurveysondage.class.php
@@ -34,616 +34,615 @@ require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
*/
class Opensurveysondage extends CommonObject
{
- /**
- * @var string ID to identify managed object
- */
- public $element = 'opensurvey_sondage';
-
- /**
- * @var string Name of table without prefix where object is stored
- */
- public $table_element = 'opensurvey_sondage';
-
- /**
- * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
- */
- public $picto = 'poll';
-
-
- /**
- * @var string ID survey
- */
- public $id_sondage;
-
- /**
- * @var string description
- */
- public $description;
-
- public $mail_admin;
- public $nom_admin;
-
- /**
- * Id of user author of the poll
- * @var int
- */
- public $fk_user_creat;
-
- /**
- * @var string Title
- */
- public $title;
-
- public $date_fin = '';
- public $status = 1;
- public $format;
- public $mailsonde;
-
- public $sujet;
-
- /**
- * @var int Allow comments on this poll
- */
- public $allow_comments;
-
- /**
- * @var int Allow users see others vote
- */
- public $allow_spy;
-
-
- /**
- * Draft status (not used)
- */
- const STATUS_DRAFT = 0;
- /**
- * Validated/Opened status
- */
- const STATUS_VALIDATED = 1;
- /**
- * Closed
- */
- const STATUS_CLOSED = 2;
-
-
-
- /**
- * Constructor
- *
- * @param DoliDb $db Database handler
- */
- public function __construct($db)
- {
- $this->db = $db;
- }
-
-
- /**
- * Create object into database
- *
- * @param User $user User that creates
- * @param int $notrigger 0=launch triggers after, 1=disable triggers
- * @return int <0 if KO, Id of created object if OK
- */
- public function create(User $user, $notrigger = 0)
- {
- $error = 0;
-
- // Clean parameters
- $this->cleanParameters();
-
- // Check parameters
- if (!$this->date_fin > 0)
- {
- $this->error = 'BadValueForEndDate';
- dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
- return -1;
- }
-
- // Insert request
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_sondage(";
- $sql .= "id_sondage,";
- $sql .= "commentaires,";
- $sql .= "fk_user_creat,";
- $sql .= "titre,";
- $sql .= "date_fin,";
- $sql .= "status,";
- $sql .= "format,";
- $sql .= "mailsonde,";
- $sql .= "allow_comments,";
- $sql .= "allow_spy,";
- $sql .= "sujet";
- $sql .= ") VALUES (";
- $sql .= "'".$this->db->escape($this->id_sondage)."',";
- $sql .= " ".(empty($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").",";
- $sql .= " ".$user->id.",";
- $sql .= " '".$this->db->escape($this->title)."',";
- $sql .= " '".$this->db->idate($this->date_fin)."',";
- $sql .= " ".$this->status.",";
- $sql .= " '".$this->db->escape($this->format)."',";
- $sql .= " ".$this->db->escape($this->mailsonde).",";
- $sql .= " ".$this->db->escape($this->allow_comments).",";
- $sql .= " ".$this->db->escape($this->allow_spy).",";
- $sql .= " '".$this->db->escape($this->sujet)."'";
- $sql .= ")";
-
- $this->db->begin();
-
- dol_syslog(get_class($this)."::create", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
-
- if (!$error)
- {
- if (!$notrigger)
- {
- global $langs, $conf;
-
- // Call trigger
- $result = $this->call_trigger('OPENSURVEY_CREATE', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
- }
-
- // Commit or rollback
- if ($error)
- {
- foreach ($this->errors as $errmsg)
- {
- dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
- $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
- }
- $this->db->rollback();
- return -1 * $error;
- } else {
- $this->db->commit();
- return $this->id;
- }
- }
-
-
- /**
- * Load object in memory from the database
- *
- * @param int $id Id object
- * @param string $numsurvey Ref of survey (admin or not)
- * @return int <0 if KO, >0 if OK
- */
- public function fetch($id, $numsurvey = '')
- {
- $sql = "SELECT";
- $sql .= " t.id_sondage,";
- $sql .= " t.titre as title,";
- $sql .= " t.commentaires as description,";
- $sql .= " t.mail_admin,";
- $sql .= " t.nom_admin,";
- $sql .= " t.fk_user_creat,";
- $sql .= " t.date_fin,";
- $sql .= " t.status,";
- $sql .= " t.format,";
- $sql .= " t.mailsonde,";
- $sql .= " t.allow_comments,";
- $sql .= " t.allow_spy,";
- $sql .= " t.sujet,";
- $sql .= " t.tms";
- $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as t";
- $sql .= " WHERE t.id_sondage = '".$this->db->escape($id ? $id : $numsurvey)."'";
-
- dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
- $obj = $this->db->fetch_object($resql);
-
- $this->id_sondage = $obj->id_sondage;
- $this->ref = $this->id_sondage; //For compatibility
-
- $this->description = $obj->description;
- $this->mail_admin = $obj->mail_admin;
- $this->nom_admin = $obj->nom_admin;
- $this->title = $obj->title;
- $this->date_fin = $this->db->jdate($obj->date_fin);
- $this->status = $obj->status;
- $this->format = $obj->format;
- $this->mailsonde = $obj->mailsonde;
- $this->allow_comments = $obj->allow_comments;
- $this->allow_spy = $obj->allow_spy;
- $this->sujet = $obj->sujet;
- $this->fk_user_creat = $obj->fk_user_creat;
-
- $this->date_m = $this->db->jdate($obj->tls);
- $ret = 1;
- } else {
- $sondage = ($id ? 'id='.$id : 'sondageid='.$numsurvey);
- $this->error = 'Fetch no poll found for '.$sondage;
- dol_syslog($this->error, LOG_ERR);
- $ret = 0;
- }
-
- $this->db->free($resql);
- } else {
- $this->error = "Error ".$this->db->lasterror();
- $ret = -1;
- }
-
- return $ret;
- }
-
-
- /**
- * Update object into database
- *
- * @param User $user User that modifies
- * @param int $notrigger 0=launch triggers after, 1=disable triggers
- * @return int <0 if KO, >0 if OK
- */
- public function update(User $user, $notrigger = 0)
- {
- global $conf, $langs;
- $error = 0;
-
- // Clean parameters
- $this->cleanParameters();
-
- // Check parameters
- // Put here code to add a control on parameters values
-
- // Update request
- $sql = "UPDATE ".MAIN_DB_PREFIX."opensurvey_sondage SET";
- $sql .= " id_sondage=".(isset($this->id_sondage) ? "'".$this->db->escape($this->id_sondage)."'" : "null").",";
- $sql .= " commentaires=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").",";
- $sql .= " mail_admin=".(isset($this->mail_admin) ? "'".$this->db->escape($this->mail_admin)."'" : "null").",";
- $sql .= " nom_admin=".(isset($this->nom_admin) ? "'".$this->db->escape($this->nom_admin)."'" : "null").",";
- $sql .= " titre=".(isset($this->title) ? "'".$this->db->escape($this->title)."'" : "null").",";
- $sql .= " date_fin=".(dol_strlen($this->date_fin) != 0 ? "'".$this->db->idate($this->date_fin)."'" : 'null').",";
- $sql .= " status=".(isset($this->status) ? "'".$this->db->escape($this->status)."'" : "null").",";
- $sql .= " format=".(isset($this->format) ? "'".$this->db->escape($this->format)."'" : "null").",";
- $sql .= " mailsonde=".(isset($this->mailsonde) ? $this->db->escape($this->mailsonde) : "null").",";
- $sql .= " allow_comments=".$this->db->escape($this->allow_comments).",";
- $sql .= " allow_spy=".$this->db->escape($this->allow_spy);
- $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'";
-
- $this->db->begin();
-
- dol_syslog(get_class($this)."::update", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
-
- if (!$error && !$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('OPENSURVEY_MODIFY', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
-
- // Commit or rollback
- if ($error)
- {
- foreach ($this->errors as $errmsg)
- {
- dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
- $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
- }
- $this->db->rollback();
- return -1 * $error;
- } else {
- $this->db->commit();
- return 1;
- }
- }
-
- /**
- * Delete object in database
- *
- * @param User $user User that deletes
- * @param int $notrigger 0=launch triggers after, 1=disable triggers
- * @param string $numsondage Num sondage admin to delete
- * @return int <0 if KO, >0 if OK
- */
- public function delete(User $user, $notrigger = 0, $numsondage = '')
- {
- global $conf, $langs;
- $error = 0;
-
- if (empty($numsondage))
- {
- $numsondage = $this->id_sondage;
- }
-
- $this->db->begin();
-
- if (!$error)
- {
- if (!$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('OPENSURVEY_DELETE', $user);
- if ($result < 0) $error++;
- // End call triggers
- }
- }
-
- if (!$error)
- {
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'";
- dol_syslog(get_class($this)."::delete", LOG_DEBUG);
- $resql = $this->db->query($sql);
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_user_studs WHERE id_sondage = '".$this->db->escape($numsondage)."'";
- dol_syslog(get_class($this)."::delete", LOG_DEBUG);
- $resql = $this->db->query($sql);
-
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."opensurvey_sondage";
- $sql .= " WHERE id_sondage = '".$this->db->escape($numsondage)."'";
-
- dol_syslog(get_class($this)."::delete", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
- }
-
- // Commit or rollback
- if ($error)
- {
- foreach ($this->errors as $errmsg)
- {
- dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
- $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
- }
- $this->db->rollback();
- return -1 * $error;
- } else {
- $this->db->commit();
- return 1;
- }
- }
-
- /**
- * Return a link to the object card (with optionaly the picto)
- *
- * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
- * @param 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, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
- {
- global $db, $conf, $langs;
- global $dolibarr_main_authentication, $dolibarr_main_demo;
- global $menumanager;
-
- if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
-
- $result = '';
- $companylink = '';
-
- $label = '
'.$langs->trans("ShowSurvey").' ';
- $label .= '
';
- $label .= '
'.$langs->trans('Ref').': '.$this->ref.'
';
- $label .= '
'.$langs->trans('Title').': '.$this->title.'
';
-
- $url = DOL_URL_ROOT.'/opensurvey/card.php?id='.$this->id;
-
- // Add param to save lastsearch_values or not
- $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
- if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
- if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
-
- $linkclose = '';
- if (empty($notooltip))
- {
- if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
- {
- $label = $langs->trans("ShowMyObject");
- $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
- }
- $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
- $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
- } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
-
- $linkstart = '
';
- $linkend = ' ';
-
- $result .= $linkstart;
- if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
- if ($withpicto != 2) $result .= $this->ref;
- $result .= $linkend;
-
- return $result;
- }
-
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Return array of lines
- *
- * @return int <0 if KO, >0 if OK
- */
- public function fetch_lines()
- {
- // phpcs:enable
- $ret = array();
-
- $sql = "SELECT id_users, nom as name, reponses FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
- $sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'";
- $resql = $this->db->query($sql);
-
- if ($resql)
- {
- $num = $this->db->num_rows($resql);
- $i = 0;
- while ($i < $num)
- {
- $obj = $this->db->fetch_object($resql);
- $tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses);
-
- $ret[] = $tmp;
- $i++;
- }
- } else dol_print_error($this->db);
-
- $this->lines = $ret;
-
- return count($this->lines);
- }
-
- /**
- * Initialise object with example values
- * Id must be 0 if object instance is a specimen
- *
- * @return void
- */
- public function initAsSpecimen()
- {
- $this->id = 0;
-
- $this->id_sondage = '';
- $this->description = 'Description of the specimen survey';
- $this->mail_admin = '';
- $this->nom_admin = '';
- $this->title = 'This is a specimen survey';
- $this->date_fin = dol_now() + 3600 * 24 * 10;
- $this->status = 1;
- $this->format = 'classic';
- $this->mailsonde = '';
- }
-
- /**
- * Returns all comments for the current opensurvey poll
- *
- * @return Object[]
- */
- public function getComments()
- {
- $comments = array();
-
- $sql = 'SELECT id_comment, usercomment, comment';
- $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_comments';
- $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'";
- $sql .= " ORDER BY id_comment";
- $resql = $this->db->query($sql);
-
- if ($resql)
- {
- $num_rows = $this->db->num_rows($resql);
-
- if ($num_rows > 0)
- {
- while ($obj = $this->db->fetch_object($resql))
- {
- $comments[] = $obj;
- }
- }
- }
-
- return $comments;
- }
-
- /**
- * Adds a comment to the poll
- *
- * @param string $comment Comment content
- * @param string $comment_user Comment author
- * @return boolean False in case of the query fails, true if it was successful
- */
- public function addComment($comment, $comment_user)
- {
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_comments (id_sondage, comment, usercomment)";
- $sql .= " VALUES ('".$this->db->escape($this->id_sondage)."','".$this->db->escape($comment)."','".$this->db->escape($comment_user)."')";
- $resql = $this->db->query($sql);
-
- if (!$resql) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Deletes a comment of the poll
- *
- * @param int $id_comment Id of the comment
- * @return boolean False in case of the query fails, true if it was successful
- */
- public function deleteComment($id_comment)
- {
- $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_comments WHERE id_comment = '.$id_comment.' AND id_sondage = "'.$this->db->escape($this->id_sondage).'"';
- $resql = $this->db->query($sql);
-
- if (!$resql) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Cleans all the class variables before doing an update or an insert
- *
- * @return void
- */
- private function cleanParameters()
- {
- $this->id_sondage = trim($this->id_sondage);
- $this->description = trim($this->description);
- $this->mail_admin = trim($this->mail_admin);
- $this->nom_admin = trim($this->nom_admin);
- $this->title = trim($this->title);
- $this->status = trim($this->status);
- $this->format = trim($this->format);
- $this->mailsonde = ($this->mailsonde ? 1 : 0);
- $this->allow_comments = ($this->allow_comments ? 1 : 0);
- $this->allow_spy = ($this->allow_spy ? 1 : 0);
- $this->sujet = trim($this->sujet);
- }
-
-
- /**
- * Return status label of Order
- *
- * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
- * @return string Libelle
- */
- public function getLibStatut($mode)
- {
- return $this->LibStatut($this->status, $mode);
- }
-
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Return label of status
- *
- * @param int $status Id statut
- * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
- * @return string Label of status
- */
- public function LibStatut($status, $mode)
- {
- // phpcs:enable
- global $langs, $conf;
-
- if (empty($this->labelStatus) || empty($this->labelStatusShort))
- {
- global $langs;
- //$langs->load("mymodule");
- $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
- $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Opened');
- $this->labelStatus[self::STATUS_CLOSED] = $langs->trans('Closed');
- $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
- $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Opened');
- $this->labelStatusShort[self::STATUS_CLOSED] = $langs->trans('Closed');
- }
-
- $statusType = 'status'.$status;
- if ($status == self::STATUS_VALIDATED) {
- if (0) $statusType = 'status1';
- else $statusType = 'status4';
- }
- if ($status == self::STATUS_CLOSED) $statusType = 'status6';
-
- return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
- }
+ /**
+ * @var string ID to identify managed object
+ */
+ public $element = 'opensurvey_sondage';
+
+ /**
+ * @var string Name of table without prefix where object is stored
+ */
+ public $table_element = 'opensurvey_sondage';
+
+ /**
+ * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
+ */
+ public $picto = 'poll';
+
+
+ /**
+ * @var string ID survey
+ */
+ public $id_sondage;
+
+ /**
+ * @var string description
+ */
+ public $description;
+
+ public $mail_admin;
+ public $nom_admin;
+
+ /**
+ * Id of user author of the poll
+ * @var int
+ */
+ public $fk_user_creat;
+
+ /**
+ * @var string Title
+ */
+ public $title;
+
+ public $date_fin = '';
+ public $status = 1;
+ public $format;
+ public $mailsonde;
+
+ public $sujet;
+
+ /**
+ * @var int Allow comments on this poll
+ */
+ public $allow_comments;
+
+ /**
+ * @var int Allow users see others vote
+ */
+ public $allow_spy;
+
+
+ /**
+ * Draft status (not used)
+ */
+ const STATUS_DRAFT = 0;
+ /**
+ * Validated/Opened status
+ */
+ const STATUS_VALIDATED = 1;
+ /**
+ * Closed
+ */
+ const STATUS_CLOSED = 2;
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDb $db Database handler
+ */
+ public function __construct($db)
+ {
+ $this->db = $db;
+ }
+
+
+ /**
+ * Create object into database
+ *
+ * @param User $user User that creates
+ * @param int $notrigger 0=launch triggers after, 1=disable triggers
+ * @return int <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = 0)
+ {
+ $error = 0;
+
+ // Clean parameters
+ $this->cleanParameters();
+
+ // Check parameters
+ if (!$this->date_fin > 0)
+ {
+ $this->error = 'BadValueForEndDate';
+ dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
+ return -1;
+ }
+
+ // Insert request
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_sondage(";
+ $sql .= "id_sondage,";
+ $sql .= "commentaires,";
+ $sql .= "fk_user_creat,";
+ $sql .= "titre,";
+ $sql .= "date_fin,";
+ $sql .= "status,";
+ $sql .= "format,";
+ $sql .= "mailsonde,";
+ $sql .= "allow_comments,";
+ $sql .= "allow_spy,";
+ $sql .= "sujet";
+ $sql .= ") VALUES (";
+ $sql .= "'".$this->db->escape($this->id_sondage)."',";
+ $sql .= " ".(empty($this->description) ? 'NULL' : "'".$this->db->escape($this->description)."'").",";
+ $sql .= " ".$user->id.",";
+ $sql .= " '".$this->db->escape($this->title)."',";
+ $sql .= " '".$this->db->idate($this->date_fin)."',";
+ $sql .= " ".$this->status.",";
+ $sql .= " '".$this->db->escape($this->format)."',";
+ $sql .= " ".$this->db->escape($this->mailsonde).",";
+ $sql .= " ".$this->db->escape($this->allow_comments).",";
+ $sql .= " ".$this->db->escape($this->allow_spy).",";
+ $sql .= " '".$this->db->escape($this->sujet)."'";
+ $sql .= ")";
+
+ $this->db->begin();
+
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
+
+ if (!$error)
+ {
+ if (!$notrigger)
+ {
+ global $langs, $conf;
+
+ // Call trigger
+ $result = $this->call_trigger('OPENSURVEY_CREATE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+ }
+
+ // Commit or rollback
+ if ($error)
+ {
+ foreach ($this->errors as $errmsg)
+ {
+ dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
+ $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
+ }
+ $this->db->rollback();
+ return -1 * $error;
+ } else {
+ $this->db->commit();
+ return $this->id;
+ }
+ }
+
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $numsurvey Ref of survey (admin or not)
+ * @return int <0 if KO, >0 if OK
+ */
+ public function fetch($id, $numsurvey = '')
+ {
+ $sql = "SELECT";
+ $sql .= " t.id_sondage,";
+ $sql .= " t.titre as title,";
+ $sql .= " t.commentaires as description,";
+ $sql .= " t.mail_admin,";
+ $sql .= " t.nom_admin,";
+ $sql .= " t.fk_user_creat,";
+ $sql .= " t.date_fin,";
+ $sql .= " t.status,";
+ $sql .= " t.format,";
+ $sql .= " t.mailsonde,";
+ $sql .= " t.allow_comments,";
+ $sql .= " t.allow_spy,";
+ $sql .= " t.sujet,";
+ $sql .= " t.tms";
+ $sql .= " FROM ".MAIN_DB_PREFIX."opensurvey_sondage as t";
+ $sql .= " WHERE t.id_sondage = '".$this->db->escape($id ? $id : $numsurvey)."'";
+
+ dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ if ($this->db->num_rows($resql))
+ {
+ $obj = $this->db->fetch_object($resql);
+
+ $this->id_sondage = $obj->id_sondage;
+ $this->ref = $this->id_sondage; //For compatibility
+
+ $this->description = $obj->description;
+ $this->mail_admin = $obj->mail_admin;
+ $this->nom_admin = $obj->nom_admin;
+ $this->title = $obj->title;
+ $this->date_fin = $this->db->jdate($obj->date_fin);
+ $this->status = $obj->status;
+ $this->format = $obj->format;
+ $this->mailsonde = $obj->mailsonde;
+ $this->allow_comments = $obj->allow_comments;
+ $this->allow_spy = $obj->allow_spy;
+ $this->sujet = $obj->sujet;
+ $this->fk_user_creat = $obj->fk_user_creat;
+
+ $this->date_m = $this->db->jdate($obj->tls);
+ $ret = 1;
+ } else {
+ $sondage = ($id ? 'id='.$id : 'sondageid='.$numsurvey);
+ $this->error = 'Fetch no poll found for '.$sondage;
+ dol_syslog($this->error, LOG_ERR);
+ $ret = 0;
+ }
+
+ $this->db->free($resql);
+ } else {
+ $this->error = "Error ".$this->db->lasterror();
+ $ret = -1;
+ }
+
+ return $ret;
+ }
+
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param int $notrigger 0=launch triggers after, 1=disable triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = 0)
+ {
+ global $conf, $langs;
+ $error = 0;
+
+ // Clean parameters
+ $this->cleanParameters();
+
+ // Check parameters
+ // Put here code to add a control on parameters values
+
+ // Update request
+ $sql = "UPDATE ".MAIN_DB_PREFIX."opensurvey_sondage SET";
+ $sql .= " id_sondage=".(isset($this->id_sondage) ? "'".$this->db->escape($this->id_sondage)."'" : "null").",";
+ $sql .= " commentaires=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").",";
+ $sql .= " mail_admin=".(isset($this->mail_admin) ? "'".$this->db->escape($this->mail_admin)."'" : "null").",";
+ $sql .= " nom_admin=".(isset($this->nom_admin) ? "'".$this->db->escape($this->nom_admin)."'" : "null").",";
+ $sql .= " titre=".(isset($this->title) ? "'".$this->db->escape($this->title)."'" : "null").",";
+ $sql .= " date_fin=".(dol_strlen($this->date_fin) != 0 ? "'".$this->db->idate($this->date_fin)."'" : 'null').",";
+ $sql .= " status=".(isset($this->status) ? "'".$this->db->escape($this->status)."'" : "null").",";
+ $sql .= " format=".(isset($this->format) ? "'".$this->db->escape($this->format)."'" : "null").",";
+ $sql .= " mailsonde=".(isset($this->mailsonde) ? $this->db->escape($this->mailsonde) : "null").",";
+ $sql .= " allow_comments=".$this->db->escape($this->allow_comments).",";
+ $sql .= " allow_spy=".$this->db->escape($this->allow_spy);
+ $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'";
+
+ $this->db->begin();
+
+ dol_syslog(get_class($this)."::update", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
+
+ if (!$error && !$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('OPENSURVEY_MODIFY', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+
+ // Commit or rollback
+ if ($error)
+ {
+ foreach ($this->errors as $errmsg)
+ {
+ dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
+ $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
+ }
+ $this->db->rollback();
+ return -1 * $error;
+ } else {
+ $this->db->commit();
+ return 1;
+ }
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param int $notrigger 0=launch triggers after, 1=disable triggers
+ * @param string $numsondage Num sondage admin to delete
+ * @return int <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = 0, $numsondage = '')
+ {
+ global $conf, $langs;
+ $error = 0;
+
+ if (empty($numsondage))
+ {
+ $numsondage = $this->id_sondage;
+ }
+
+ $this->db->begin();
+
+ if (!$error)
+ {
+ if (!$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('OPENSURVEY_DELETE', $user);
+ if ($result < 0) $error++;
+ // End call triggers
+ }
+ }
+
+ if (!$error)
+ {
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_comments WHERE id_sondage = '".$this->db->escape($numsondage)."'";
+ dol_syslog(get_class($this)."::delete", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX."opensurvey_user_studs WHERE id_sondage = '".$this->db->escape($numsondage)."'";
+ dol_syslog(get_class($this)."::delete", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."opensurvey_sondage";
+ $sql .= " WHERE id_sondage = '".$this->db->escape($numsondage)."'";
+
+ dol_syslog(get_class($this)."::delete", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
+ }
+
+ // Commit or rollback
+ if ($error)
+ {
+ foreach ($this->errors as $errmsg)
+ {
+ dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
+ $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
+ }
+ $this->db->rollback();
+ return -1 * $error;
+ } else {
+ $this->db->commit();
+ return 1;
+ }
+ }
+
+ /**
+ * Return a link to the object card (with optionaly the picto)
+ *
+ * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+ * @param 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, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+ {
+ global $db, $conf, $langs;
+ global $dolibarr_main_authentication, $dolibarr_main_demo;
+ global $menumanager;
+
+ if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+
+ $result = '';
+
+ $label = img_picto('', $this->picto).'
'.$langs->trans("ShowSurvey").' ';
+ $label .= '
';
+ $label .= '
'.$langs->trans('Ref').': '.$this->ref.'
';
+ $label .= '
'.$langs->trans('Title').': '.$this->title.'
';
+
+ $url = DOL_URL_ROOT.'/opensurvey/card.php?id='.$this->id;
+
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
+ if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+
+ $linkclose = '';
+ if (empty($notooltip))
+ {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+ {
+ $label = $langs->trans("ShowMyObject");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
+ } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+
+ $linkstart = '
';
+ $linkend = ' ';
+
+ $result .= $linkstart;
+ if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ if ($withpicto != 2) $result .= $this->ref;
+ $result .= $linkend;
+
+ return $result;
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return array of lines
+ *
+ * @return int <0 if KO, >0 if OK
+ */
+ public function fetch_lines()
+ {
+ // phpcs:enable
+ $ret = array();
+
+ $sql = "SELECT id_users, nom as name, reponses FROM ".MAIN_DB_PREFIX."opensurvey_user_studs";
+ $sql .= " WHERE id_sondage = '".$this->db->escape($this->id_sondage)."'";
+ $resql = $this->db->query($sql);
+
+ if ($resql)
+ {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < $num)
+ {
+ $obj = $this->db->fetch_object($resql);
+ $tmp = array('id_users'=>$obj->id_users, 'nom'=>$obj->name, 'reponses'=>$obj->reponses);
+
+ $ret[] = $tmp;
+ $i++;
+ }
+ } else dol_print_error($this->db);
+
+ $this->lines = $ret;
+
+ return count($this->lines);
+ }
+
+ /**
+ * Initialise object with example values
+ * Id must be 0 if object instance is a specimen
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ $this->id = 0;
+
+ $this->id_sondage = '';
+ $this->description = 'Description of the specimen survey';
+ $this->mail_admin = '';
+ $this->nom_admin = '';
+ $this->title = 'This is a specimen survey';
+ $this->date_fin = dol_now() + 3600 * 24 * 10;
+ $this->status = 1;
+ $this->format = 'classic';
+ $this->mailsonde = '';
+ }
+
+ /**
+ * Returns all comments for the current opensurvey poll
+ *
+ * @return Object[]
+ */
+ public function getComments()
+ {
+ $comments = array();
+
+ $sql = 'SELECT id_comment, usercomment, comment';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.'opensurvey_comments';
+ $sql .= " WHERE id_sondage='".$this->db->escape($this->id_sondage)."'";
+ $sql .= " ORDER BY id_comment";
+ $resql = $this->db->query($sql);
+
+ if ($resql)
+ {
+ $num_rows = $this->db->num_rows($resql);
+
+ if ($num_rows > 0)
+ {
+ while ($obj = $this->db->fetch_object($resql))
+ {
+ $comments[] = $obj;
+ }
+ }
+ }
+
+ return $comments;
+ }
+
+ /**
+ * Adds a comment to the poll
+ *
+ * @param string $comment Comment content
+ * @param string $comment_user Comment author
+ * @return boolean False in case of the query fails, true if it was successful
+ */
+ public function addComment($comment, $comment_user)
+ {
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."opensurvey_comments (id_sondage, comment, usercomment)";
+ $sql .= " VALUES ('".$this->db->escape($this->id_sondage)."','".$this->db->escape($comment)."','".$this->db->escape($comment_user)."')";
+ $resql = $this->db->query($sql);
+
+ if (!$resql) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Deletes a comment of the poll
+ *
+ * @param int $id_comment Id of the comment
+ * @return boolean False in case of the query fails, true if it was successful
+ */
+ public function deleteComment($id_comment)
+ {
+ $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'opensurvey_comments WHERE id_comment = '.$id_comment.' AND id_sondage = "'.$this->db->escape($this->id_sondage).'"';
+ $resql = $this->db->query($sql);
+
+ if (!$resql) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Cleans all the class variables before doing an update or an insert
+ *
+ * @return void
+ */
+ private function cleanParameters()
+ {
+ $this->id_sondage = trim($this->id_sondage);
+ $this->description = trim($this->description);
+ $this->mail_admin = trim($this->mail_admin);
+ $this->nom_admin = trim($this->nom_admin);
+ $this->title = trim($this->title);
+ $this->status = trim($this->status);
+ $this->format = trim($this->format);
+ $this->mailsonde = ($this->mailsonde ? 1 : 0);
+ $this->allow_comments = ($this->allow_comments ? 1 : 0);
+ $this->allow_spy = ($this->allow_spy ? 1 : 0);
+ $this->sujet = trim($this->sujet);
+ }
+
+
+ /**
+ * Return status label of Order
+ *
+ * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
+ * @return string Libelle
+ */
+ public function getLibStatut($mode)
+ {
+ return $this->LibStatut($this->status, $mode);
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return label of status
+ *
+ * @param int $status Id statut
+ * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
+ * @return string Label of status
+ */
+ public function LibStatut($status, $mode)
+ {
+ // phpcs:enable
+ global $langs, $conf;
+
+ if (empty($this->labelStatus) || empty($this->labelStatusShort))
+ {
+ global $langs;
+ //$langs->load("mymodule");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('Opened');
+ $this->labelStatus[self::STATUS_CLOSED] = $langs->trans('Closed');
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans('Draft');
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans('Opened');
+ $this->labelStatusShort[self::STATUS_CLOSED] = $langs->trans('Closed');
+ }
+
+ $statusType = 'status'.$status;
+ if ($status == self::STATUS_VALIDATED) {
+ if (0) $statusType = 'status1';
+ else $statusType = 'status4';
+ }
+ if ($status == self::STATUS_CLOSED) $statusType = 'status6';
+
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
+ }
}
diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php
index 697c51f09c4..8ae09ea45aa 100644
--- a/htdocs/product/class/product.class.php
+++ b/htdocs/product/class/product.class.php
@@ -2210,7 +2210,7 @@ class Product extends CommonObject
}
}*/
} else {
- $this->error=$this->db->lasterror;
+ $this->error = $this->db->lasterror;
return -1;
}
}
@@ -2255,12 +2255,12 @@ class Product extends CommonObject
}
$this->prices_by_qty_list[0] = $resultat;
} else {
- $this->error=$this->db->lasterror;
+ $this->error = $this->db->lasterror;
return -1;
}
}
} else {
- $this->error=$this->db->lasterror;
+ $this->error = $this->db->lasterror;
return -1;
}
} elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) // prices per customer and quantity
@@ -2314,12 +2314,12 @@ class Product extends CommonObject
}
$this->prices_by_qty_list[$i] = $resultat;
} else {
- $this->error=$this->db->lasterror;
+ $this->error = $this->db->lasterror;
return -1;
}
}
} else {
- $this->error=$this->db->lasterror;
+ $this->error = $this->db->lasterror;
return -1;
}
}
@@ -2346,7 +2346,7 @@ class Product extends CommonObject
return 0;
}
} else {
- $this->error=$this->db->lasterror;
+ $this->error = $this->db->lasterror;
return -1;
}
}
@@ -4280,9 +4280,9 @@ class Product extends CommonObject
if ($maxlength) { $newref = dol_trunc($newref, $maxlength, 'middle');
}
- if ($this->type == Product::TYPE_PRODUCT) { $label = '
'.$langs->trans("Product").' ';
+ if ($this->type == Product::TYPE_PRODUCT) { $label = img_picto('', 'product').'
'.$langs->trans("Product").' ';
}
- if ($this->type == Product::TYPE_SERVICE) { $label = '
'.$langs->trans("Service").' ';
+ if ($this->type == Product::TYPE_SERVICE) { $label = img_picto('', 'service').'
'.$langs->trans("Service").' ';
}
if (!empty($this->ref)) {
$label .= '
'.$langs->trans('ProductRef').': '.$this->ref;
@@ -4769,7 +4769,7 @@ class Product extends CommonObject
if ($result < 0) dol_print_error($this->db, $this->error);
$stock_sending_client = $this->stats_expedition['qty'];
}
- if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || ! empty($conf->supplier_order->enabled))
+ if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled))
{
$filterStatus = '1,2,3,4';
if (isset($includedraftpoforvirtual)) $filterStatus = '0,'.$filterStatus;
@@ -5204,15 +5204,17 @@ class Product extends CommonObject
$this->barcode = -1; // Create barcode automatically
}
- /**
- * Returns the text label from units dictionary
- *
- * @param string $type Label type (long or short)
- * @return string|int <0 if ko, label if ok
- */
- public function getLabelOfUnit($type = 'long')
- {
- global $langs;
+ /**
+ * Returns the label, shot_label or code found in units dictionary from ->fk_unit.
+ * A langs->trans() must be called on result to get translated value.
+ *
+ * @param string $type Label type (long, short or code)
+ * @return string|int <0 if KO, label if OK (Example: 'long', 'short', 'unitCODE')
+ * @see getLabelOfUnit() in CommonObjectLine
+ */
+ public function getLabelOfUnit($type = 'long')
+ {
+ global $langs;
if (!$this->fk_unit) {
return '';
@@ -5220,25 +5222,24 @@ class Product extends CommonObject
$langs->load('products');
- $label_type = 'label';
+ $label_type = 'label';
+ if ($type == 'short') $label_type = 'short_label';
+ elseif ($type == 'code') $label_type = 'code';
- if ($type == 'short') {
- $label_type = 'short_label';
- }
-
- $sql = 'select '.$label_type.', code from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit;
- $resql = $this->db->query($sql);
- if ($resql && $this->db->num_rows($resql) > 0) {
- $res = $this->db->fetch_array($resql);
- $label = ($label_type == 'short' ? $res[$label_type] : 'unit'.$res['code']);
- $this->db->free($resql);
- return $label;
- } else {
- $this->error = $this->db->error().' sql='.$sql;
- dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
- return -1;
- }
- }
+ $sql = 'select '.$label_type.', code from '.MAIN_DB_PREFIX.'c_units where rowid='.$this->fk_unit;
+ $resql = $this->db->query($sql);
+ if ($resql && $this->db->num_rows($resql) > 0) {
+ $res = $this->db->fetch_array($resql);
+ if ($label_type == 'code') $label = 'unit'.$res['code'];
+ else $label = $res[$label_type];
+ $this->db->free($resql);
+ return $label;
+ } else {
+ $this->error = $this->db->error().' sql='.$sql;
+ dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
+ return -1;
+ }
+ }
/**
* Return if object has a sell-by date or eat-by date
diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php
index d2a190f8149..56f91bfa2ee 100644
--- a/htdocs/product/fournisseurs.php
+++ b/htdocs/product/fournisseurs.php
@@ -858,6 +858,52 @@ SCRIPT;
print_barre_liste($langs->trans('SupplierPrices'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit, 1);
+ // Definition of fields for lists
+ // Some fields are missing because they are not included in the database query
+ $arrayfields = array(
+ 'pfp.datec'=>array('label'=>$langs->trans("AppliedPricesFrom"), 'checked'=>1, 'position'=>1),
+ 's.nom'=>array('label'=>$langs->trans("Suppliers"), 'checked'=>1, 'position'=>2),
+ 'pfp.fk_availability'=>array('label'=>$langs->trans("Availability"), 'enabled' => !empty($conf->global->FOURN_PRODUCT_AVAILABILITY), 'checked'=>0, 'position'=>4),
+ 'pfp.quantity'=>array('label'=>$langs->trans("QtyMin"), 'checked'=>1, 'position'=>5),
+ 'pfp.unitprice'=>array('label'=>$langs->trans("UnitPriceHT"), 'checked'=>1, 'position'=>9),
+ 'pfp.multicurrency_unitprice'=>array('label'=>$langs->trans("UnitPriceHTCurrency"), 'enabled' => $conf->multicurrency->enabled, 'checked'=>0, 'position'=>10),
+ 'pfp.delivery_time_days'=>array('label'=>$langs->trans("NbDaysToDelivery"), 'checked'=>1, 'position'=>13),
+ 'pfp.supplier_reputation'=>array('label'=>$langs->trans("ReputationForThisProduct"), 'checked'=>1, 'position'=>14),
+ 'pfp.barcode'=>array('label'=>$langs->trans("BarcodeValue"), 'enabled' => $conf->barcode->enabled, 'checked'=>0, 'position'=>15),
+ 'pfp.fk_barcode_type'=>array('label'=>$langs->trans("BarcodeType"), 'enabled' => $conf->barcode->enabled, 'checked'=>0, 'position'=>16),
+ 'pfp.packaging'=>array('label'=>$langs->trans("PackagingForThisProduct"), 'enabled' => !empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING), 'checked'=>0, 'position'=>17),
+ 'pfp.tms'=>array('label'=>$langs->trans("DateModification"), 'enabled' => $conf->barcode->enabled, 'checked'=>1, 'position'=>18),
+ );
+
+ // fetch optionals attributes and labels
+ $extrafields->fetch_name_optionals_label("product_fournisseur_price");
+ $extralabels = $extrafields->attributes["product_fournisseur_price"]['label'];
+
+ if (!empty($extralabels)) {
+ foreach ($extralabels as $key => $value) {
+ // Show field if not hidden
+ if (!empty($extrafields->attributes["product_fournisseur_price"]['list'][$key]) && $extrafields->attributes["product_fournisseur_price"]['list'][$key] != 3) {
+ if (!empty($extrafields->attributes["product_fournisseur_price"]['langfile'][$key])) $langs->load($extrafields->attributes["product_fournisseur_price"]['langfile'][$key]);
+ if (!empty($extrafields->attributes["product_fournisseur_price"]['help'][$key])) $extratitle = $form->textwithpicto($langs->trans($value), $langs->trans($extrafields->attributes["product_fournisseur_price"]['help'][$key]));
+ else $extratitle = $langs->trans($value);
+ $arrayfields['ef.'.$key] = array('label'=>$extratitle, 'checked'=>0, 'position'=>(end($arrayfields)['position']+1));
+ }
+ }
+ }
+
+ // Selection of new fields
+ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+
+ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
+ $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
+
+ print '
';
}
}
}
diff --git a/htdocs/product/inventory/card.php b/htdocs/product/inventory/card.php
index 3949f8af6fe..357251fe512 100644
--- a/htdocs/product/inventory/card.php
+++ b/htdocs/product/inventory/card.php
@@ -447,11 +447,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
// Documents
if ($includedocgeneration) {
$objref = dol_sanitizeFileName($object->ref);
- $relativepath = $objref . '/' . $objref . '.pdf';
+ $relativepath = $objref.'/'.$objref.'.pdf';
$filedir = $conf->mymodule->dir_output.'/'.$object->element.'/'.$objref;
- $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
- $genallowed = $user->rights->mymodule->myobject->read; // If you can read, you can build the PDF to read content
- $delallowed = $user->rights->mymodule->myobject->write; // If you can create/edit, you can remove a file on card
+ $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
+ $genallowed = $user->rights->mymodule->myobject->read; // If you can read, you can build the PDF to read content
+ $delallowed = $user->rights->mymodule->myobject->write; // If you can create/edit, you can remove a file on card
print $formfile->showdocuments('mymodule:MyObject', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang);
}
diff --git a/htdocs/product/inventory/inventory.php b/htdocs/product/inventory/inventory.php
index 001194495bb..790d30b444f 100644
--- a/htdocs/product/inventory/inventory.php
+++ b/htdocs/product/inventory/inventory.php
@@ -133,7 +133,7 @@ if (empty($reshook))
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")), null, 'errors');
}
- if (! $error && ! empty($conf->productbatch->enabled)) {
+ if (!$error && !empty($conf->productbatch->enabled)) {
$tmpproduct = new Product($db);
$result = $tmpproduct->fetch($fk_product);
@@ -320,53 +320,53 @@ if ($object->id > 0)
print '
';
print '';
} else {
- 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');
+ 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))
- {
- if ($object->status == Inventory::STATUS_DRAFT)
- {
- if ($permissiontoadd)
- {
- print '
id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").') '."\n";
- } else {
- print '
'.$langs->trans('Validate').' ('.$langs->trans("Start").') '."\n";
- }
- }
+ if (empty($reshook))
+ {
+ if ($object->status == Inventory::STATUS_DRAFT)
+ {
+ if ($permissiontoadd)
+ {
+ print '
id.'&action=confirm_validate&confirm=yes">'.$langs->trans("Validate").' ('.$langs->trans("Start").') '."\n";
+ } else {
+ print '
'.$langs->trans('Validate').' ('.$langs->trans("Start").') '."\n";
+ }
+ }
- if ($object->status == Inventory::STATUS_VALIDATED)
- {
- if ($permissiontoadd)
- {
- /*
+ if ($object->status == Inventory::STATUS_VALIDATED)
+ {
+ if ($permissiontoadd)
+ {
+ /*
if ($conf->barcode->enabled) {
print '
'.$langs->trans("UpdateByScaningProductBarcode").' ';
}
if ($conf->productbatch->enabled) {
print '
'.$langs->trans('UpdateByScaningLot').' ';
}*/
- if ($conf->barcode->enabled || $conf->productbatch->enabled) {
- print '
'.$langs->trans("UpdateByScaning").' ';
- }
- } else {
- print '
'.$langs->trans('Save').' '."\n";
- }
- }
+ if ($conf->barcode->enabled || $conf->productbatch->enabled) {
+ print '
'.$langs->trans("UpdateByScaning").' ';
+ }
+ } else {
+ print '
'.$langs->trans('Save').' '."\n";
+ }
+ }
- if ($object->status == Inventory::STATUS_VALIDATED)
- {
- if ($permissiontoadd)
- {
- print '
id.'&action=record">'.$langs->trans("Finish").' '."\n";
- } else {
- print '
'.$langs->trans('Finish').' '."\n";
- }
- }
+ if ($object->status == Inventory::STATUS_VALIDATED)
+ {
+ if ($permissiontoadd)
+ {
+ print '
id.'&action=record">'.$langs->trans("Finish").' '."\n";
+ } else {
+ print '
'.$langs->trans('Finish').' '."\n";
+ }
+ }
- /*if ($object->status == Inventory::STATUS_VALIDATED)
+ /*if ($object->status == Inventory::STATUS_VALIDATED)
{
if ($permissiontoadd)
{
diff --git a/htdocs/product/list.php b/htdocs/product/list.php
index d28bbef42c3..6d9a60b0c66 100644
--- a/htdocs/product/list.php
+++ b/htdocs/product/list.php
@@ -219,7 +219,7 @@ $arrayfields = array(
);
// MultiPrices
-if ($conf->global->PRODUIT_MULTIPRICES){
+if ($conf->global->PRODUIT_MULTIPRICES) {
for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++)
{
$keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i;
@@ -753,7 +753,7 @@ if ($resql)
}
// Multiprice
- if ($conf->global->PRODUIT_MULTIPRICES){
+ if ($conf->global->PRODUIT_MULTIPRICES) {
foreach ($arraypricelevel as $key => $value)
{
if (!empty($arrayfields['p.sellprice'.$key]['checked']))
@@ -905,7 +905,7 @@ if ($resql)
}
// Multiprices
- if ($conf->global->PRODUIT_MULTIPRICES){
+ if ($conf->global->PRODUIT_MULTIPRICES) {
foreach ($arraypricelevel as $key => $value)
{
if (!empty($arrayfields['p.sellprice'.$key]['checked']))
@@ -1265,7 +1265,7 @@ if ($resql)
// Multiprices
- if ($conf->global->PRODUIT_MULTIPRICES){
+ if ($conf->global->PRODUIT_MULTIPRICES) {
foreach ($arraypricelevel as $key => $value)
{
if (!empty($arrayfields['p.sellprice'.$key]['checked']))
@@ -1389,7 +1389,7 @@ if ($resql)
if ($obj->fk_product_type != 1)
{
if ($obj->seuil_stock_alerte != '' && $product_static->stock_reel < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' ';
- print $product_static->stock_reel;
+ print price2num($product_static->stock_reel, 'MS');
}
print '';
if (!$i) $totalarray['nbfield']++;
@@ -1401,7 +1401,7 @@ if ($resql)
if ($obj->fk_product_type != 1)
{
if ($obj->seuil_stock_alerte != '' && $product_static->stock_theorique < (float) $obj->seuil_stock_alerte) print img_warning($langs->trans("StockLowerThanLimit", $obj->seuil_stock_alerte)).' ';
- print $product_static->stock_theorique;
+ print price2num($product_static->stock_theorique, 'MS');
}
print '';
if (!$i) $totalarray['nbfield']++;
diff --git a/htdocs/product/stock/class/api_stockmovements.class.php b/htdocs/product/stock/class/api_stockmovements.class.php
index a8e15f8f28e..1efa81bc0a8 100644
--- a/htdocs/product/stock/class/api_stockmovements.class.php
+++ b/htdocs/product/stock/class/api_stockmovements.class.php
@@ -303,7 +303,7 @@ class StockMovements extends DolibarrApi
unset($object->note_public);
unset($object->shipping_method_id);
unset($object->fk_account);
- unset($object->modelpdf);
+ unset($object->model_pdf);
unset($object->fk_delivery_address);
unset($object->cond_reglement);
unset($object->cond_reglement_id);
diff --git a/htdocs/product/stock/class/entrepot.class.php b/htdocs/product/stock/class/entrepot.class.php
index 25857803843..a16b1ee189c 100644
--- a/htdocs/product/stock/class/entrepot.class.php
+++ b/htdocs/product/stock/class/entrepot.class.php
@@ -707,7 +707,7 @@ class Entrepot extends CommonObject
$result = '';
- $label = '
'.$langs->trans("Warehouse").' ';
+ $label = img_picto('', $this->picto).'
'.$langs->trans("Warehouse").' ';
$label .= '
'.$langs->trans('Ref').': '.(empty($this->ref) ? (empty($this->label) ? $this->libelle : $this->label) : $this->ref);
if (!empty($this->lieu)) {
$label .= '
'.$langs->trans('LocationSummary').': '.$this->lieu;
@@ -736,7 +736,7 @@ class Entrepot extends CommonObject
$result .= $linkstart;
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);
- if ($withpicto != 2) $result .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label)?$this->libelle:$this->label));
+ if ($withpicto != 2) $result .= (($showfullpath || !empty($conf->global->STOCK_ALWAYS_SHOW_FULL_ARBO)) ? $this->get_full_arbo() : (empty($this->label) ? $this->libelle : $this->label));
$result .= $linkend;
global $action;
@@ -867,8 +867,8 @@ class Entrepot extends CommonObject
if (!dol_strlen($modele)) {
$modele = 'standard';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->STOCK_ADDON_PDF)) {
$modele = $conf->global->STOCK_ADDON_PDF;
}
diff --git a/htdocs/product/stock/class/mouvementstock.class.php b/htdocs/product/stock/class/mouvementstock.class.php
index d1c703924d4..bfdfb14f6e8 100644
--- a/htdocs/product/stock/class/mouvementstock.class.php
+++ b/htdocs/product/stock/class/mouvementstock.class.php
@@ -1172,8 +1172,8 @@ class MouvementStock extends CommonObject
if (!dol_strlen($modele)) {
$modele = 'stdmovement';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->MOUVEMENT_ADDON_PDF)) {
$modele = $conf->global->MOUVEMENT_ADDON_PDF;
}
diff --git a/htdocs/product/stock/class/productlot.class.php b/htdocs/product/stock/class/productlot.class.php
index b495f64485a..9ff36db3c5b 100644
--- a/htdocs/product/stock/class/productlot.class.php
+++ b/htdocs/product/stock/class/productlot.class.php
@@ -56,17 +56,46 @@ class Productlot extends CommonObject
*/
public $ismultientitymanaged = 1;
+
+ /**
+ * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
+ * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
+ * 'label' the translation key.
+ * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
+ * 'position' is the sort order of field.
+ * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
+ * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
+ * 'noteditable' says if field is not editable (1 or 0)
+ * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
+ * 'index' if we want an index in database.
+ * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
+ * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
+ * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
+ * 'css' is the CSS style to use on field. For example: 'maxwidth200'
+ * 'help' is a string visible as a tooltip on field
+ * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
+ * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
+ * 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
+ * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
+ * 'comment' is not used. You can store here any text of your choice. It is not used by application.
+ *
+ * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
+ */
+
/**
* @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, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
- 'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>1, 'notnull'=>0, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'comment'=>'Batch'),
- 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
- 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
- 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
- 'fk_user_creat'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
- 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511)
+ 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'),
+ 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>15, 'notnull'=>1, 'index'=>1, 'searchall'=>1),
+ 'batch' => array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>1, 'notnull'=>0, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'comment'=>'Batch', 'searchall'=>1),
+ 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
+ 'sellby' => array('type'=>'date', 'label'=>'SellByDate', 'enabled'=>'empty($conf->global->PRODUCT_DISABLE_SELLBY)?1:0', 'visible'=>5, 'position'=>60),
+ 'eatby' => array('type'=>'date', 'label'=>'EatByDate', 'enabled'=>'empty($conf->global->PRODUCT_DISABLE_EATBY)?1:0', 'visible'=>5, 'position'=>62),
+ 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500),
+ 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
+ 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
+ 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511)
);
/**
diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php
index fe6e8d3e829..cd83f2c19c8 100644
--- a/htdocs/product/stock/product.php
+++ b/htdocs/product/stock/product.php
@@ -39,7 +39,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productstockentrepot.class.php';
if (!empty($conf->productbatch->enabled)) {
- require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
+ require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
}
if (!empty($conf->projet->enabled)) {
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
@@ -88,7 +88,7 @@ $extrafields->fetch_name_optionals_label($object->table_element);
if ($id > 0 || !empty($ref))
{
- $result = $object->fetch($id, $ref);
+ $result = $object->fetch($id, $ref);
}
if (empty($id) && !empty($object->id)) $id = $object->id;
@@ -100,9 +100,9 @@ $canvas = !empty($object->canvas) ? $object->canvas : GETPOST("canvas");
$objcanvas = null;
if (!empty($canvas))
{
- require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
- $objcanvas = new Canvas($db, $action);
- $objcanvas->getCanvas('stockproduct', 'card', $canvas);
+ require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';
+ $objcanvas = new Canvas($db, $action);
+ $objcanvas->getCanvas('stockproduct', 'card', $canvas);
}
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@@ -168,27 +168,27 @@ if ($action == 'delete_productstockwarehouse' && !empty($user->rights->produit->
// Set stock limit
if ($action == 'setseuil_stock_alerte' && !empty($user->rights->produit->creer))
{
- $object = new Product($db);
- $result = $object->fetch($id);
- $object->seuil_stock_alerte = $stocklimit;
- $result = $object->update($object->id, $user, 0, 'update');
- if ($result < 0)
- setEventMessages($object->error, $object->errors, 'errors');
- //else
- // setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs');
- $action = '';
+ $object = new Product($db);
+ $result = $object->fetch($id);
+ $object->seuil_stock_alerte = $stocklimit;
+ $result = $object->update($object->id, $user, 0, 'update');
+ if ($result < 0)
+ setEventMessages($object->error, $object->errors, 'errors');
+ //else
+ // setEventMessages($lans->trans("SavedRecordSuccessfully"), null, 'mesgs');
+ $action = '';
}
// Set desired stock
if ($action == 'setdesiredstock' && !empty($user->rights->produit->creer))
{
- $object = new Product($db);
- $result = $object->fetch($id);
- $object->desiredstock = $desiredstock;
- $result = $object->update($object->id, $user, 0, 'update');
- if ($result < 0)
- setEventMessages($object->error, $object->errors, 'errors');
- $action = '';
+ $object = new Product($db);
+ $result = $object->fetch($id);
+ $object->desiredstock = $desiredstock;
+ $result = $object->update($object->id, $user, 0, 'update');
+ if ($result < 0)
+ setEventMessages($object->error, $object->errors, 'errors');
+ $action = '';
}
@@ -258,12 +258,12 @@ if ($action == "correct_stock" && !$cancel)
); // We do not change value of stock for a correction
} else {
$result = $object->correct_stock(
- $user,
- GETPOST("id_entrepot", 'int'),
+ $user,
+ GETPOST("id_entrepot", 'int'),
$nbpiece,
- GETPOST("mouvement", 'int'),
- GETPOST("label", 'alphanohtml'),
- $priceunit,
+ GETPOST("mouvement", 'int'),
+ GETPOST("label", 'alphanohtml'),
+ $priceunit,
GETPOST('inventorycode', 'alphanohtml'),
$origin_element,
$origin_id
@@ -277,12 +277,12 @@ if ($action == "correct_stock" && !$cancel)
header("Location: ".$backtopage);
exit;
} else {
- header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
+ header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
exit;
}
} else {
- setEventMessages($object->error, $object->errors, 'errors');
- $action = 'correction';
+ setEventMessages($object->error, $object->errors, 'errors');
+ $action = 'correction';
}
}
}
@@ -311,15 +311,15 @@ if ($action == "transfert_stock" && !$cancel)
}
if (!empty($conf->productbatch->enabled))
{
- $object = new Product($db);
- $result = $object->fetch($id);
+ $object = new Product($db);
+ $result = $object->fetch($id);
- if ($object->hasbatch() && !$batchnumber)
- {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors');
- $error++;
- $action = 'transfert';
- }
+ if ($object->hasbatch() && !$batchnumber)
+ {
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("batch_number")), null, 'errors');
+ $error++;
+ $action = 'transfert';
+ }
}
if (!$error)
@@ -399,31 +399,31 @@ if ($action == "transfert_stock" && !$cancel)
} else {
if (!$error)
{
- // Remove stock
- $result1 = $object->correct_stock(
- $user,
- GETPOST("id_entrepot", 'int'),
- $nbpiece,
- 1,
- GETPOST("label", 'alphanohtml'),
- $pricesrc,
- GETPOST('inventorycode', 'alphanohtml')
- );
- if ($result1 < 0) $error++;
+ // Remove stock
+ $result1 = $object->correct_stock(
+ $user,
+ GETPOST("id_entrepot", 'int'),
+ $nbpiece,
+ 1,
+ GETPOST("label", 'alphanohtml'),
+ $pricesrc,
+ GETPOST('inventorycode', 'alphanohtml')
+ );
+ if ($result1 < 0) $error++;
}
if (!$error)
{
- // Add stock
- $result2 = $object->correct_stock(
- $user,
- GETPOST("id_entrepot_destination", 'int'),
- $nbpiece,
- 0,
- GETPOST("label", 'alphanohtml'),
- $pricedest,
- GETPOST('inventorycode', 'alphanohtml')
- );
- if ($result2 < 0) $error++;
+ // Add stock
+ $result2 = $object->correct_stock(
+ $user,
+ GETPOST("id_entrepot_destination", 'int'),
+ $nbpiece,
+ 0,
+ GETPOST("label", 'alphanohtml'),
+ $pricedest,
+ GETPOST('inventorycode', 'alphanohtml')
+ );
+ if ($result2 < 0) $error++;
}
}
@@ -452,35 +452,35 @@ if ($action == "transfert_stock" && !$cancel)
// Update batch information
if ($action == 'updateline' && GETPOST('save') == $langs->trans('Save'))
{
- $pdluo = new Productbatch($db);
- $result = $pdluo->fetch(GETPOST('pdluoid', 'int'));
+ $pdluo = new Productbatch($db);
+ $result = $pdluo->fetch(GETPOST('pdluoid', 'int'));
- if ($result > 0)
- {
- if ($pdluo->id)
- {
- if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) {
- setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors');
- } else {
- $d_eatby = dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']);
- $d_sellby = dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']);
- $pdluo->batch = $batchnumber;
- $pdluo->eatby = $d_eatby;
- $pdluo->sellby = $d_sellby;
- $result = $pdluo->update($user);
- if ($result < 0)
- {
- setEventMessages($pdluo->error, $pdluo->errors, 'errors');
- }
- }
- } else {
- setEventMessages($langs->trans('BatchInformationNotfound'), null, 'errors');
- }
- } else {
- setEventMessages($pdluo->error, null, 'errors');
- }
- header("Location: product.php?id=".$id);
- exit;
+ if ($result > 0)
+ {
+ if ($pdluo->id)
+ {
+ if ((!GETPOST("sellby")) && (!GETPOST("eatby")) && (!$batchnumber)) {
+ setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("atleast1batchfield")), null, 'errors');
+ } else {
+ $d_eatby = dol_mktime(0, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']);
+ $d_sellby = dol_mktime(0, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']);
+ $pdluo->batch = $batchnumber;
+ $pdluo->eatby = $d_eatby;
+ $pdluo->sellby = $d_sellby;
+ $result = $pdluo->update($user);
+ if ($result < 0)
+ {
+ setEventMessages($pdluo->error, $pdluo->errors, 'errors');
+ }
+ }
+ } else {
+ setEventMessages($langs->trans('BatchInformationNotfound'), null, 'errors');
+ }
+ } else {
+ setEventMessages($pdluo->error, null, 'errors');
+ }
+ header("Location: product.php?id=".$id);
+ exit;
}
@@ -528,17 +528,17 @@ if ($id > 0 || $ref)
dol_htmloutput_events();
- $linkback = '
'.$langs->trans("BackToList").' ';
+ $linkback = '
'.$langs->trans("BackToList").' ';
- $shownav = 1;
- if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0;
+ $shownav = 1;
+ if ($user->socid && !in_array('stock', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0;
- dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
+ dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');
- print '
';
+ print '
';
- print '
';
- print '
';
+ print '
';
+ print '';
if (!$variants) {
if ($conf->productbatch->enabled) {
@@ -629,7 +629,7 @@ if ($id > 0 || $ref)
$text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) ? $langs->trans("ReStockOnBill").' ' : '');
$text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) ? $langs->trans("ReStockOnValidateOrder").' ' : '');
$text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) ? $langs->trans("ReStockOnDispatchOrder").' ' : '');
- $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) ? $langs->trans("StockOnReception").' ' : '');
+ $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) ? $langs->trans("StockOnReception").' ' : '');
print '';
print $form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1);
@@ -656,13 +656,13 @@ if ($id > 0 || $ref)
// Number of product from customer order already sent (partial shipping)
if (!empty($conf->expedition->enabled)) {
- require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
- $filterShipmentStatus = '';
- if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
- $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
- } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
- $filterShipmentStatus = Expedition::STATUS_CLOSED;
- }
+ require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
+ $filterShipmentStatus = '';
+ if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
+ $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
+ } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
+ $filterShipmentStatus = Expedition::STATUS_CLOSED;
+ }
if ($found) $helpondiff .= ' '; else $found = 1;
$result = $object->load_stats_sending(0, '2', 1, $filterShipmentStatus);
$helpondiff .= $langs->trans("ProductQtyInShipmentAlreadySent").': '.$object->stats_expedition['qty'];
@@ -730,8 +730,8 @@ if ($id > 0 || $ref)
}
print "
";
- print '';
- print '
';
+ print '';
+ print '
';
dol_fiche_end();
}
@@ -763,7 +763,7 @@ if (empty($reshook))
{
if (empty($action) && $object->id)
{
- print "\n";
+ print "
\n";
if ($user->rights->stock->mouvement->creer)
{
diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php
index ec5e3ebde69..c7d9facf74d 100644
--- a/htdocs/product/stock/productlot_list.php
+++ b/htdocs/product/stock/productlot_list.php
@@ -38,7 +38,8 @@ $langs->loadLangs(array('stocks', 'productbatch', 'other', 'users'));
$id = GETPOST('id', 'int');
$action = GETPOST('action', 'alpha');
$backtopage = GETPOST('backtopage', 'alpha');
-$toselect = GETPOST('toselect', 'array');
+$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
+$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectlist'; // To manage different context of search
$optioncss = GETPOST('optioncss', 'alpha');
$search_entity = GETPOST('search_entity', 'int');
@@ -57,72 +58,75 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined,
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
-if (!$sortfield) $sortfield = "t.batch"; // Set here default search field
-if (!$sortorder) $sortorder = "ASC";
-
-// Protection if external user
-$socid = 0;
-if ($user->socid > 0)
-{
- $socid = $user->socid;
- //accessforbidden();
-}
// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array
$object = new Productlot($db);
-$hookmanager->initHooks(array('product_lotlist'));
$extrafields = new ExtraFields($db);
+$diroutputmassaction = $conf->mymodule->dir_output.'/temp/massgeneration/'.$user->id;
+$hookmanager->initHooks(array('product_lotlist'));
-// fetch optionals attributes and labels
+// Fetch optionals attributes and labels
$extrafields->fetch_name_optionals_label($object->table_element);
+//$extrafields->fetch_name_optionals_label($object->table_element_line);
$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
-// List of fields to search into when doing a "search in all"
-$fieldstosearchall = array(
- 't.ref'=>'Ref',
- 't.note_public'=>'NotePublic',
-);
+// Default sort order (if not yet defined by previous GETPOST)
+if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
+if (!$sortorder) $sortorder = "ASC";
-// Definition of fields for list
-$arrayfields = array(
- //'t.entity'=>array('label'=>$langs->trans("Fieldentity"), 'checked'=>1),
- 't.batch'=>array('label'=>$langs->trans("Batch"), 'checked'=>1),
- 't.fk_product'=>array('label'=>$langs->trans("Product"), 'checked'=>1),
- 't.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>1),
- 't.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>1),
- //'t.import_key'=>array('label'=>$langs->trans("ImportId"), 'checked'=>1),
- //'t.entity'=>array('label'=>$langs->trans("Entity"), 'checked'=>1, 'enabled'=>(! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))),
- //'t.fk_user_creat'=>array('label'=>$langs->trans("UserCreationShort"), 'checked'=>0, 'position'=>500),
- //'t.fk_user_modif'=>array('label'=>$langs->trans("UserModificationShort"), 'checked'=>0, 'position'=>500),
- 't.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500),
- 't.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500),
- //'t.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000),
-);
-if (!empty($conf->global->PRODUCT_DISABLE_SELLBY)) {
- unset($arrayfields['t.sellby']);
+// Initialize array of search criterias
+$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
+$search = array();
+foreach ($object->fields as $key => $val)
+{
+ if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha');
}
-if (!empty($conf->global->PRODUCT_DISABLE_EATBY)) {
- unset($arrayfields['t.eatby']);
+
+// List of fields to search into when doing a "search in all"
+$fieldstosearchall = array();
+foreach ($object->fields as $key => $val)
+{
+ if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
+}
+
+// Definition of array of fields for columns
+$arrayfields = array();
+foreach ($object->fields as $key => $val)
+{
+ // If $val['visible']==0, then we never show the field
+ if (!empty($val['visible'])) {
+ $visible = dol_eval($val['visible'], 1);
+ $arrayfields['t.'.$key] = array(
+ 'label'=>$val['label'],
+ 'checked'=>(($visible < 0) ? 0 : 1),
+ 'enabled'=>($visible != 3 && dol_eval($val['enabled'], 1)),
+ 'position'=>$val['position']
+ );
+ }
}
// Extra fields
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
{
foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
{
- if (!empty($extrafields->attributes[$object->table_element]['list'][$key]))
- $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]));
+ if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
+ $arrayfields["ef.".$key] = array(
+ 'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
+ 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1),
+ 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key],
+ 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key]),
+ 'langfile'=>$extrafields->attributes[$object->table_element]['langfile'][$key]
+ );
+ }
}
}
$object->fields = dol_sort_array($object->fields, 'position');
$arrayfields = dol_sort_array($arrayfields, 'position');
-// Load object if id or ref is provided as parameter
-if (($id > 0 || !empty($ref)) && $action != 'add')
-{
- $result = $object->fetch($id, $ref);
- if ($result < 0) dol_print_error($db);
-}
+$permissiontoread = $user->rights->stock->read;
+$permissiontoadd = $user->rights->stock->write;
+$permissiontodelete = $user->rights->stock->delete;
@@ -131,425 +135,416 @@ if (($id > 0 || !empty($ref)) && $action != 'add')
*/
if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
-if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'confirm_presend') { $massaction = ''; }
+if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
$parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
-include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
-
-// Purge search criteria
-if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
-{
- $search_entity = '';
- $search_product = '';
- $search_batch = '';
- $search_fk_user_creat = '';
- $search_fk_user_modif = '';
- $search_import_key = '';
- $search_date_creation = '';
- $search_date_update = '';
- $toselect = array();
- $search_array_options = array();
-}
-
-
if (empty($reshook))
{
+ // Selection of new fields
+ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
+
+ // Purge search criteria
+ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
+ {
+ foreach ($object->fields as $key => $val)
+ {
+ $search[$key] = '';
+ }
+ $toselect = '';
+ $search_array_options = array();
+ }
+ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
+ || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha'))
+ {
+ $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
+ }
+
+ // Mass actions
$objectclass = 'ProductLot';
$objectlabel = 'LotSerial';
- $permissiontoread = $user->rights->stock->read;
- $permissiontodelete = $user->rights->stock->delete;
- $uploaddir = $conf->stock->dir_output;
+ $uploaddir = $conf->productbatch->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}
-
-
/*
* VIEW
*/
-$now = dol_now();
$form = new Form($db);
-$productstatic = new Product($db);
-//$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes";
+$now = dol_now();
+
+//$help_url="EN:Module_MyObject|FR:Module_MyObject_FR|ES:Módulo_MyObject";
$help_url = '';
$title = $langs->trans('LotSerialList');
-llxHeader('', $title, $help_url);
-
-// Put here content of your page
-
-// Example : Adding jquery code
-print '';
-$sql = "SELECT";
-$sql .= " t.rowid,";
-$sql .= " t.entity,";
-$sql .= " t.fk_product,";
-$sql .= " t.batch,";
-$sql .= " t.sellby,";
-$sql .= " t.eatby,";
-$sql .= " t.datec as date_creation,";
-$sql .= " t.tms as date_update,";
-$sql .= " t.fk_user_creat,";
-$sql .= " t.fk_user_modif,";
-$sql .= " t.import_key,";
-$sql .= " p.fk_product_type as product_type,";
-$sql .= " p.ref as product_ref,";
-$sql .= " p.label as product_label,";
-$sql .= " p.tosell,";
-$sql .= " p.tobuy,";
-$sql .= " p.tobatch";
-// Add fields for extrafields
+// Build and execute select
+// --------------------------------------------------------------------
+$sql = 'SELECT ';
+foreach ($object->fields as $key => $val)
+{
+ $sql .= 't.'.$key.', ';
+}
+// Add fields from extrafields
if (!empty($extrafields->attributes[$object->table_element]['label'])) {
- foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : '');
+ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
}
// Add fields from hooks
$parameters = array();
-$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
-$sql .= $hookmanager->resPrint;
-$sql .= " FROM ".MAIN_DB_PREFIX."product_lot as t";
+$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
+$sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
+$sql = preg_replace('/,\s*$/', '', $sql);
+$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
-$sql .= ", ".MAIN_DB_PREFIX."product as p";
-$sql .= " WHERE p.rowid = t.fk_product";
-$sql .= " AND p.entity IN (".getEntity('product').")";
-
-if ($search_entity) $sql .= natural_search("entity", $search_entity);
-if ($search_product) $sql .= natural_search("p.ref", $search_product);
-if ($search_batch) $sql .= natural_search("batch", $search_batch);
-if ($search_fk_user_creat) $sql .= natural_search("fk_user_creat", $search_fk_user_creat);
-if ($search_fk_user_modif) $sql .= natural_search("fk_user_modif", $search_fk_user_modif);
-if ($search_import_key) $sql .= natural_search("import_key", $search_import_key);
-
-if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall);
+if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
+else $sql .= " WHERE 1 = 1";
+foreach ($search as $key => $val)
+{
+ if ($key == 'status' && $search[$key] == -1) continue;
+ $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
+ if (strpos($object->fields[$key]['type'], 'integer:') === 0) {
+ if ($search[$key] == '-1') $search[$key] = '';
+ $mode_search = 2;
+ }
+ if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
+}
+if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
+//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
// Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks
$parameters = array();
-$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
+$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
+
+/* If a group by is required
+ $sql.= " GROUP BY ";
+ foreach($object->fields as $key => $val)
+ {
+ $sql.='t.'.$key.', ';
+ }
+ // Add fields from extrafields
+ if (! empty($extrafields->attributes[$object->table_element]['label'])) {
+ foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
+ }
+ // Add where from hooks
+ $parameters=array();
+ $reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook
+ $sql.=$hookmanager->resPrint;
+ $sql=preg_replace('/,\s*$/','', $sql);
+ */
+
$sql .= $db->order($sortfield, $sortorder);
-//$sql.= $db->plimit($conf->liste_limit+1, $offset);
// Count total nb of records
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
- $result = $db->query($sql);
- $nbtotalofrecords = $db->num_rows($result);
- if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0
+ $resql = $db->query($sql);
+ $nbtotalofrecords = $db->num_rows($resql);
+ if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0
{
$page = 0;
$offset = 0;
}
}
-
-$sql .= $db->plimit($limit + 1, $offset);
-
-
-dol_syslog($script_file, LOG_DEBUG);
-$resql = $db->query($sql);
-if ($resql)
+// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
+if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit)))
{
+ $num = $nbtotalofrecords;
+} else {
+ if ($limit) $sql .= $db->plimit($limit + 1, $offset);
+
+ $resql = $db->query($sql);
+ if (!$resql)
+ {
+ dol_print_error($db);
+ exit;
+ }
+
$num = $db->num_rows($resql);
+}
- $arrayofselected = is_array($toselect) ? $toselect : array();
+// Direct jump if only one record found
+if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page)
+{
+ $obj = $db->fetch_object($resql);
+ $id = $obj->rowid;
+ header("Location: ".dol_buildpath('/mymodule/myobject_card.php', 1).'?id='.$id);
+ exit;
+}
- $param = '';
- if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
- if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
- if ($search_entity != '') $param .= '&search_entity='.urlencode($search_entity);
- if ($search_product != '') $param .= '&search_product='.urlencode($search_product);
- if ($search_batch != '') $param .= '&search_batch='.urlencode($search_batch);
- if ($search_fk_user_creat != '') $param .= '&search_fk_user_creat='.urlencode($search_fk_user_creat);
- if ($search_fk_user_modif != '') $param .= '&search_fk_user_modif='.urlencode($search_fk_user_modif);
- if ($search_import_key != '') $param .= '&search_import_key='.urlencode($search_import_key);
- if ($optioncss != '') $param .= '&optioncss='.$optioncss;
- // Add $param from extra fields
- include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
- $arrayofmassactions = array(
- //'presend'=>$langs->trans("SendByMail"),
- //'builddoc'=>$langs->trans("PDFMerge"),
- );
- //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']='
'.$langs->trans("Delete");
- if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
- $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
+// Output page
+// --------------------------------------------------------------------
- print '
'."\n";
+
+if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords))
+{
+ $hidegeneratedfilelistifempty = 1;
+ if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;
+
+ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
+ $formfile = new FormFile($db);
+
+ // Show list of available documents
+ $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
+ $urlsource .= str_replace('&', '&', $param);
+
+ $filedir = $diroutputmassaction;
+ $genallowed = $permissiontoread;
+ $delallowed = $permissiontoadd;
+
+ print $formfile->showdocuments('massfilesarea_mymodule', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
}
// End of page
diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php
index e3331fcec74..e7054f21a3c 100644
--- a/htdocs/projet/card.php
+++ b/htdocs/projet/card.php
@@ -344,7 +344,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09'));
}
- $result = $object->generateDocument($object->modelpdf, $outputlangs);
+ $result = $object->generateDocument($object->model_pdf, $outputlangs);
if ($result <= 0)
{
setEventMessages($object->error, $object->errors, 'errors');
@@ -1352,7 +1352,7 @@ if ($action == 'create' && $user->rights->projet->creer)
$genallowed = ($user->rights->projet->lire && $userAccess > 0);
$delallowed = ($user->rights->projet->creer && $userWrite > 0);
- print $formfile->showdocuments('project', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf);
+ print $formfile->showdocuments('project', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf);
print '
';
diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php
index a9175780491..30a2a0c242b 100644
--- a/htdocs/projet/class/project.class.php
+++ b/htdocs/projet/class/project.class.php
@@ -492,7 +492,7 @@ class Project extends CommonObject
$sql .= " WHERE entity IN (".getEntity('project').")";
if (!empty($ref)) {
$sql .= " AND ref = '".$this->db->escape($ref)."'";
- } elseif (! empty($ref_ext)) {
+ } elseif (!empty($ref_ext)) {
$sql .= " AND ref_ext = '".$this->db->escape($ref_ext)."'";
} else {
$sql .= " AND email_msgid = '".$this->db->escape($email_msgid)."'";
@@ -535,7 +535,7 @@ class Project extends CommonObject
$this->opp_percent = $obj->opp_percent;
$this->budget_amount = $obj->budget_amount;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf;
+ $this->modelpdf = $obj->model_pdf; // deprecated
$this->usage_opportunity = (int) $obj->usage_opportunity;
$this->usage_task = (int) $obj->usage_task;
$this->usage_bill_time = (int) $obj->usage_bill_time;
@@ -1021,7 +1021,7 @@ class Project extends CommonObject
}
$label = '';
- if ($option != 'nolink') $label = ''.$langs->trans("Project").' ';
+ if ($option != 'nolink') $label = img_picto('', $this->picto).' '.$langs->trans("Project").' ';
$label .= ($label ? ' ' : '').''.$langs->trans('Ref').': '.$this->ref; // The space must be after the : to not being explode when showing the title in img_picto
$label .= ($label ? ' ' : '').''.$langs->trans('Label').': '.$this->title; // The space must be after the : to not being explode when showing the title in img_picto
if (isset($this->public)) {
@@ -1689,8 +1689,8 @@ class Project extends CommonObject
if (!dol_strlen($modele)) {
$modele = 'baleine';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->PROJECT_ADDON_PDF)) {
$modele = $conf->global->PROJECT_ADDON_PDF;
}
diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php
index abbb918132a..8020477702a 100644
--- a/htdocs/projet/class/task.class.php
+++ b/htdocs/projet/class/task.class.php
@@ -648,7 +648,7 @@ class Task extends CommonObject
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
$result = '';
- $label = ''.$langs->trans("ShowTask").' ';
+ $label = img_picto('', $this->picto).' '.$langs->trans("ShowTask").' ';
if (!empty($this->ref))
$label .= ''.$langs->trans('Ref').': '.$this->ref;
if (!empty($this->label))
diff --git a/htdocs/projet/tasks/list.php b/htdocs/projet/tasks/list.php
index d2e7f98c35c..1ffd3541344 100644
--- a/htdocs/projet/tasks/list.php
+++ b/htdocs/projet/tasks/list.php
@@ -376,7 +376,7 @@ if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $
{
$obj = $db->fetch_object($resql);
$id = $obj->id;
- header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1');
+ header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withproject=1');
exit;
}
diff --git a/htdocs/projet/tasks/task.php b/htdocs/projet/tasks/task.php
index 7a109eb1f50..0a432351f60 100644
--- a/htdocs/projet/tasks/task.php
+++ b/htdocs/projet/tasks/task.php
@@ -165,7 +165,7 @@ if ($action == 'builddoc' && $user->rights->projet->creer)
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09'));
}
- $result = $object->generateDocument($object->modelpdf, $outputlangs);
+ $result = $object->generateDocument($object->model_pdf, $outputlangs);
if ($result <= 0)
{
setEventMessages($object->error, $object->errors, 'errors');
@@ -627,7 +627,7 @@ if ($id > 0 || !empty($ref))
$genallowed = ($user->rights->projet->lire);
$delallowed = ($user->rights->projet->creer);
- print $formfile->showdocuments('project_task', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf);
+ print $formfile->showdocuments('project_task', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf);
print '
';
diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php
index b2993ec86f5..3be1af4935e 100644
--- a/htdocs/public/payment/paymentok.php
+++ b/htdocs/public/payment/paymentok.php
@@ -628,7 +628,6 @@ if ($ispaymentok)
$error++; // Not yet supported
}
$paiement->paiementid = $paymentTypeId;
- $paiement->num_paiement = '';
$paiement->num_payment = '';
$paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
$paiement->ext_payment_id = $TRANSACTIONID;
diff --git a/htdocs/reception/card.php b/htdocs/reception/card.php
index 27722c29ed4..98d35d1e14e 100644
--- a/htdocs/reception/card.php
+++ b/htdocs/reception/card.php
@@ -154,7 +154,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
@@ -392,7 +392,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -486,7 +486,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
if ($result <= 0)
{
setEventMessages($object->error, $object->errors, 'errors');
@@ -644,7 +644,7 @@ if (empty($reshook))
}
$ret = $object->fetch($object->id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
} else {
header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition
@@ -2060,7 +2060,7 @@ if ($action == 'create')
$genallowed = $user->rights->reception->lire;
$delallowed = $user->rights->reception->creer;
- print $formfile->showdocuments('reception', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
+ print $formfile->showdocuments('reception', $objectref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
// Show links to link elements
//$linktoelem = $form->showLinkToObjectBlock($object, null, array('order'));
@@ -2091,7 +2091,7 @@ if ($action == 'create')
// Build document if it not exists
if (!$file || !is_readable($file))
{
- $result = $object->generateDocument(GETPOST('model') ?GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $result = $object->generateDocument(GETPOST('model') ?GETPOST('model') : $object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
if ($result <= 0)
{
dol_print_error($db, $object->error, $object->errors);
diff --git a/htdocs/reception/class/reception.class.php b/htdocs/reception/class/reception.class.php
index 826c61de815..7b2f4927a22 100644
--- a/htdocs/reception/class/reception.class.php
+++ b/htdocs/reception/class/reception.class.php
@@ -401,7 +401,7 @@ class Reception extends CommonObject
$this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planed
$this->fk_delivery_address = $obj->fk_address;
$this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf;
+ $this->modelpdf = $obj->model_pdf; // deprecated
$this->shipping_method_id = $obj->fk_shipping_method;
$this->tracking_number = $obj->tracking_number;
$this->origin = ($obj->origin ? $obj->origin : 'commande'); // For compatibility
@@ -784,7 +784,7 @@ class Reception extends CommonObject
if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight);
if (isset($this->note_private)) $this->note = trim($this->note_private);
if (isset($this->note_public)) $this->note = trim($this->note_public);
- if (isset($this->modelpdf)) $this->modelpdf = trim($this->modelpdf);
+ if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf);
// Check parameters
@@ -1071,7 +1071,7 @@ class Reception extends CommonObject
{
global $conf, $langs;
$result = '';
- $label = '
'.$langs->trans("Reception").' ';
+ $label = img_picto('', $this->picto).'
'.$langs->trans("Reception").' ';
$label .= '
'.$langs->trans('Ref').': '.$this->ref;
$label .= '
'.$langs->trans('RefSupplier').': '.($this->ref_supplier ? $this->ref_supplier : $this->ref_client);
@@ -1877,8 +1877,8 @@ class Reception extends CommonObject
{
$modele = 'squille';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->RECEPTION_ADDON_PDF)) {
$modele = $conf->global->RECEPTION_ADDON_PDF;
}
diff --git a/htdocs/recruitment/class/recruitmentcandidature.class.php b/htdocs/recruitment/class/recruitmentcandidature.class.php
index 4ceea690f06..036d6bb1610 100644
--- a/htdocs/recruitment/class/recruitmentcandidature.class.php
+++ b/htdocs/recruitment/class/recruitmentcandidature.class.php
@@ -710,7 +710,7 @@ class RecruitmentCandidature extends CommonObject
$result = '';
- $label = '
'.$langs->trans("RecruitmentCandidature").' ';
+ $label = img_picto('', $this->picto).'
'.$langs->trans("RecruitmentCandidature").' ';
$label .= '
';
$label .= '
'.$langs->trans('Ref').': '.$this->ref;
$label .= '
'.$langs->trans('Email').': '.$this->email;
diff --git a/htdocs/recruitment/class/recruitmentjobposition.class.php b/htdocs/recruitment/class/recruitmentjobposition.class.php
index 7bc5d507f42..0f28b34be6a 100644
--- a/htdocs/recruitment/class/recruitmentjobposition.class.php
+++ b/htdocs/recruitment/class/recruitmentjobposition.class.php
@@ -690,13 +690,13 @@ class RecruitmentJobPosition extends CommonObject
$resql = $this->db->query($sql);
if ($resql)
{
- $modelpdf = $this->modelpdf;
- $triggerName = 'PROPAL_CLOSE_REFUSED';
+ $modelpdf = $this->model_pdf;
+ $triggerName = 'RECRUITMENTJOB_CLOSE_REFUSED';
if ($status == self::STATUS_RECRUITED)
{
$triggerName = 'RECRUITMENTJOB_CLOSE_RECRUITED';
- $modelpdf = $this->modelpdf;
+ $modelpdf = $this->model_pdf;
if ($result < 0)
{
@@ -798,7 +798,7 @@ class RecruitmentJobPosition extends CommonObject
$result = '';
- $label = '
'.$langs->trans("PositionToBeFilled").' ';
+ $label = img_picto('', $this->picto).'
'.$langs->trans("PositionToBeFilled").' ';
$label .= '
';
$label .= '
'.$langs->trans('Ref').': '.$this->ref;
$label .= '
'.$langs->trans('Label').': '.$this->label;
@@ -1076,8 +1076,8 @@ class RecruitmentJobPosition extends CommonObject
if (!dol_strlen($modele)) {
$modele = 'standard_recruitmentjobposition';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
} elseif (!empty($conf->global->RECRUITMENTJOBPOSITION_ADDON_PDF)) {
$modele = $conf->global->RECRUITMENTJOBPOSITION_ADDON_PDF;
}
diff --git a/htdocs/recruitment/recruitmentindex.php b/htdocs/recruitment/recruitmentindex.php
index 5b7a268d6fb..4087ae25bd7 100644
--- a/htdocs/recruitment/recruitmentindex.php
+++ b/htdocs/recruitment/recruitmentindex.php
@@ -321,14 +321,14 @@ $NBMAX = 3;
$max = 3;
// Last modified job position
-if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read)
+if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read)
{
$sql = "SELECT s.rowid, s.ref, s.label, s.date_creation, s.tms, s.status";
- $sql.= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s";
- if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql.= " WHERE s.entity IN (".getEntity($staticrecruitmentjobposition->element).")";
- if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id;
- if ($socid) $sql.= " AND s.fk_soc = $socid";
+ $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s";
+ if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE s.entity IN (".getEntity($staticrecruitmentjobposition->element).")";
+ if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
+ if ($socid) $sql .= " AND s.fk_soc = $socid";
$sql .= " ORDER BY s.tms DESC";
$sql .= $db->plimit($max, 0);
@@ -379,15 +379,15 @@ if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitm
}
// Last modified job position
-if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read)
+if (!empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitmentjobposition->read)
{
$sql = "SELECT rc.rowid, rc.ref, rc.email, rc.lastname, rc.firstname, rc.date_creation, rc.tms, rc.status";
- $sql.= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc";
- $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s ON rc.fk_recruitmentjobposition = s.rowid";
- if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql.= " WHERE rc.entity IN (".getEntity($staticrecruitmentjobposition->element).")";
- if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id;
- if ($socid) $sql.= " AND s.fk_soc = $socid";
+ $sql .= " FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature as rc";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."recruitment_recruitmentjobposition as s ON rc.fk_recruitmentjobposition = s.rowid";
+ if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE rc.entity IN (".getEntity($staticrecruitmentjobposition->element).")";
+ if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id;
+ if ($socid) $sql .= " AND s.fk_soc = $socid";
$sql .= " ORDER BY rc.tms DESC";
$sql .= $db->plimit($max, 0);
@@ -409,9 +409,9 @@ if (! empty($conf->recruitment->enabled) && $user->rights->recruitment->recruitm
while ($i < $num)
{
$objp = $db->fetch_object($resql);
- $staticrecruitmentcandidature->id=$objp->rowid;
- $staticrecruitmentcandidature->ref=$objp->ref;
- $staticrecruitmentcandidature->email=$objp->email;
+ $staticrecruitmentcandidature->id = $objp->rowid;
+ $staticrecruitmentcandidature->ref = $objp->ref;
+ $staticrecruitmentcandidature->email = $objp->email;
$staticrecruitmentcandidature->status = $objp->status;
$staticrecruitmentcandidature->date_creation = $objp->date_creation;
$staticrecruitmentcandidature->firstname = $objp->firstname;
diff --git a/htdocs/resource/class/dolresource.class.php b/htdocs/resource/class/dolresource.class.php
index 294f36e5589..0fc5d256541 100644
--- a/htdocs/resource/class/dolresource.class.php
+++ b/htdocs/resource/class/dolresource.class.php
@@ -922,7 +922,7 @@ class Dolresource extends CommonObject
global $conf, $langs;
$result = '';
- $label = '
'.$langs->trans("ShowResource").' ';
+ $label = img_picto('', $this->picto).'
'.$langs->trans("ShowResource").' ';
$label .= '
';
$label .= '
'.$langs->trans('Ref').': '.$this->ref;
/*if (isset($this->status)) {
diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php
index 4b07247281b..4218dcd7872 100644
--- a/htdocs/societe/card.php
+++ b/htdocs/societe/card.php
@@ -2687,7 +2687,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))
$genallowed = $user->rights->societe->lire;
$delallowed = $user->rights->societe->creer;
- print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang);
+ print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang);
}
// Subsidiaries list
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index b208135121b..a5a489f014b 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -2360,42 +2360,42 @@ class Societe extends CommonObject
if ($option == 'customer' || $option == 'compta' || $option == 'category')
{
- $label .= '
'.$langs->trans("Customer").' ';
+ $label .= img_picto('', $this->picto).'
'.$langs->trans("Customer").' ';
$linkstart = '
';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("Prospect").' ';
$linkstart = ' ';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("Supplier").' ';
$linkstart = ' ';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("ThirdParty").' ';
$linkstart = ' ';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("ThirdParty").' ';
$linkstart = ' ';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("ThirdParty").' ';
$linkstart = ' ';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("ThirdParty").' ';
$linkstart = ' ';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("ThirdParty").' ';
$linkstart = ' ';
+ $label .= img_picto('', $this->picto).' '.$langs->trans("ThirdParty").' ';
$linkstart = ' rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
$sql .= " WHERE s.entity IN (".getEntity('societe').")";
if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
-if ($socid) $sql .= " AND s.rowid = ".$socid;
if ($search_sale && $search_sale != -2) $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
if (!$user->rights->fournisseur->lire) $sql .= " AND (s.fournisseur <> 1 OR s.client <> 0)"; // client=0, fournisseur=0 must be visible
if ($search_sale == -2) $sql .= " AND sc.fk_user IS NULL";
@@ -484,10 +483,12 @@ if ($search_stcomm != '' && $search_stcomm != -2) $sql .= natural_search("s.fk_s
if ($search_import_key) $sql .= natural_search("s.import_key", $search_import_key);
// Add where from extra fields
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
-
// Add where from hooks
-$parameters = array();
+$parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
+if (empty($reshook)) {
+ if ($socid) $sql .= " AND s.rowid = ".$socid;
+}
$sql .= $hookmanager->resPrint;
$sql .= $db->order($sortfield, $sortorder);
diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php
index 16b29836a60..739c4456a78 100644
--- a/htdocs/societe/paymentmodes.php
+++ b/htdocs/societe/paymentmodes.php
@@ -1530,7 +1530,7 @@ if ($socid && $action != 'edit' && $action != 'create' && $action != 'editcard'
$genallowed = $user->rights->societe->lire;
$delallowed = $user->rights->societe->creer;
- print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang);
+ print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 0, 0, 0, 28, 0, 'entity='.$object->entity, 0, '', $object->default_lang);
// Show direct download link
if (!empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD))
diff --git a/htdocs/stripe/class/stripe.class.php b/htdocs/stripe/class/stripe.class.php
index 539a39b4140..961011b51e0 100644
--- a/htdocs/stripe/class/stripe.class.php
+++ b/htdocs/stripe/class/stripe.class.php
@@ -36,11 +36,11 @@ class Stripe extends CommonObject
/**
* @var int Thirdparty ID
*/
- public $fk_soc;
+ public $fk_soc;
- /**
- * @var int ID
- */
+ /**
+ * @var int ID
+ */
public $fk_key;
/**
@@ -62,9 +62,9 @@ class Stripe extends CommonObject
public $code;
public $declinecode;
- /**
- * @var string Message
- */
+ /**
+ * @var string Message
+ */
public $message;
/**
@@ -102,21 +102,21 @@ class Stripe extends CommonObject
dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
$result = $this->db->query($sql);
- if ($result) {
+ if ($result) {
if ($this->db->num_rows($result)) {
$obj = $this->db->fetch_object($result);
- $tokenstring = $obj->tokenstring;
+ $tokenstring = $obj->tokenstring;
- $tmparray = dol_json_decode($tokenstring);
- $key = $tmparray->stripe_user_id;
- } else {
- $tokenstring = '';
- }
- } else {
- dol_print_error($this->db);
- }
+ $tmparray = dol_json_decode($tokenstring);
+ $key = $tmparray->stripe_user_id;
+ } else {
+ $tokenstring = '';
+ }
+ } else {
+ dol_print_error($this->db);
+ }
- dol_syslog("No dedicated Stripe Connect account available for entity ".$conf->entity);
+ dol_syslog("No dedicated Stripe Connect account available for entity ".$conf->entity);
return $key;
}
@@ -194,7 +194,7 @@ class Stripe extends CommonObject
}
} elseif ($createifnotlinkedtostripe)
{
- $ipaddress = getUserRemoteIP();
+ $ipaddress = getUserRemoteIP();
$dataforcustomer = array(
"email" => $object->email,
@@ -291,9 +291,9 @@ class Stripe extends CommonObject
return $stripepaymentmethod;
}
- /**
+ /**
* Get the Stripe payment intent. Create it with confirmnow=false
- * Warning. If a payment was tried and failed, a payment intent was created.
+ * Warning. If a payment was tried and failed, a payment intent was created.
* But if we change something on object to pay (amount or other), reusing same payment intent is not allowed by Stripe.
* Recommended solution is to recreate a new payment intent each time we need one (old one will be automatically closed after a delay),
* that's why i comment the part of code to retreive a payment intent with object id (never mind if we cumulate payment intent with old ones that will not be used)
@@ -333,9 +333,9 @@ class Stripe extends CommonObject
$fee = $amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE;
if ($fee >= $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL && $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL > $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) {
- $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL;
+ $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL;
} elseif ($fee < $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) {
- $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL;
+ $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL;
}
if (!in_array($currency_code, $arrayzerounitcurrency)) {
$stripefee = round($fee * 100);
@@ -345,7 +345,7 @@ class Stripe extends CommonObject
$paymentintent = null;
- if (is_object($object) && ! empty($conf->global->STRIPE_REUSE_EXISTING_INTENT_IF_FOUND))
+ if (is_object($object) && !empty($conf->global->STRIPE_REUSE_EXISTING_INTENT_IF_FOUND))
{
// Warning. If a payment was tried and failed, a payment intent was created.
// But if we change something on object to pay (amount or other that does not change the idempotency key), reusing same payment intent is not allowed by Stripe.
@@ -354,167 +354,167 @@ class Stripe extends CommonObject
// That's why we can comment the part of code to retreive a payment intent with object id (never mind if we cumulate payment intent with old ones that will not be used)
$sql = "SELECT pi.ext_payment_id, pi.entity, pi.fk_facture, pi.sourcetype, pi.ext_payment_site";
- $sql.= " FROM " . MAIN_DB_PREFIX . "prelevement_facture_demande as pi";
- $sql.= " WHERE pi.fk_facture = " . $object->id;
- $sql.= " AND pi.sourcetype = '" . $object->element . "'";
- $sql.= " AND pi.entity IN (".getEntity('societe').")";
- $sql.= " AND pi.ext_payment_site = '" . $service . "'";
+ $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pi";
+ $sql .= " WHERE pi.fk_facture = ".$object->id;
+ $sql .= " AND pi.sourcetype = '".$object->element."'";
+ $sql .= " AND pi.entity IN (".getEntity('societe').")";
+ $sql .= " AND pi.ext_payment_site = '".$service."'";
- dol_syslog(get_class($this) . "::getPaymentIntent search stripe payment intent for object id = ".$object->id, LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql) {
- $num = $this->db->num_rows($resql);
- if ($num)
- {
- $obj = $this->db->fetch_object($resql);
- $intent = $obj->ext_payment_id;
+ dol_syslog(get_class($this)."::getPaymentIntent search stripe payment intent for object id = ".$object->id, LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ if ($num)
+ {
+ $obj = $this->db->fetch_object($resql);
+ $intent = $obj->ext_payment_id;
- dol_syslog(get_class($this) . "::getPaymentIntent found existing payment intent record");
+ dol_syslog(get_class($this)."::getPaymentIntent found existing payment intent record");
- // Force to use the correct API key
- global $stripearrayofkeysbyenv;
- \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
+ // Force to use the correct API key
+ global $stripearrayofkeysbyenv;
+ \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
- try {
- if (empty($key)) { // If the Stripe connect account not set, we use common API usage
- $paymentintent = \Stripe\PaymentIntent::retrieve($intent);
- } else {
- $paymentintent = \Stripe\PaymentIntent::retrieve($intent, array("stripe_account" => $key));
- }
- }
- catch (Exception $e) {
- $error++;
- $this->error = $e->getMessage();
- }
- }
- }
+ try {
+ if (empty($key)) { // If the Stripe connect account not set, we use common API usage
+ $paymentintent = \Stripe\PaymentIntent::retrieve($intent);
+ } else {
+ $paymentintent = \Stripe\PaymentIntent::retrieve($intent, array("stripe_account" => $key));
+ }
+ }
+ catch (Exception $e) {
+ $error++;
+ $this->error = $e->getMessage();
+ }
+ }
+ }
}
if (empty($paymentintent))
{
- $ipaddress = getUserRemoteIP();
- $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
- if (is_object($object))
- {
- $metadata['dol_type'] = $object->element;
- $metadata['dol_id'] = $object->id;
+ $ipaddress = getUserRemoteIP();
+ $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
+ if (is_object($object))
+ {
+ $metadata['dol_type'] = $object->element;
+ $metadata['dol_id'] = $object->id;
if (is_object($object->thirdparty) && $object->thirdparty->id > 0) $metadata['dol_thirdparty_id'] = $object->thirdparty->id;
- }
+ }
- // list of payment method types
- $paymentmethodtypes = array("card");
- if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT) ) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC())
- if (!empty($conf->global->STRIPE_IDEAL) ) $paymentmethodtypes[] = "ideal"; //&& ($object->thirdparty->isInEEC())
+ // list of payment method types
+ $paymentmethodtypes = array("card");
+ if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC())
+ if (!empty($conf->global->STRIPE_IDEAL)) $paymentmethodtypes[] = "ideal"; //&& ($object->thirdparty->isInEEC())
- $dataforintent = array(
- "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent
- "confirmation_method" => $mode,
- "amount" => $stripeamount,
- "currency" => $currency_code,
- "payment_method_types" => $paymentmethodtypes,
- "description" => $description,
- "statement_descriptor_suffix" => dol_trunc($tag, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
- //"save_payment_method" => true,
+ $dataforintent = array(
+ "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent
+ "confirmation_method" => $mode,
+ "amount" => $stripeamount,
+ "currency" => $currency_code,
+ "payment_method_types" => $paymentmethodtypes,
+ "description" => $description,
+ "statement_descriptor_suffix" => dol_trunc($tag, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
+ //"save_payment_method" => true,
"setup_future_usage" => "on_session",
- "metadata" => $metadata
- );
- if (!is_null($customer)) $dataforintent["customer"] = $customer;
- // payment_method =
- // payment_method_types = array('card')
- //var_dump($dataforintent);
- if ($off_session)
- {
- unset($dataforintent['setup_future_usage']);
- $dataforintent["off_session"] = true;
- }
- if (!is_null($payment_method))
- {
- $dataforintent["payment_method"] = $payment_method;
- $description .= ' - '.$payment_method;
- }
+ "metadata" => $metadata
+ );
+ if (!is_null($customer)) $dataforintent["customer"] = $customer;
+ // payment_method =
+ // payment_method_types = array('card')
+ //var_dump($dataforintent);
+ if ($off_session)
+ {
+ unset($dataforintent['setup_future_usage']);
+ $dataforintent["off_session"] = true;
+ }
+ if (!is_null($payment_method))
+ {
+ $dataforintent["payment_method"] = $payment_method;
+ $description .= ' - '.$payment_method;
+ }
- if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0)
- {
- $dataforintent["application_fee_amount"] = $stripefee;
- }
- if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email)
- {
- $dataforintent["receipt_email"] = $object->thirdparty->email;
- }
+ if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0)
+ {
+ $dataforintent["application_fee_amount"] = $stripefee;
+ }
+ if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email)
+ {
+ $dataforintent["receipt_email"] = $object->thirdparty->email;
+ }
- try {
- // Force to use the correct API key
- global $stripearrayofkeysbyenv;
- \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
+ try {
+ // Force to use the correct API key
+ global $stripearrayofkeysbyenv;
+ \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
- $arrayofoptions = array();
- if (empty($noidempotency_key)) {
- $arrayofoptions["idempotency_key"] = $description;
- }
- // Note: If all data for payment intent are same than a previous on, even if we use 'create', Stripe will return ID of the old existing payment intent.
- if (!empty($key)) { // If the Stripe connect account not set, we use common API usage
- $arrayofoptions["stripe_account"] = $key;
- }
- $paymentintent = \Stripe\PaymentIntent::create($dataforintent, $arrayofoptions);
+ $arrayofoptions = array();
+ if (empty($noidempotency_key)) {
+ $arrayofoptions["idempotency_key"] = $description;
+ }
+ // Note: If all data for payment intent are same than a previous on, even if we use 'create', Stripe will return ID of the old existing payment intent.
+ if (!empty($key)) { // If the Stripe connect account not set, we use common API usage
+ $arrayofoptions["stripe_account"] = $key;
+ }
+ $paymentintent = \Stripe\PaymentIntent::create($dataforintent, $arrayofoptions);
- // Store the payment intent
- if (is_object($object))
- {
- $paymentintentalreadyexists = 0;
- // Check that payment intent $paymentintent->id is not already recorded.
- $sql = "SELECT pi.rowid";
- $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pi";
- $sql .= " WHERE pi.entity IN (".getEntity('societe').")";
- $sql .= " AND pi.ext_payment_site = '".$service."'";
- $sql .= " AND pi.ext_payment_id = '".$this->db->escape($paymentintent->id)."'";
+ // Store the payment intent
+ if (is_object($object))
+ {
+ $paymentintentalreadyexists = 0;
+ // Check that payment intent $paymentintent->id is not already recorded.
+ $sql = "SELECT pi.rowid";
+ $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pi";
+ $sql .= " WHERE pi.entity IN (".getEntity('societe').")";
+ $sql .= " AND pi.ext_payment_site = '".$service."'";
+ $sql .= " AND pi.ext_payment_id = '".$this->db->escape($paymentintent->id)."'";
- dol_syslog(get_class($this)."::getPaymentIntent search if payment intent already in prelevement_facture_demande", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql) {
- $num = $this->db->num_rows($resql);
- if ($num)
- {
- $obj = $this->db->fetch_object($resql);
- if ($obj) $paymentintentalreadyexists++;
- }
- } else dol_print_error($this->db);
+ dol_syslog(get_class($this)."::getPaymentIntent search if payment intent already in prelevement_facture_demande", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $num = $this->db->num_rows($resql);
+ if ($num)
+ {
+ $obj = $this->db->fetch_object($resql);
+ if ($obj) $paymentintentalreadyexists++;
+ }
+ } else dol_print_error($this->db);
- // If not, we create it.
- if (!$paymentintentalreadyexists)
- {
- $now = dol_now();
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture_demande (date_demande, fk_user_demande, ext_payment_id, fk_facture, sourcetype, entity, ext_payment_site, amount)";
- $sql .= " VALUES ('".$this->db->idate($now)."', ".$user->id.", '".$this->db->escape($paymentintent->id)."', ".$object->id.", '".$this->db->escape($object->element)."', ".$conf->entity.", '".$service."', ".$amount.")";
- $resql = $this->db->query($sql);
- if (!$resql)
- {
- $error++;
- $this->error = $this->db->lasterror();
- dol_syslog(get_class($this)."::PaymentIntent failed to insert paymentintent with id=".$paymentintent->id." into database.");
- }
- }
- } else {
- $_SESSION["stripe_payment_intent"] = $paymentintent;
- }
- } catch (Stripe\Error\Card $e)
- {
- $error++;
- $this->error = $e->getMessage();
- $this->code = $e->getStripeCode();
- $this->declinecode = $e->getDeclineCode();
- } catch (Exception $e)
- {
- /*var_dump($dataforintent);
+ // If not, we create it.
+ if (!$paymentintentalreadyexists)
+ {
+ $now = dol_now();
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture_demande (date_demande, fk_user_demande, ext_payment_id, fk_facture, sourcetype, entity, ext_payment_site, amount)";
+ $sql .= " VALUES ('".$this->db->idate($now)."', ".$user->id.", '".$this->db->escape($paymentintent->id)."', ".$object->id.", '".$this->db->escape($object->element)."', ".$conf->entity.", '".$service."', ".$amount.")";
+ $resql = $this->db->query($sql);
+ if (!$resql)
+ {
+ $error++;
+ $this->error = $this->db->lasterror();
+ dol_syslog(get_class($this)."::PaymentIntent failed to insert paymentintent with id=".$paymentintent->id." into database.");
+ }
+ }
+ } else {
+ $_SESSION["stripe_payment_intent"] = $paymentintent;
+ }
+ } catch (Stripe\Error\Card $e)
+ {
+ $error++;
+ $this->error = $e->getMessage();
+ $this->code = $e->getStripeCode();
+ $this->declinecode = $e->getDeclineCode();
+ } catch (Exception $e)
+ {
+ /*var_dump($dataforintent);
var_dump($description);
var_dump($key);
var_dump($paymentintent);
var_dump($e->getMessage());
var_dump($e);*/
- $error++;
- $this->error = $e->getMessage();
- $this->code = '';
- $this->declinecode = '';
- }
+ $error++;
+ $this->error = $e->getMessage();
+ $this->code = '';
+ $this->declinecode = '';
+ }
}
dol_syslog("getPaymentIntent return error=".$error." this->error=".$this->error, LOG_INFO, -1);
@@ -572,7 +572,7 @@ class Stripe extends CommonObject
// list of payment method types
$paymentmethodtypes = array("card");
- if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT) ) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC())
+ if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC())
// iDEAL not supported with setupIntent
$dataforintent = array(
@@ -933,10 +933,10 @@ class Stripe extends CommonObject
}
} elseif (preg_match('/acct_/i', $source))
{
- $charge = \Stripe\Charge::create(array(
+ $charge = \Stripe\Charge::create(array(
"amount" => "$stripeamount",
"currency" => "$currency",
- "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
+ "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
"description" => "Stripe payment: ".$description,
"capture" => $capture,
"metadata" => $metadata,
@@ -946,7 +946,7 @@ class Stripe extends CommonObject
$paymentarray = array(
"amount" => "$stripeamount",
"currency" => "$currency",
- "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
+ "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
"description" => "Stripe payment: ".$description,
"capture" => $capture,
"metadata" => $metadata,
@@ -965,9 +965,9 @@ class Stripe extends CommonObject
// With Stripe Connect
$fee = $amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE;
if ($fee >= $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL && $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL > $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) {
- $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL;
+ $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL;
} elseif ($fee < $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) {
- $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL;
+ $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL;
}
if (!in_array($currency, $arrayzerounitcurrency)) $stripefee = round($fee * 100);
diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php
index 9e776f94371..0c4e53da2b9 100644
--- a/htdocs/supplier_proposal/card.php
+++ b/htdocs/supplier_proposal/card.php
@@ -191,7 +191,7 @@ if (empty($reshook))
$outputlangs->setDefaultLang($newlang);
}
$ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
@@ -217,7 +217,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -266,7 +266,7 @@ if (empty($reshook))
$object->remise_absolue = GETPOST('remise_absolue');
$object->socid = GETPOST('socid');
$object->fk_project = GETPOST('projectid', 'int');
- $object->modelpdf = GETPOST('model');
+ $object->model_pdf = GETPOST('model');
$object->author = $user->id; // deprecated
$object->note = GETPOST('note', 'none');
$object->statut = SupplierProposal::STATUS_DRAFT;
@@ -284,7 +284,7 @@ if (empty($reshook))
$object->mode_reglement_id = GETPOST('mode_reglement_id');
$object->fk_account = GETPOST('fk_account', 'int');
$object->fk_project = GETPOST('projectid', 'int');
- $object->modelpdf = GETPOST('model');
+ $object->model_pdf = GETPOST('model');
$object->author = $user->id; // deprecated
$object->note = GETPOST('note', 'none');
@@ -436,7 +436,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -517,7 +517,7 @@ if (empty($reshook))
$outputlangs->setDefaultLang($newlang);
}
$ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
} elseif ($action == "setabsolutediscount" && $usercancreate) {
if ($_POST["remise_id"]) {
@@ -780,7 +780,7 @@ if (empty($reshook))
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlang);
}
- $model = $object->modelpdf;
+ $model = $object->model_pdf;
$ret = $object->fetch($id); // Reload to get new records
$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
@@ -963,7 +963,7 @@ if (empty($reshook))
$outputlangs->setDefaultLang($newlang);
}
$ret = $object->fetch($id); // Reload to get new records
- $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
}
unset($_POST['qty']);
@@ -1922,7 +1922,7 @@ if ($action == 'create')
$genallowed = $usercanread;
$delallowed = $usercancreate;
- print $formfile->showdocuments('supplier_proposal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
+ print $formfile->showdocuments('supplier_proposal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
// Show links to link elements
diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php
index 344bea2d6be..79b50071a18 100644
--- a/htdocs/supplier_proposal/class/supplier_proposal.class.php
+++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php
@@ -6,7 +6,7 @@
* Copyright (C) 2005-2013 Regis Houssin
* Copyright (C) 2006 Andre Cianfarani
* Copyright (C) 2008 Raphael Bertrand
- * Copyright (C) 2010-2015 Juanjo Menent
+ * Copyright (C) 2010-2020 Juanjo Menent
* Copyright (C) 2010-2018 Philippe Grand
* Copyright (C) 2012-2014 Christophe Battarel
* Copyright (C) 2013 Florian Henry
@@ -776,1897 +776,1900 @@ class SupplierProposal extends CommonObject
$this->line->multicurrency_total_tva = $multicurrency_total_tva;
$this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
- $result = $this->line->update();
- if ($result > 0)
- {
- // Reorder if child line
- if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
+ $result = $this->line->update();
+ if ($result > 0)
+ {
+ // Reorder if child line
+ if (!empty($fk_parent_line)) $this->line_order(true, 'DESC');
- $this->update_price(1);
+ $this->update_price(1);
- $this->fk_supplier_proposal = $this->id;
+ $this->fk_supplier_proposal = $this->id;
- $this->db->commit();
- return $result;
- } else {
- $this->error = $this->db->error();
- $this->db->rollback();
- return -1;
- }
- } else {
- dol_syslog(get_class($this)."::updateline Erreur -2 SupplierProposal en mode incompatible pour cette action");
- return -2;
- }
- }
+ $this->db->commit();
+ return $result;
+ } else {
+ $this->error = $this->db->error();
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ dol_syslog(get_class($this)."::updateline Erreur -2 SupplierProposal en mode incompatible pour cette action");
+ return -2;
+ }
+ }
- /**
- * Delete detail line
- *
- * @param int $lineid Id of line to delete
- * @return int >0 if OK, <0 if KO
- */
- public function deleteline($lineid)
- {
- if ($this->statut == 0)
- {
- $line = new SupplierProposalLine($this->db);
+ /**
+ * Delete detail line
+ *
+ * @param int $lineid Id of line to delete
+ * @return int >0 if OK, <0 if KO
+ */
+ public function deleteline($lineid)
+ {
+ if ($this->statut == 0)
+ {
+ $line = new SupplierProposalLine($this->db);
- // For triggers
- $line->fetch($lineid);
+ // For triggers
+ $line->fetch($lineid);
- if ($line->delete() > 0)
- {
- $this->update_price(1);
+ if ($line->delete() > 0)
+ {
+ $this->update_price(1);
- return 1;
- } else {
- return -1;
- }
- } else {
- return -2;
- }
- }
+ return 1;
+ } else {
+ return -1;
+ }
+ } else {
+ return -2;
+ }
+ }
- /**
- * Create commercial proposal into database
- * this->ref can be set or empty. If empty, we will use "(PROVid)"
- *
- * @param User $user User that create
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int <0 if KO, >=0 if OK
- */
- public function create($user, $notrigger = 0)
- {
- global $langs, $conf, $mysoc, $hookmanager;
- $error = 0;
+ /**
+ * Create commercial proposal into database
+ * this->ref can be set or empty. If empty, we will use "(PROVid)"
+ *
+ * @param User $user User that create
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <0 if KO, >=0 if OK
+ */
+ public function create($user, $notrigger = 0)
+ {
+ global $langs, $conf, $mysoc, $hookmanager;
+ $error = 0;
- $now = dol_now();
+ $now = dol_now();
- dol_syslog(get_class($this)."::create");
+ dol_syslog(get_class($this)."::create");
- // Check parameters
- $result = $this->fetch_thirdparty();
- if ($result < 0)
- {
- $this->error = "Failed to fetch company";
- dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
- return -3;
- }
+ // Check parameters
+ $result = $this->fetch_thirdparty();
+ if ($result < 0)
+ {
+ $this->error = "Failed to fetch company";
+ dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
+ return -3;
+ }
- // Check parameters
- if (!empty($this->ref)) // We check that ref is not already used
- {
- $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
- if ($result > 0)
- {
- $this->error = 'ErrorRefAlreadyExists';
- dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
- $this->db->rollback();
- return -1;
- }
- }
+ // Check parameters
+ if (!empty($this->ref)) // We check that ref is not already used
+ {
+ $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used
+ if ($result > 0)
+ {
+ $this->error = 'ErrorRefAlreadyExists';
+ dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
+ $this->db->rollback();
+ return -1;
+ }
+ }
- // Multicurrency
- if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now);
- if (empty($this->fk_multicurrency))
- {
- $this->multicurrency_code = $conf->currency;
- $this->fk_multicurrency = 0;
- $this->multicurrency_tx = 1;
- }
+ // Multicurrency
+ if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $now);
+ if (empty($this->fk_multicurrency))
+ {
+ $this->multicurrency_code = $conf->currency;
+ $this->fk_multicurrency = 0;
+ $this->multicurrency_tx = 1;
+ }
- $this->db->begin();
+ $this->db->begin();
- // Insert into database
- $sql = "INSERT INTO ".MAIN_DB_PREFIX."supplier_proposal (";
- $sql .= "fk_soc";
- $sql .= ", price";
- $sql .= ", remise";
- $sql .= ", remise_percent";
- $sql .= ", remise_absolue";
- $sql .= ", tva";
- $sql .= ", total";
- $sql .= ", datec";
- $sql .= ", ref";
- $sql .= ", fk_user_author";
- $sql .= ", note_private";
- $sql .= ", note_public";
- $sql .= ", model_pdf";
- $sql .= ", fk_cond_reglement";
- $sql .= ", fk_mode_reglement";
- $sql .= ", fk_account";
- $sql .= ", date_livraison";
- $sql .= ", fk_shipping_method";
- $sql .= ", fk_projet";
- $sql .= ", entity";
- $sql .= ", fk_multicurrency";
- $sql .= ", multicurrency_code";
- $sql .= ", multicurrency_tx";
- $sql .= ") ";
- $sql .= " VALUES (";
- $sql .= $this->socid;
- $sql .= ", 0";
- $sql .= ", ".$this->remise;
- $sql .= ", ".($this->remise_percent ? $this->db->escape($this->remise_percent) : 'null');
- $sql .= ", ".($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'null');
- $sql .= ", 0";
- $sql .= ", 0";
- $sql .= ", '".$this->db->idate($now)."'";
- $sql .= ", '(PROV)'";
- $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null");
- $sql .= ", '".$this->db->escape($this->note_private)."'";
- $sql .= ", '".$this->db->escape($this->note_public)."'";
- $sql .= ", '".$this->db->escape($this->modelpdf)."'";
- $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL');
- $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL');
- $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
- $sql .= ", ".($this->date_livraison != '' ? "'".$this->db->idate($this->date_livraison)."'" : "null");
- $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
- $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
- $sql .= ", ".$conf->entity;
- $sql .= ", ".(int) $this->fk_multicurrency;
- $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
- $sql .= ", ".(double) $this->multicurrency_tx;
- $sql .= ")";
+ // Insert into database
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX."supplier_proposal (";
+ $sql .= "fk_soc";
+ $sql .= ", price";
+ $sql .= ", remise";
+ $sql .= ", remise_percent";
+ $sql .= ", remise_absolue";
+ $sql .= ", tva";
+ $sql .= ", total";
+ $sql .= ", datec";
+ $sql .= ", ref";
+ $sql .= ", fk_user_author";
+ $sql .= ", note_private";
+ $sql .= ", note_public";
+ $sql .= ", model_pdf";
+ $sql .= ", fk_cond_reglement";
+ $sql .= ", fk_mode_reglement";
+ $sql .= ", fk_account";
+ $sql .= ", date_livraison";
+ $sql .= ", fk_shipping_method";
+ $sql .= ", fk_projet";
+ $sql .= ", entity";
+ $sql .= ", fk_multicurrency";
+ $sql .= ", multicurrency_code";
+ $sql .= ", multicurrency_tx";
+ $sql .= ") ";
+ $sql .= " VALUES (";
+ $sql .= $this->socid;
+ $sql .= ", 0";
+ $sql .= ", ".$this->remise;
+ $sql .= ", ".($this->remise_percent ? $this->db->escape($this->remise_percent) : 'null');
+ $sql .= ", ".($this->remise_absolue ? $this->db->escape($this->remise_absolue) : 'null');
+ $sql .= ", 0";
+ $sql .= ", 0";
+ $sql .= ", '".$this->db->idate($now)."'";
+ $sql .= ", '(PROV)'";
+ $sql .= ", ".($user->id > 0 ? "'".$user->id."'" : "null");
+ $sql .= ", '".$this->db->escape($this->note_private)."'";
+ $sql .= ", '".$this->db->escape($this->note_public)."'";
+ $sql .= ", '".$this->db->escape($this->model_pdf)."'";
+ $sql .= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'NULL');
+ $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'NULL');
+ $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
+ $sql .= ", ".($this->date_livraison != '' ? "'".$this->db->idate($this->date_livraison)."'" : "null");
+ $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : 'NULL');
+ $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
+ $sql .= ", ".$conf->entity;
+ $sql .= ", ".(int) $this->fk_multicurrency;
+ $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
+ $sql .= ", ".(double) $this->multicurrency_tx;
+ $sql .= ")";
- dol_syslog(get_class($this)."::create", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."supplier_proposal");
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."supplier_proposal");
- if ($this->id)
- {
- $this->ref = '(PROV'.$this->id.')';
- $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
+ if ($this->id)
+ {
+ $this->ref = '(PROV'.$this->id.')';
+ $sql = 'UPDATE '.MAIN_DB_PREFIX."supplier_proposal SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id;
- dol_syslog(get_class($this)."::create", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql) $error++;
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) $error++;
- if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
- {
- $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
- }
+ if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
+ {
+ $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
+ }
- // Add object linked
- if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects))
- {
- foreach ($this->linked_objects as $origin => $tmp_origin_id)
- {
- if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
- {
- foreach ($tmp_origin_id as $origin_id)
- {
- $ret = $this->add_object_linked($origin, $origin_id);
- if (!$ret)
- {
- dol_print_error($this->db);
- $error++;
- }
- }
- }
- }
- }
+ // Add object linked
+ if (!$error && $this->id && is_array($this->linked_objects) && !empty($this->linked_objects))
+ {
+ foreach ($this->linked_objects as $origin => $tmp_origin_id)
+ {
+ if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
+ {
+ foreach ($tmp_origin_id as $origin_id)
+ {
+ $ret = $this->add_object_linked($origin, $origin_id);
+ if (!$ret)
+ {
+ dol_print_error($this->db);
+ $error++;
+ }
+ }
+ }
+ }
+ }
- /*
+ /*
* Insertion du detail des produits dans la base
*/
- if (!$error)
- {
- $fk_parent_line = 0;
- $num = count($this->lines);
+ if (!$error)
+ {
+ $fk_parent_line = 0;
+ $num = count($this->lines);
- for ($i = 0; $i < $num; $i++)
- {
- // Reset fk_parent_line for no child products and special product
- if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
- $fk_parent_line = 0;
- }
+ for ($i = 0; $i < $num; $i++)
+ {
+ // Reset fk_parent_line for no child products and special product
+ if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
+ $fk_parent_line = 0;
+ }
- $result = $this->addline(
- $this->lines[$i]->desc,
- $this->lines[$i]->subprice,
- $this->lines[$i]->qty,
- $this->lines[$i]->tva_tx,
- $this->lines[$i]->localtax1_tx,
- $this->lines[$i]->localtax2_tx,
- $this->lines[$i]->fk_product,
- $this->lines[$i]->remise_percent,
- 'HT',
- 0,
- 0,
- $this->lines[$i]->product_type,
- $this->lines[$i]->rang,
- $this->lines[$i]->special_code,
- $fk_parent_line,
- $this->lines[$i]->fk_fournprice,
- $this->lines[$i]->pa_ht,
- $this->lines[$i]->label,
- $this->lines[$i]->array_options,
- $this->lines[$i]->ref_fourn,
- $this->lines[$i]->fk_unit,
- 'supplier_proposal',
- $this->lines[$i]->rowid
- );
+ $result = $this->addline(
+ $this->lines[$i]->desc,
+ $this->lines[$i]->subprice,
+ $this->lines[$i]->qty,
+ $this->lines[$i]->tva_tx,
+ $this->lines[$i]->localtax1_tx,
+ $this->lines[$i]->localtax2_tx,
+ $this->lines[$i]->fk_product,
+ $this->lines[$i]->remise_percent,
+ 'HT',
+ 0,
+ 0,
+ $this->lines[$i]->product_type,
+ $this->lines[$i]->rang,
+ $this->lines[$i]->special_code,
+ $fk_parent_line,
+ $this->lines[$i]->fk_fournprice,
+ $this->lines[$i]->pa_ht,
+ $this->lines[$i]->label,
+ $this->lines[$i]->array_options,
+ $this->lines[$i]->ref_fourn,
+ $this->lines[$i]->fk_unit,
+ 'supplier_proposal',
+ $this->lines[$i]->rowid
+ );
- if ($result < 0)
- {
- $error++;
- $this->error = $this->db->error;
- dol_print_error($this->db);
- break;
- }
- // Defined the new fk_parent_line
- if ($result > 0 && $this->lines[$i]->product_type == 9) {
- $fk_parent_line = $result;
- }
- }
- }
+ if ($result < 0)
+ {
+ $error++;
+ $this->error = $this->db->error;
+ dol_print_error($this->db);
+ break;
+ }
+ // Defined the new fk_parent_line
+ if ($result > 0 && $this->lines[$i]->product_type == 9) {
+ $fk_parent_line = $result;
+ }
+ }
+ }
- if (!$error)
- {
- // Mise a jour infos denormalisees
- $resql = $this->update_price(1);
- if ($resql)
- {
- $action = 'update';
+ if (!$error)
+ {
+ // Mise a jour infos denormalisees
+ $resql = $this->update_price(1);
+ if ($resql)
+ {
+ $action = 'update';
- // Actions on extra fields
- if (!$error)
- {
- $result = $this->insertExtraFields();
- if ($result < 0)
- {
- $error++;
- }
- }
+ // Actions on extra fields
+ if (!$error)
+ {
+ $result = $this->insertExtraFields();
+ if ($result < 0)
+ {
+ $error++;
+ }
+ }
- if (!$error && !$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('PROPOSAL_SUPPLIER_CREATE', $user);
- if ($result < 0) { $error++; }
- // End call triggers
- }
- } else {
- $this->error = $this->db->lasterror();
- $error++;
- }
- }
- } else {
- $this->error = $this->db->lasterror();
- $error++;
- }
+ if (!$error && !$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('PROPOSAL_SUPPLIER_CREATE', $user);
+ if ($result < 0) { $error++; }
+ // End call triggers
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $error++;
+ }
- if (!$error)
- {
- $this->db->commit();
- dol_syslog(get_class($this)."::create done id=".$this->id);
- return $this->id;
- } else {
- $this->db->rollback();
- return -2;
- }
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -1;
- }
- }
+ if (!$error)
+ {
+ $this->db->commit();
+ dol_syslog(get_class($this)."::create done id=".$this->id);
+ return $this->id;
+ } else {
+ $this->db->rollback();
+ return -2;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Insert into DB a supplier_proposal object completely defined by its data members (ex, results from copy).
- *
- * @param User $user User that create
- * @return int Id of the new object if ok, <0 if ko
- * @see create()
- */
- public function create_from($user)
- {
- // phpcs:enable
- $this->products = $this->lines;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Insert into DB a supplier_proposal object completely defined by its data members (ex, results from copy).
+ *
+ * @param User $user User that create
+ * @return int Id of the new object if ok, <0 if ko
+ * @see create()
+ */
+ public function create_from($user)
+ {
+ // phpcs:enable
+ $this->products = $this->lines;
- return $this->create($user);
- }
+ return $this->create($user);
+ }
- /**
- * Load an object from its id and create a new one in database
- *
+ /**
+ * Load an object from its id and create a new one in database
+ *
* @param User $user User making the clone
- * @param int $fromid Id of thirdparty
- * @return int New id of clone
- */
- public function createFromClone(User $user, $fromid = 0)
- {
- global $conf, $hookmanager;
-
- $error = 0;
- $now = dol_now();
-
- $this->db->begin();
-
- // get extrafields so they will be clone
- foreach ($this->lines as $line)
- $line->fetch_optionals();
-
- // Load source object
- $objFrom = clone $this;
-
- $objsoc = new Societe($this->db);
-
- // Change socid if needed
- if (!empty($fromid) && $fromid != $this->socid)
- {
- if ($objsoc->fetch($fromid) > 0)
- {
- $this->socid = $objsoc->id;
- $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
- $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
- $this->fk_project = '';
- }
-
- // TODO Change product price if multi-prices
- } else {
- $objsoc->fetch($this->socid);
- }
-
- $this->id = 0;
- $this->statut = 0;
-
- if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php"))
- {
- $this->error = 'ErrorSetupNotComplete';
- return -1;
- }
-
- // Clear fields
- $this->user_author = $user->id;
- $this->user_valid = '';
- $this->date = $now;
-
- // Set ref
- require_once DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.'.php';
- $obj = $conf->global->SUPPLIER_PROPOSAL_ADDON;
- $modSupplierProposal = new $obj;
- $this->ref = $modSupplierProposal->getNextValue($objsoc, $this);
-
- // Create clone
- $this->context['createfromclone'] = 'createfromclone';
- $result = $this->create($user);
- if ($result < 0) $error++;
-
- if (!$error)
- {
- // Hook of thirdparty module
- if (is_object($hookmanager))
- {
- $parameters = array('objFrom'=>$objFrom);
- $action = '';
- $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
- if ($reshook < 0) $error++;
- }
- }
-
- unset($this->context['createfromclone']);
-
- // End
- if (!$error)
- {
- $this->db->commit();
- return $this->id;
- } else {
- $this->db->rollback();
- return -1;
- }
- }
-
- /**
- * Load a proposal from database and its ligne array
- *
- * @param int $rowid id of object to load
- * @param string $ref Ref of proposal
- * @return int >0 if OK, <0 if KO
- */
- public function fetch($rowid, $ref = '')
- {
- global $conf;
-
- $sql = "SELECT p.rowid, p.entity, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc";
- $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht";
- $sql .= ", p.datec";
- $sql .= ", p.date_valid as datev";
- $sql .= ", p.date_livraison as date_livraison";
- $sql .= ", p.model_pdf, p.extraparams";
- $sql .= ", p.note_private, p.note_public";
- $sql .= ", p.fk_projet as fk_project, p.fk_statut";
- $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
- $sql .= ", p.fk_cond_reglement";
- $sql .= ", p.fk_mode_reglement";
- $sql .= ', p.fk_account';
- $sql .= ", p.fk_shipping_method";
- $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
- $sql .= ", c.label as statut_label";
- $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
- $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
- $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p";
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id';
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid';
- $sql .= " WHERE p.fk_statut = c.id";
- $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
- if ($ref) $sql .= " AND p.ref='".$ref."'";
- else $sql .= " AND p.rowid=".$rowid;
-
- dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- if ($this->db->num_rows($resql))
- {
- $obj = $this->db->fetch_object($resql);
-
- $this->id = $obj->rowid;
- $this->entity = $obj->entity;
-
- $this->ref = $obj->ref;
- $this->remise = $obj->remise;
- $this->remise_percent = $obj->remise_percent;
- $this->remise_absolue = $obj->remise_absolue;
- $this->total = $obj->total; // TODO deprecated
- $this->total_ht = $obj->total_ht;
- $this->total_tva = $obj->tva;
- $this->total_localtax1 = $obj->localtax1;
- $this->total_localtax2 = $obj->localtax2;
- $this->total_ttc = $obj->total;
- $this->socid = $obj->fk_soc;
- $this->fk_project = $obj->fk_project;
- $this->model_pdf = $obj->model_pdf;
- $this->modelpdf = $obj->model_pdf;
- $this->note = $obj->note_private; // TODO deprecated
- $this->note_private = $obj->note_private;
- $this->note_public = $obj->note_public;
- $this->statut = (int) $obj->fk_statut;
- $this->statut_libelle = $obj->statut_label;
- $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
- $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
- $this->date_creation = $this->db->jdate($obj->datec); //Creation date
- $this->date_validation = $this->db->jdate($obj->datev); //Validation date
- $this->date_livraison = $this->db->jdate($obj->date_livraison);
- $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
-
- $this->mode_reglement_id = $obj->fk_mode_reglement;
- $this->mode_reglement_code = $obj->mode_reglement_code;
- $this->mode_reglement = $obj->mode_reglement;
- $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
- $this->cond_reglement_id = $obj->fk_cond_reglement;
- $this->cond_reglement_code = $obj->cond_reglement_code;
- $this->cond_reglement = $obj->cond_reglement;
- $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
-
- $this->extraparams = (array) json_decode($obj->extraparams, true);
-
- $this->user_author_id = $obj->fk_user_author;
- $this->user_valid_id = $obj->fk_user_valid;
- $this->user_close_id = $obj->fk_user_cloture;
-
- // Multicurrency
- $this->fk_multicurrency = $obj->fk_multicurrency;
- $this->multicurrency_code = $obj->multicurrency_code;
- $this->multicurrency_tx = $obj->multicurrency_tx;
- $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
- $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
- $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
-
- if ($obj->fk_statut == 0)
- {
- $this->brouillon = 1;
- }
-
- // Retreive all extrafield
- // fetch optionals attributes and labels
- $this->fetch_optionals();
-
- $this->db->free($resql);
-
- $this->lines = array();
-
- // Lines of supplier proposals
- $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,";
- $sql .= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,";
- $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
- $sql .= ' d.ref_fourn as ref_produit_fourn,';
- $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit';
- $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
- $sql .= " WHERE d.fk_supplier_proposal = ".$this->id;
- $sql .= " ORDER by d.rang";
-
- $result = $this->db->query($sql);
- if ($result)
- {
- $num = $this->db->num_rows($result);
- $i = 0;
-
- while ($i < $num)
- {
- $objp = $this->db->fetch_object($result);
-
- $line = new SupplierProposalLine($this->db);
-
- $line->rowid = $objp->rowid; // deprecated
- $line->id = $objp->rowid;
- $line->fk_supplier_proposal = $objp->fk_supplier_proposal;
- $line->fk_parent_line = $objp->fk_parent_line;
- $line->product_type = $objp->product_type;
- $line->label = $objp->custom_label;
- $line->desc = $objp->description; // Description ligne
- $line->qty = $objp->qty;
- $line->tva_tx = $objp->tva_tx;
- $line->localtax1_tx = $objp->localtax1_tx;
- $line->localtax2_tx = $objp->localtax2_tx;
- $line->subprice = $objp->subprice;
- $line->fk_remise_except = $objp->fk_remise_except;
- $line->remise_percent = $objp->remise_percent;
-
- $line->info_bits = $objp->info_bits;
- $line->total_ht = $objp->total_ht;
- $line->total_tva = $objp->total_tva;
- $line->total_localtax1 = $objp->total_localtax1;
- $line->total_localtax2 = $objp->total_localtax2;
- $line->total_ttc = $objp->total_ttc;
- $line->fk_fournprice = $objp->fk_fournprice;
- $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
- $line->pa_ht = $marginInfos[0];
- $line->marge_tx = $marginInfos[1];
- $line->marque_tx = $marginInfos[2];
- $line->special_code = $objp->special_code;
- $line->rang = $objp->rang;
-
- $line->fk_product = $objp->fk_product;
-
- $line->ref = $objp->product_ref; // deprecated
- $line->product_ref = $objp->product_ref;
- $line->libelle = $objp->product_label; // deprecated
- $line->product_label = $objp->product_label;
- $line->product_desc = $objp->product_desc; // Description produit
- $line->fk_product_type = $objp->fk_product_type;
-
- $line->ref_fourn = $objp->ref_produit_fourn;
-
- // Multicurrency
- $line->fk_multicurrency = $objp->fk_multicurrency;
- $line->multicurrency_code = $objp->multicurrency_code;
- $line->multicurrency_subprice = $objp->multicurrency_subprice;
- $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
- $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
- $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
- $line->fk_unit = $objp->fk_unit;
-
- $this->lines[$i] = $line;
-
- $i++;
- }
- $this->db->free($result);
- } else {
- $this->error = $this->db->error();
- return -1;
- }
-
- // Retreive all extrafield
- // fetch optionals attributes and labels
- $this->fetch_optionals();
-
- return 1;
- }
-
- $this->error = "Record Not Found";
- return 0;
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
-
- /**
- * Set status to validated
- *
- * @param User $user Object user that validate
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int <0 if KO, >=0 if OK
- */
- public function valid($user, $notrigger = 0)
- {
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
-
- global $conf, $langs;
-
- $error = 0;
- $now = dol_now();
-
- if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->creer))
- || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance)))
- {
- $this->db->begin();
-
- // Numbering module definition
- $soc = new Societe($this->db);
- $soc->fetch($this->socid);
-
- // 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($soc);
- } else {
- $num = $this->ref;
- }
- $this->newref = dol_sanitizeFileName($num);
-
- $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
- $sql .= " SET ref = '".$this->db->escape($num)."',";
- $sql .= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id;
- $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
-
- dol_syslog(get_class($this)."::valid", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql)
- {
- dol_print_error($this->db);
- $error++;
- }
-
- // Trigger calls
- if (!$error && !$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('PROPOSAL_SUPPLIER_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 = 'supplier_proposal/".$this->db->escape($this->newref)."'";
- $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$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->supplier_proposal->dir_output.'/'.$oldref;
- $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref;
- if (!$error && file_exists($dirsource))
- {
- dol_syslog(get_class($this)."::valid 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->supplier_proposal->dir_output.'/'.$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);
- }
- }
- }
- }
-
- $this->ref = $num;
- $this->brouillon = 0;
- $this->statut = 1;
- $this->user_valid_id = $user->id;
- $this->datev = $now;
-
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- dol_syslog("You don't have permission to validate supplier proposal", LOG_WARNING);
- return -2;
- }
- }
-
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Set delivery date
- *
- * @param User $user Object user that modify
- * @param int $date_livraison Delivery date
- * @return int <0 if ko, >0 if ok
- */
- public function set_date_livraison($user, $date_livraison)
- {
- // phpcs:enable
- if (!empty($user->rights->supplier_proposal->creer))
- {
- $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal ";
- $sql .= " SET date_livraison = ".($date_livraison != '' ? "'".$this->db->idate($date_livraison)."'" : 'null');
- $sql .= " WHERE rowid = ".$this->id;
-
- if ($this->db->query($sql))
- {
- $this->date_livraison = $date_livraison;
- return 1;
- } else {
- $this->error = $this->db->error();
- dol_syslog(get_class($this)."::set_date_livraison Erreur SQL");
- return -1;
- }
- }
- }
-
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Set an overall discount on the proposal
- *
- * @param User $user Object user that modify
- * @param double $remise Amount discount
- * @return int <0 if ko, >0 if ok
- */
- public function set_remise_percent($user, $remise)
- {
- // phpcs:enable
- $remise = trim($remise) ?trim($remise) : 0;
-
- if (!empty($user->rights->supplier_proposal->creer))
- {
- $remise = price2num($remise);
-
- $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET remise_percent = ".$remise;
- $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
-
- if ($this->db->query($sql))
- {
- $this->remise_percent = $remise;
- $this->update_price(1);
- return 1;
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
- }
-
-
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Set an absolute overall discount on the proposal
- *
- * @param User $user Object user that modify
- * @param double $remise Amount discount
- * @return int <0 if ko, >0 if ok
- */
- public function set_remise_absolue($user, $remise)
- {
- // phpcs:enable
- $remise = trim($remise) ?trim($remise) : 0;
-
- if (!empty($user->rights->supplier_proposal->creer))
- {
- $remise = price2num($remise);
-
- $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal ";
- $sql .= " SET remise_absolue = ".$remise;
- $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
-
- if ($this->db->query($sql))
- {
- $this->remise_absolue = $remise;
- $this->update_price(1);
- return 1;
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
- }
-
-
-
- /**
- * Reopen the commercial proposal
- *
- * @param User $user Object user that close
- * @param int $statut Statut
- * @param string $note Comment
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int <0 if KO, >0 if OK
- */
- public function reopen($user, $statut, $note = '', $notrigger = 0)
- {
- global $langs, $conf;
-
- $this->statut = $statut;
- $error = 0;
-
- $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
- $sql .= " SET fk_statut = ".$this->statut.",";
- if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',";
- $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
- $sql .= " WHERE rowid = ".$this->id;
-
- $this->db->begin();
-
- dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
- $resql = $this->db->query($sql);
- if (!$resql) {
- $error++; $this->errors[] = "Error ".$this->db->lasterror();
- }
- if (!$error)
- {
- if (!$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('PROPOSAL_SUPPLIER_REOPEN', $user);
- if ($result < 0) { $error++; }
- // End call triggers
- }
- }
-
- // Commit or rollback
- if ($error)
- {
- if (!empty($this->errors))
- {
- foreach ($this->errors as $errmsg)
- {
- dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
- $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
- }
- }
- $this->db->rollback();
- return -1 * $error;
- } else {
- $this->db->commit();
- return 1;
- }
- }
-
-
- /**
- * Close the askprice
- *
- * @param User $user Object user that close
- * @param int $status Status
- * @param string $note Comment
- * @return int <0 if KO, >0 if OK
- */
- public function cloture($user, $status, $note)
- {
- global $langs, $conf;
-
- $this->statut = $status;
- $error = 0;
- $now = dol_now();
-
- $this->db->begin();
-
- $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
- $sql .= " SET fk_statut = ".$status.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
- $sql .= " WHERE rowid = ".$this->id;
-
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : $this->modelpdf;
- $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED';
-
- if ($status == 2)
- {
- $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED';
- $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : $this->modelpdf;
-
- if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists
- {
- $result = $this->updateOrCreatePriceFournisseur($user);
- }
- }
- if ($status == 4)
- {
- $triggerName = 'PROPOSAL_SUPPLIER_CLASSIFY_BILLED';
- }
-
- if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
- {
- // Define output language
- $outputlangs = $langs;
- if (!empty($conf->global->MAIN_MULTILANGS)) {
- $outputlangs = new Translate("", $conf);
- $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
- $outputlangs->setDefaultLang($newlang);
- }
- //$ret=$object->fetch($id); // Reload to get new records
- $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
- }
-
- // Call trigger
- $result = $this->call_trigger($triggerName, $user);
- if ($result < 0) { $error++; }
- // End call triggers
-
- if (!$error)
- {
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- $this->error = $this->db->lasterror();
- $this->errors[] = $this->db->lasterror();
- $this->db->rollback();
- return -1;
- }
- }
-
- /**
- * Add or update supplier price according to result of proposal
- *
- * @param User $user Object user
- * @return int > 0 if OK
- */
- public function updateOrCreatePriceFournisseur($user)
- {
- global $conf;
-
- dol_syslog(get_class($this)."::updateOrCreatePriceFournisseur", LOG_DEBUG);
- foreach ($this->lines as $product)
- {
- if ($product->subprice <= 0) continue;
- $productsupplier = new ProductFournisseur($this->db);
-
- $multicurrency_tx = 1;
- $fk_multicurrency = 0;
-
- if (empty($this->thirdparty)) $this->fetch_thirdparty();
-
- $ref_fourn = $product->ref_fourn;
- if (empty($ref_fourn)) $ref_fourn = $product->ref_supplier;
- if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code);
- $productsupplier->id = $product->fk_product;
-
- $productsupplier->update_buyprice($product->qty, $product->total_ht, $user, 'HT', $this->thirdparty, '', $ref_fourn, $product->tva_tx, 0, 0, 0, $product->info_bits, '', '', array(), '', $product->multicurrency_total_ht, 'HT', $multicurrency_tx, $product->multicurrency_code, '', '', '');
- }
-
- return 1;
- }
-
- /**
- * Upate ProductFournisseur
- *
- * @param int $idProductFournPrice id of llx_product_fournisseur_price
- * @param Product $product contain informations to update
- * @param User $user Object user
- * @return int <0 if KO, >0 if OK
- */
- public function updatePriceFournisseur($idProductFournPrice, $product, $user)
- {
- $price = price2num($product->subprice * $product->qty, 'MU');
- $unitPrice = price2num($product->subprice, 'MU');
-
- $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_fournisseur_price SET '.(!empty($product->ref_fourn) ? 'ref_fourn = "'.$product->ref_fourn.'", ' : '').' price ='.$price.', unitprice ='.$unitPrice.' WHERE rowid = '.$idProductFournPrice;
-
- $resql = $this->db->query($sql);
- if (!$resql) {
- $this->error = $this->db->error();
- $this->db->rollback();
- return -1;
- }
- }
-
- /**
- * Create ProductFournisseur
- *
- * @param Product $product Object Product
- * @param User $user Object user
- * @return int <0 if KO, >0 if OK
- */
- public function createPriceFournisseur($product, $user)
- {
- global $conf;
-
- $price = price2num($product->subprice * $product->qty, 'MU');
- $qty = price2num($product->qty);
- $unitPrice = price2num($product->subprice, 'MU');
-
- $now = dol_now();
-
- $values = array(
- "'".$this->db->idate($now)."'",
- $product->fk_product,
- $this->thirdparty->id,
- "'".$product->ref_fourn."'",
- $price,
- $qty,
- $unitPrice,
- $product->tva_tx,
- $user->id
- );
- if (!empty($conf->multicurrency->enabled)) {
- if (!empty($product->multicurrency_code)) {
+ * @param int $fromid Id of thirdparty
+ * @return int New id of clone
+ */
+ public function createFromClone(User $user, $fromid = 0)
+ {
+ global $conf, $hookmanager;
+
+ $error = 0;
+ $now = dol_now();
+
+ $this->db->begin();
+
+ // get extrafields so they will be clone
+ foreach ($this->lines as $line)
+ $line->fetch_optionals();
+
+ // Load source object
+ $objFrom = clone $this;
+
+ $objsoc = new Societe($this->db);
+
+ // Change socid if needed
+ if (!empty($fromid) && $fromid != $this->socid)
+ {
+ if ($objsoc->fetch($fromid) > 0)
+ {
+ $this->socid = $objsoc->id;
+ $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
+ $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
+ $this->fk_project = '';
+ }
+
+ // TODO Change product price if multi-prices
+ } else {
+ $objsoc->fetch($this->socid);
+ }
+
+ $this->id = 0;
+ $this->statut = 0;
+
+ if (empty($conf->global->SUPPLIER_PROPOSAL_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.".php"))
+ {
+ $this->error = 'ErrorSetupNotComplete';
+ return -1;
+ }
+
+ // Clear fields
+ $this->user_author = $user->id;
+ $this->user_valid = '';
+ $this->date = $now;
+
+ // Set ref
+ require_once DOL_DOCUMENT_ROOT."/core/modules/supplier_proposal/".$conf->global->SUPPLIER_PROPOSAL_ADDON.'.php';
+ $obj = $conf->global->SUPPLIER_PROPOSAL_ADDON;
+ $modSupplierProposal = new $obj;
+ $this->ref = $modSupplierProposal->getNextValue($objsoc, $this);
+
+ // Create clone
+ $this->context['createfromclone'] = 'createfromclone';
+ $result = $this->create($user);
+ if ($result < 0) $error++;
+
+ if (!$error)
+ {
+ // Hook of thirdparty module
+ if (is_object($hookmanager))
+ {
+ $parameters = array('objFrom'=>$objFrom);
+ $action = '';
+ $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+ if ($reshook < 0) $error++;
+ }
+ }
+
+ unset($this->context['createfromclone']);
+
+ // End
+ if (!$error)
+ {
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load a proposal from database and its ligne array
+ *
+ * @param int $rowid id of object to load
+ * @param string $ref Ref of proposal
+ * @return int >0 if OK, <0 if KO
+ */
+ public function fetch($rowid, $ref = '')
+ {
+ global $conf;
+
+ $sql = "SELECT p.rowid, p.entity, p.ref, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc";
+ $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht";
+ $sql .= ", p.datec";
+ $sql .= ", p.date_valid as datev";
+ $sql .= ", p.date_livraison as date_livraison";
+ $sql .= ", p.model_pdf, p.extraparams";
+ $sql .= ", p.note_private, p.note_public";
+ $sql .= ", p.fk_projet as fk_project, p.fk_statut";
+ $sql .= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture";
+ $sql .= ", p.fk_cond_reglement";
+ $sql .= ", p.fk_mode_reglement";
+ $sql .= ', p.fk_account';
+ $sql .= ", p.fk_shipping_method";
+ $sql .= ", p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc";
+ $sql .= ", c.label as statut_label";
+ $sql .= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc";
+ $sql .= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement";
+ $sql .= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."supplier_proposal as p";
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id';
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid';
+ $sql .= " WHERE p.fk_statut = c.id";
+ $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
+ if ($ref) $sql .= " AND p.ref='".$ref."'";
+ else $sql .= " AND p.rowid=".$rowid;
+
+ dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ if ($this->db->num_rows($resql))
+ {
+ $obj = $this->db->fetch_object($resql);
+
+ $this->id = $obj->rowid;
+ $this->entity = $obj->entity;
+
+ $this->ref = $obj->ref;
+ $this->remise = $obj->remise;
+ $this->remise_percent = $obj->remise_percent;
+ $this->remise_absolue = $obj->remise_absolue;
+ $this->total = $obj->total; // TODO deprecated
+ $this->total_ht = $obj->total_ht;
+ $this->total_tva = $obj->tva;
+ $this->total_localtax1 = $obj->localtax1;
+ $this->total_localtax2 = $obj->localtax2;
+ $this->total_ttc = $obj->total;
+ $this->socid = $obj->fk_soc;
+ $this->fk_project = $obj->fk_project;
+ $this->model_pdf = $obj->model_pdf;
+ $this->modelpdf = $obj->model_pdf; // deprecated
+ $this->note = $obj->note_private; // TODO deprecated
+ $this->note_private = $obj->note_private;
+ $this->note_public = $obj->note_public;
+ $this->statut = (int) $obj->fk_statut;
+ $this->statut_libelle = $obj->statut_label;
+ $this->datec = $this->db->jdate($obj->datec); // TODO deprecated
+ $this->datev = $this->db->jdate($obj->datev); // TODO deprecated
+ $this->date_creation = $this->db->jdate($obj->datec); //Creation date
+ $this->date_validation = $this->db->jdate($obj->datev); //Validation date
+ $this->date_livraison = $this->db->jdate($obj->date_livraison);
+ $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
+
+ $this->mode_reglement_id = $obj->fk_mode_reglement;
+ $this->mode_reglement_code = $obj->mode_reglement_code;
+ $this->mode_reglement = $obj->mode_reglement;
+ $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
+ $this->cond_reglement_id = $obj->fk_cond_reglement;
+ $this->cond_reglement_code = $obj->cond_reglement_code;
+ $this->cond_reglement = $obj->cond_reglement;
+ $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
+
+ $this->extraparams = (array) json_decode($obj->extraparams, true);
+
+ $this->user_author_id = $obj->fk_user_author;
+ $this->user_valid_id = $obj->fk_user_valid;
+ $this->user_close_id = $obj->fk_user_cloture;
+
+ // Multicurrency
+ $this->fk_multicurrency = $obj->fk_multicurrency;
+ $this->multicurrency_code = $obj->multicurrency_code;
+ $this->multicurrency_tx = $obj->multicurrency_tx;
+ $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
+ $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
+ $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
+
+ if ($obj->fk_statut == 0)
+ {
+ $this->brouillon = 1;
+ }
+
+ // Retreive all extrafield
+ // fetch optionals attributes and labels
+ $this->fetch_optionals();
+
+ $this->db->free($resql);
+
+ $this->lines = array();
+
+ // Lines of supplier proposals
+ $sql = "SELECT d.rowid, d.fk_supplier_proposal, d.fk_parent_line, d.label as custom_label, d.description, d.price, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.qty, d.fk_remise_except, d.remise_percent, d.subprice, d.fk_product,";
+ $sql .= " d.info_bits, d.total_ht, d.total_tva, d.total_localtax1, d.total_localtax2, d.total_ttc, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht, d.special_code, d.rang, d.product_type,";
+ $sql .= ' p.ref as product_ref, p.description as product_desc, p.fk_product_type, p.label as product_label,';
+ $sql .= ' d.ref_fourn as ref_produit_fourn,';
+ $sql .= ' d.fk_multicurrency, d.multicurrency_code, d.multicurrency_subprice, d.multicurrency_total_ht, d.multicurrency_total_tva, d.multicurrency_total_ttc, d.fk_unit';
+ $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposaldet as d";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
+ $sql .= " WHERE d.fk_supplier_proposal = ".$this->id;
+ $sql .= " ORDER by d.rang";
+
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ $num = $this->db->num_rows($result);
+ $i = 0;
+
+ while ($i < $num)
+ {
+ $objp = $this->db->fetch_object($result);
+
+ $line = new SupplierProposalLine($this->db);
+
+ $line->rowid = $objp->rowid; // deprecated
+ $line->id = $objp->rowid;
+ $line->fk_supplier_proposal = $objp->fk_supplier_proposal;
+ $line->fk_parent_line = $objp->fk_parent_line;
+ $line->product_type = $objp->product_type;
+ $line->label = $objp->custom_label;
+ $line->desc = $objp->description; // Description ligne
+ $line->qty = $objp->qty;
+ $line->tva_tx = $objp->tva_tx;
+ $line->localtax1_tx = $objp->localtax1_tx;
+ $line->localtax2_tx = $objp->localtax2_tx;
+ $line->subprice = $objp->subprice;
+ $line->fk_remise_except = $objp->fk_remise_except;
+ $line->remise_percent = $objp->remise_percent;
+
+ $line->info_bits = $objp->info_bits;
+ $line->total_ht = $objp->total_ht;
+ $line->total_tva = $objp->total_tva;
+ $line->total_localtax1 = $objp->total_localtax1;
+ $line->total_localtax2 = $objp->total_localtax2;
+ $line->total_ttc = $objp->total_ttc;
+ $line->fk_fournprice = $objp->fk_fournprice;
+ $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
+ $line->pa_ht = $marginInfos[0];
+ $line->marge_tx = $marginInfos[1];
+ $line->marque_tx = $marginInfos[2];
+ $line->special_code = $objp->special_code;
+ $line->rang = $objp->rang;
+
+ $line->fk_product = $objp->fk_product;
+
+ $line->ref = $objp->product_ref; // deprecated
+ $line->product_ref = $objp->product_ref;
+ $line->libelle = $objp->product_label; // deprecated
+ $line->product_label = $objp->product_label;
+ $line->product_desc = $objp->product_desc; // Description produit
+ $line->fk_product_type = $objp->fk_product_type;
+
+ $line->ref_fourn = $objp->ref_produit_fourn;
+
+ // Multicurrency
+ $line->fk_multicurrency = $objp->fk_multicurrency;
+ $line->multicurrency_code = $objp->multicurrency_code;
+ $line->multicurrency_subprice = $objp->multicurrency_subprice;
+ $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
+ $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
+ $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
+ $line->fk_unit = $objp->fk_unit;
+
+ $this->lines[$i] = $line;
+
+ $i++;
+ }
+ $this->db->free($result);
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+
+ // Retreive all extrafield
+ // fetch optionals attributes and labels
+ $this->fetch_optionals();
+
+ return 1;
+ }
+
+ $this->error = "Record Not Found";
+ return 0;
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
+
+ /**
+ * Set status to validated
+ *
+ * @param User $user Object user that validate
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <0 if KO, >=0 if OK
+ */
+ public function valid($user, $notrigger = 0)
+ {
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+
+ global $conf, $langs;
+
+ $error = 0;
+ $now = dol_now();
+
+ if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->creer))
+ || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance)))
+ {
+ $this->db->begin();
+
+ // Numbering module definition
+ $soc = new Societe($this->db);
+ $soc->fetch($this->socid);
+
+ // 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($soc);
+ } else {
+ $num = $this->ref;
+ }
+ $this->newref = dol_sanitizeFileName($num);
+
+ $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
+ $sql .= " SET ref = '".$this->db->escape($num)."',";
+ $sql .= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id;
+ $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
+
+ dol_syslog(get_class($this)."::valid", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql)
+ {
+ dol_print_error($this->db);
+ $error++;
+ }
+
+ // Trigger calls
+ if (!$error && !$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('PROPOSAL_SUPPLIER_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 = 'supplier_proposal/".$this->db->escape($this->newref)."'";
+ $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'supplier_proposal/".$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->supplier_proposal->dir_output.'/'.$oldref;
+ $dirdest = $conf->supplier_proposal->dir_output.'/'.$newref;
+ if (!$error && file_exists($dirsource))
+ {
+ dol_syslog(get_class($this)."::valid 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->supplier_proposal->dir_output.'/'.$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);
+ }
+ }
+ }
+ }
+
+ $this->ref = $num;
+ $this->brouillon = 0;
+ $this->statut = 1;
+ $this->user_valid_id = $user->id;
+ $this->datev = $now;
+
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ dol_syslog("You don't have permission to validate supplier proposal", LOG_WARNING);
+ return -2;
+ }
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Set delivery date
+ *
+ * @param User $user Object user that modify
+ * @param int $date_livraison Delivery date
+ * @return int <0 if ko, >0 if ok
+ */
+ public function set_date_livraison($user, $date_livraison)
+ {
+ // phpcs:enable
+ if (!empty($user->rights->supplier_proposal->creer))
+ {
+ $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal ";
+ $sql .= " SET date_livraison = ".($date_livraison != '' ? "'".$this->db->idate($date_livraison)."'" : 'null');
+ $sql .= " WHERE rowid = ".$this->id;
+
+ if ($this->db->query($sql))
+ {
+ $this->date_livraison = $date_livraison;
+ return 1;
+ } else {
+ $this->error = $this->db->error();
+ dol_syslog(get_class($this)."::set_date_livraison Erreur SQL");
+ return -1;
+ }
+ }
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Set an overall discount on the proposal
+ *
+ * @param User $user Object user that modify
+ * @param double $remise Amount discount
+ * @return int <0 if ko, >0 if ok
+ */
+ public function set_remise_percent($user, $remise)
+ {
+ // phpcs:enable
+ $remise = trim($remise) ?trim($remise) : 0;
+
+ if (!empty($user->rights->supplier_proposal->creer))
+ {
+ $remise = price2num($remise);
+
+ $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal SET remise_percent = ".$remise;
+ $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
+
+ if ($this->db->query($sql))
+ {
+ $this->remise_percent = $remise;
+ $this->update_price(1);
+ return 1;
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
+ }
+
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Set an absolute overall discount on the proposal
+ *
+ * @param User $user Object user that modify
+ * @param double $remise Amount discount
+ * @return int <0 if ko, >0 if ok
+ */
+ public function set_remise_absolue($user, $remise)
+ {
+ // phpcs:enable
+ $remise = trim($remise) ?trim($remise) : 0;
+
+ if (!empty($user->rights->supplier_proposal->creer))
+ {
+ $remise = price2num($remise);
+
+ $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal ";
+ $sql .= " SET remise_absolue = ".$remise;
+ $sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
+
+ if ($this->db->query($sql))
+ {
+ $this->remise_absolue = $remise;
+ $this->update_price(1);
+ return 1;
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
+ }
+
+
+
+ /**
+ * Reopen the commercial proposal
+ *
+ * @param User $user Object user that close
+ * @param int $statut Statut
+ * @param string $note Comment
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int <0 if KO, >0 if OK
+ */
+ public function reopen($user, $statut, $note = '', $notrigger = 0)
+ {
+ global $langs, $conf;
+
+ $this->statut = $statut;
+ $error = 0;
+
+ $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
+ $sql .= " SET fk_statut = ".$this->statut.",";
+ if (!empty($note)) $sql .= " note_private = '".$this->db->escape($note)."',";
+ $sql .= " date_cloture=NULL, fk_user_cloture=NULL";
+ $sql .= " WHERE rowid = ".$this->id;
+
+ $this->db->begin();
+
+ dol_syslog(get_class($this)."::reopen", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++; $this->errors[] = "Error ".$this->db->lasterror();
+ }
+ if (!$error)
+ {
+ if (!$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('PROPOSAL_SUPPLIER_REOPEN', $user);
+ if ($result < 0) { $error++; }
+ // End call triggers
+ }
+ }
+
+ // Commit or rollback
+ if ($error)
+ {
+ if (!empty($this->errors))
+ {
+ foreach ($this->errors as $errmsg)
+ {
+ dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
+ $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
+ }
+ }
+ $this->db->rollback();
+ return -1 * $error;
+ } else {
+ $this->db->commit();
+ return 1;
+ }
+ }
+
+
+ /**
+ * Close the askprice
+ *
+ * @param User $user Object user that close
+ * @param int $status Status
+ * @param string $note Comment
+ * @return int <0 if KO, >0 if OK
+ */
+ public function cloture($user, $status, $note)
+ {
+ global $langs, $conf;
+
+ $this->statut = $status;
+ $error = 0;
+ $now = dol_now();
+
+ $this->db->begin();
+
+ $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
+ $sql .= " SET fk_statut = ".$status.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id;
+ $sql .= " WHERE rowid = ".$this->id;
+
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_CLOSED : $this->modelpdf;
+ $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_REFUSED';
+
+ if ($status == 2)
+ {
+ $triggerName = 'PROPOSAL_SUPPLIER_CLOSE_SIGNED';
+ $modelpdf = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_TOBILL : $this->modelpdf;
+
+ if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) // TODO This option was not tested correctly. Error if product ref does not exists
+ {
+ $result = $this->updateOrCreatePriceFournisseur($user);
+ }
+ }
+ if ($status == 4)
+ {
+ $triggerName = 'PROPOSAL_SUPPLIER_CLASSIFY_BILLED';
+ }
+
+ if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
+ {
+ // Define output language
+ $outputlangs = $langs;
+ if (!empty($conf->global->MAIN_MULTILANGS)) {
+ $outputlangs = new Translate("", $conf);
+ $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $this->thirdparty->default_lang);
+ $outputlangs->setDefaultLang($newlang);
+ }
+ //$ret=$object->fetch($id); // Reload to get new records
+ $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
+ }
+
+ // Call trigger
+ $result = $this->call_trigger($triggerName, $user);
+ if ($result < 0) { $error++; }
+ // End call triggers
+
+ if (!$error)
+ {
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->errors[] = $this->db->lasterror();
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Add or update supplier price according to result of proposal
+ *
+ * @param User $user Object user
+ * @return int > 0 if OK
+ */
+ public function updateOrCreatePriceFournisseur($user)
+ {
+ global $conf;
+
+ dol_syslog(get_class($this)."::updateOrCreatePriceFournisseur", LOG_DEBUG);
+ foreach ($this->lines as $product)
+ {
+ if ($product->subprice <= 0) continue;
+ $productsupplier = new ProductFournisseur($this->db);
+
+ $multicurrency_tx = 1;
+ $fk_multicurrency = 0;
+
+ if (empty($this->thirdparty)) $this->fetch_thirdparty();
+
+ $ref_fourn = $product->ref_fourn;
+ if (empty($ref_fourn)) $ref_fourn = $product->ref_supplier;
+ if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $product->multicurrency_code);
+ $productsupplier->id = $product->fk_product;
+
+ $productsupplier->update_buyprice($product->qty, $product->total_ht, $user, 'HT', $this->thirdparty, '', $ref_fourn, $product->tva_tx, 0, 0, 0, $product->info_bits, '', '', array(), '', $product->multicurrency_total_ht, 'HT', $multicurrency_tx, $product->multicurrency_code, '', '', '');
+ }
+
+ return 1;
+ }
+
+ /**
+ * Upate ProductFournisseur
+ *
+ * @param int $idProductFournPrice id of llx_product_fournisseur_price
+ * @param Product $product contain informations to update
+ * @param User $user Object user
+ * @return int <0 if KO, >0 if OK
+ */
+ public function updatePriceFournisseur($idProductFournPrice, $product, $user)
+ {
+ $price = price2num($product->subprice * $product->qty, 'MU');
+ $unitPrice = price2num($product->subprice, 'MU');
+
+ $sql = 'UPDATE '.MAIN_DB_PREFIX.'product_fournisseur_price SET '.(!empty($product->ref_fourn) ? 'ref_fourn = "'.$product->ref_fourn.'", ' : '').' price ='.$price.', unitprice ='.$unitPrice.' WHERE rowid = '.$idProductFournPrice;
+
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $this->error = $this->db->error();
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Create ProductFournisseur
+ *
+ * @param Product $product Object Product
+ * @param User $user Object user
+ * @return int <0 if KO, >0 if OK
+ */
+ public function createPriceFournisseur($product, $user)
+ {
+ global $conf;
+
+ $price = price2num($product->subprice * $product->qty, 'MU');
+ $qty = price2num($product->qty);
+ $unitPrice = price2num($product->subprice, 'MU');
+
+ $now = dol_now();
+
+ $values = array(
+ "'".$this->db->idate($now)."'",
+ $product->fk_product,
+ $this->thirdparty->id,
+ "'".$product->ref_fourn."'",
+ $price,
+ $qty,
+ $unitPrice,
+ $product->tva_tx,
+ $user->id
+ );
+ if (!empty($conf->multicurrency->enabled)) {
+ if (!empty($product->multicurrency_code)) {
include_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
- $multicurrency = new MultiCurrency($this->db); //need to fetch because empty fk_multicurrency and rate
- $multicurrency->fetch(0, $product->multicurrency_code);
- if (!empty($multicurrency->id)) {
- $values[] = $multicurrency->id;
- $values[] = "'".$product->multicurrency_code."'";
- $values[] = $product->multicurrency_subprice;
- $values[] = $product->multicurrency_total_ht;
- $values[] = $multicurrency->rate->rate;
- } else {
- for ($i = 0; $i < 5; $i++) $values[] = 'NULL';
- }
- }
- }
+ $multicurrency = new MultiCurrency($this->db); //need to fetch because empty fk_multicurrency and rate
+ $multicurrency->fetch(0, $product->multicurrency_code);
+ if (!empty($multicurrency->id)) {
+ $values[] = $multicurrency->id;
+ $values[] = "'".$product->multicurrency_code."'";
+ $values[] = $product->multicurrency_subprice;
+ $values[] = $product->multicurrency_total_ht;
+ $values[] = $multicurrency->rate->rate;
+ } else {
+ for ($i = 0; $i < 5; $i++) $values[] = 'NULL';
+ }
+ }
+ }
- $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_fournisseur_price ';
- $sql .= '(datec, fk_product, fk_soc, ref_fourn, price, quantity, unitprice, tva_tx, fk_user';
- if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx';
- $sql .= ') VALUES ('.implode(',', $values).')';
+ $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'product_fournisseur_price ';
+ $sql .= '(datec, fk_product, fk_soc, ref_fourn, price, quantity, unitprice, tva_tx, fk_user';
+ if (!empty($conf->multicurrency->enabled) && !empty($product->multicurrency_code)) $sql .= ',fk_multicurrency, multicurrency_code, multicurrency_unitprice, multicurrency_price, multicurrency_tx';
+ $sql .= ') VALUES ('.implode(',', $values).')';
- $resql = $this->db->query($sql);
- if (!$resql) {
- $this->error = $this->db->error();
- $this->db->rollback();
- return -1;
- }
- }
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $this->error = $this->db->error();
+ $this->db->rollback();
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Set draft status
- *
- * @param User $user Object user that modify
- * @return int <0 if KO, >0 if OK
- */
- public function setDraft($user)
- {
- // phpcs:enable
- global $conf, $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @return int <0 if KO, >0 if OK
+ */
+ public function setDraft($user)
+ {
+ // phpcs:enable
+ global $conf, $langs;
- $error = 0;
+ $error = 0;
- if ($this->statut == self::STATUS_DRAFT)
- {
- dol_syslog(get_class($this)."::setDraft already draft status", LOG_WARNING);
- return 0;
- }
+ if ($this->statut == self::STATUS_DRAFT)
+ {
+ dol_syslog(get_class($this)."::setDraft already draft status", LOG_WARNING);
+ return 0;
+ }
- $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
- $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
- $sql .= " WHERE rowid = ".$this->id;
+ $sql = "UPDATE ".MAIN_DB_PREFIX."supplier_proposal";
+ $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
+ $sql .= " WHERE rowid = ".$this->id;
- if ($this->db->query($sql))
- {
- if (!$error) {
- $this->oldcopy = clone $this;
- }
+ if ($this->db->query($sql))
+ {
+ if (!$error) {
+ $this->oldcopy = clone $this;
+ }
- if (!$error) {
- // Call trigger
- $result = $this->call_trigger('PROPOSAL_SUPPLIER_UNVALIDATE', $user);
- if ($result < 0) $error++;
- }
+ if (!$error) {
+ // Call trigger
+ $result = $this->call_trigger('PROPOSAL_SUPPLIER_UNVALIDATE', $user);
+ if ($result < 0) $error++;
+ }
- if (!$error) {
- $this->statut = self::STATUS_DRAFT;
- $this->brouillon = 1;
- $this->db->commit();
- return 1;
- } else {
- $this->db->rollback();
- return -1;
- }
- } else {
- return -1;
- }
- }
+ if (!$error) {
+ $this->statut = self::STATUS_DRAFT;
+ $this->brouillon = 1;
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ } else {
+ return -1;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Return list of askprice (eventually filtered on user) into an array
- *
- * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
- * @param int $draft 0=not draft, 1=draft
- * @param int $notcurrentuser 0=all user, 1=not current user
- * @param int $socid Id third pary
- * @param int $limit For pagination
- * @param int $offset For pagination
- * @param string $sortfield Sort criteria
- * @param string $sortorder Sort order
- * @return int -1 if KO, array with result if OK
- */
- public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datec', $sortorder = 'DESC')
- {
- // phpcs:enable
- global $conf, $user;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return list of askprice (eventually filtered on user) into an array
+ *
+ * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
+ * @param int $draft 0=not draft, 1=draft
+ * @param int $notcurrentuser 0=all user, 1=not current user
+ * @param int $socid Id third pary
+ * @param int $limit For pagination
+ * @param int $offset For pagination
+ * @param string $sortfield Sort criteria
+ * @param string $sortorder Sort order
+ * @return int -1 if KO, array with result if OK
+ */
+ public function liste_array($shortlist = 0, $draft = 0, $notcurrentuser = 0, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'p.datec', $sortorder = 'DESC')
+ {
+ // phpcs:enable
+ global $conf, $user;
- $ga = array();
+ $ga = array();
- $sql = "SELECT s.rowid, s.nom as name, s.client,";
- $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
- $sql .= " p.datep as dp, p.fin_validite as datelimite";
- if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user";
- $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c";
- if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
- $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")";
- $sql .= " AND p.fk_soc = s.rowid";
- $sql .= " AND p.fk_statut = c.id";
- if (!$user->rights->societe->client->voir && !$socid) //restriction
- {
- $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
- }
- if ($socid) $sql .= " AND s.rowid = ".$socid;
- if ($draft) $sql .= " AND p.fk_statut = 0";
- if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id;
- $sql .= $this->db->order($sortfield, $sortorder);
- $sql .= $this->db->plimit($limit, $offset);
+ $sql = "SELECT s.rowid, s.nom as name, s.client,";
+ $sql .= " p.rowid as supplier_proposalid, p.fk_statut, p.total_ht, p.ref, p.remise, ";
+ $sql .= " p.datep as dp, p.fin_validite as datelimite";
+ if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user";
+ $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as p, ".MAIN_DB_PREFIX."c_propalst as c";
+ if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
+ $sql .= " WHERE p.entity IN (".getEntity('supplier_proposal').")";
+ $sql .= " AND p.fk_soc = s.rowid";
+ $sql .= " AND p.fk_statut = c.id";
+ if (!$user->rights->societe->client->voir && !$socid) //restriction
+ {
+ $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
+ }
+ if ($socid) $sql .= " AND s.rowid = ".$socid;
+ if ($draft) $sql .= " AND p.fk_statut = 0";
+ if ($notcurrentuser > 0) $sql .= " AND p.fk_user_author <> ".$user->id;
+ $sql .= $this->db->order($sortfield, $sortorder);
+ $sql .= $this->db->plimit($limit, $offset);
- $result = $this->db->query($sql);
- if ($result)
- {
- $num = $this->db->num_rows($result);
- if ($num)
- {
- $i = 0;
- while ($i < $num)
- {
- $obj = $this->db->fetch_object($result);
+ $result = $this->db->query($sql);
+ if ($result)
+ {
+ $num = $this->db->num_rows($result);
+ if ($num)
+ {
+ $i = 0;
+ while ($i < $num)
+ {
+ $obj = $this->db->fetch_object($result);
- if ($shortlist == 1)
- {
- $ga[$obj->supplier_proposalid] = $obj->ref;
- } elseif ($shortlist == 2)
- {
- $ga[$obj->supplier_proposalid] = $obj->ref.' ('.$obj->name.')';
- } else {
- $ga[$i]['id'] = $obj->supplier_proposalid;
- $ga[$i]['ref'] = $obj->ref;
- $ga[$i]['name'] = $obj->name;
- }
+ if ($shortlist == 1)
+ {
+ $ga[$obj->supplier_proposalid] = $obj->ref;
+ } elseif ($shortlist == 2)
+ {
+ $ga[$obj->supplier_proposalid] = $obj->ref.' ('.$obj->name.')';
+ } else {
+ $ga[$i]['id'] = $obj->supplier_proposalid;
+ $ga[$i]['ref'] = $obj->ref;
+ $ga[$i]['name'] = $obj->name;
+ }
- $i++;
- }
- }
- return $ga;
- } else {
- dol_print_error($this->db);
- return -1;
- }
- }
+ $i++;
+ }
+ }
+ return $ga;
+ } else {
+ dol_print_error($this->db);
+ return -1;
+ }
+ }
- /**
- * Delete askprice
- *
- * @param User $user Object user that delete
- * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
- * @return int 1 if ok, otherwise if error
- */
- public function delete($user, $notrigger = 0)
- {
- global $conf, $langs;
- require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
+ /**
+ * Delete askprice
+ *
+ * @param User $user Object user that delete
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int 1 if ok, otherwise if error
+ */
+ public function delete($user, $notrigger = 0)
+ {
+ global $conf, $langs;
+ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
- $error = 0;
+ $error = 0;
- $this->db->begin();
+ $this->db->begin();
- if (!$notrigger)
- {
- // Call trigger
- $result = $this->call_trigger('PROPOSAL_SUPPLIER_DELETE', $user);
- if ($result < 0) { $error++; }
- // End call triggers
- }
+ if (!$notrigger)
+ {
+ // Call trigger
+ $result = $this->call_trigger('PROPOSAL_SUPPLIER_DELETE', $user);
+ if ($result < 0) { $error++; }
+ // End call triggers
+ }
- if (!$error)
- {
- $main = MAIN_DB_PREFIX.'supplier_proposaldet';
- $ef = $main."_extrafields";
- $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_supplier_proposal = ".$this->id.")";
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".$this->id;
- if ($this->db->query($sql))
- {
- $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE rowid = ".$this->id;
- if ($this->db->query($sqlef) && $this->db->query($sql))
- {
- // Delete linked object
- $res = $this->deleteObjectLinked();
- if ($res < 0) $error++;
+ if (!$error)
+ {
+ $main = MAIN_DB_PREFIX.'supplier_proposaldet';
+ $ef = $main."_extrafields";
+ $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_supplier_proposal = ".$this->id.")";
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal = ".$this->id;
+ if ($this->db->query($sql))
+ {
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal WHERE rowid = ".$this->id;
+ if ($this->db->query($sqlef) && $this->db->query($sql))
+ {
+ // Delete linked object
+ $res = $this->deleteObjectLinked();
+ if ($res < 0) $error++;
- if (!$error)
- {
- // We remove directory
- $ref = dol_sanitizeFileName($this->ref);
- if ($conf->supplier_proposal->dir_output && !empty($this->ref))
- {
- $dir = $conf->supplier_proposal->dir_output."/".$ref;
- $file = $dir."/".$ref.".pdf";
- if (file_exists($file))
- {
- dol_delete_preview($this);
+ if (!$error)
+ {
+ // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
+ $this->deleteEcmFiles();
- if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
- {
- $this->error = 'ErrorFailToDeleteFile';
- $this->errors = array('ErrorFailToDeleteFile');
- $this->db->rollback();
- return 0;
- }
- }
- if (file_exists($dir))
- {
- $res = @dol_delete_dir_recursive($dir);
- if (!$res)
- {
- $this->error = 'ErrorFailToDeleteDir';
- $this->errors = array('ErrorFailToDeleteDir');
- $this->db->rollback();
- return 0;
- }
- }
- }
- }
+ // We remove directory
+ $ref = dol_sanitizeFileName($this->ref);
+ if ($conf->supplier_proposal->dir_output && !empty($this->ref))
+ {
+ $dir = $conf->supplier_proposal->dir_output."/".$ref;
+ $file = $dir."/".$ref.".pdf";
+ if (file_exists($file))
+ {
+ dol_delete_preview($this);
- // Removed extrafields
- if (!$error)
- {
- $result = $this->deleteExtraFields();
- if ($result < 0)
- {
- $error++;
- $errorflag = -4;
- dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
- }
- }
+ if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers
+ {
+ $this->error = 'ErrorFailToDeleteFile';
+ $this->errors = array('ErrorFailToDeleteFile');
+ $this->db->rollback();
+ return 0;
+ }
+ }
+ if (file_exists($dir))
+ {
+ $res = @dol_delete_dir_recursive($dir);
+ if (!$res)
+ {
+ $this->error = 'ErrorFailToDeleteDir';
+ $this->errors = array('ErrorFailToDeleteDir');
+ $this->db->rollback();
+ return 0;
+ }
+ }
+ }
+ }
- if (!$error)
- {
- dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
- $this->db->commit();
- return 1;
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return 0;
- }
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -3;
- }
- } else {
- $this->error = $this->db->lasterror();
- $this->db->rollback();
- return -2;
- }
- } else {
- $this->db->rollback();
- return -1;
- }
- }
+ // Removed extrafields
+ if (!$error)
+ {
+ $result = $this->deleteExtraFields();
+ if ($result < 0)
+ {
+ $error++;
+ $errorflag = -4;
+ dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
+ }
+ }
- /**
- * Object SupplierProposal Information
- *
- * @param int $id Proposal id
- * @return void
- */
- public function info($id)
- {
- $sql = "SELECT c.rowid, ";
- $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,";
- $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture";
- $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c";
- $sql .= " WHERE c.rowid = ".$id;
+ if (!$error)
+ {
+ dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return 0;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -3;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -2;
+ }
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
- $result = $this->db->query($sql);
+ /**
+ * Object SupplierProposal Information
+ *
+ * @param int $id Proposal id
+ * @return void
+ */
+ public function info($id)
+ {
+ $sql = "SELECT c.rowid, ";
+ $sql .= " c.datec, c.date_valid as datev, c.date_cloture as dateo,";
+ $sql .= " c.fk_user_author, c.fk_user_valid, c.fk_user_cloture";
+ $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as c";
+ $sql .= " WHERE c.rowid = ".$id;
- if ($result)
- {
- if ($this->db->num_rows($result))
- {
- $obj = $this->db->fetch_object($result);
+ $result = $this->db->query($sql);
- $this->id = $obj->rowid;
+ if ($result)
+ {
+ if ($this->db->num_rows($result))
+ {
+ $obj = $this->db->fetch_object($result);
- $this->date_creation = $this->db->jdate($obj->datec);
- $this->date_validation = $this->db->jdate($obj->datev);
- $this->date_cloture = $this->db->jdate($obj->dateo);
+ $this->id = $obj->rowid;
- $cuser = new User($this->db);
- $cuser->fetch($obj->fk_user_author);
- $this->user_creation = $cuser;
+ $this->date_creation = $this->db->jdate($obj->datec);
+ $this->date_validation = $this->db->jdate($obj->datev);
+ $this->date_cloture = $this->db->jdate($obj->dateo);
- if ($obj->fk_user_valid)
- {
- $vuser = new User($this->db);
- $vuser->fetch($obj->fk_user_valid);
- $this->user_validation = $vuser;
- }
+ $cuser = new User($this->db);
+ $cuser->fetch($obj->fk_user_author);
+ $this->user_creation = $cuser;
- if ($obj->fk_user_cloture)
- {
- $cluser = new User($this->db);
- $cluser->fetch($obj->fk_user_cloture);
- $this->user_cloture = $cluser;
- }
- }
- $this->db->free($result);
- } else {
- dol_print_error($this->db);
- }
- }
+ if ($obj->fk_user_valid)
+ {
+ $vuser = new User($this->db);
+ $vuser->fetch($obj->fk_user_valid);
+ $this->user_validation = $vuser;
+ }
+
+ if ($obj->fk_user_cloture)
+ {
+ $cluser = new User($this->db);
+ $cluser->fetch($obj->fk_user_cloture);
+ $this->user_cloture = $cluser;
+ }
+ }
+ $this->db->free($result);
+ } else {
+ dol_print_error($this->db);
+ }
+ }
- /**
- * Return label of status of proposal (draft, validated, ...)
- *
- * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
- * @return string Label
- */
- public function getLibStatut($mode = 0)
- {
- return $this->LibStatut((isset($this->statut) ? $this->statut : $this->status), $mode);
- }
+ /**
+ * Return label of status of proposal (draft, validated, ...)
+ *
+ * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
+ * @return string Label
+ */
+ public function getLibStatut($mode = 0)
+ {
+ return $this->LibStatut((isset($this->statut) ? $this->statut : $this->status), $mode);
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Return label of a status (draft, validated, ...)
- *
- * @param int $status Id status
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Return label of a status (draft, validated, ...)
+ *
+ * @param int $status Id status
* @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
- * @return string Label
- */
- public function LibStatut($status, $mode = 1)
- {
- // phpcs:enable
+ * @return string Label
+ */
+ public function LibStatut($status, $mode = 1)
+ {
+ // phpcs:enable
- // Init/load array of translation of status
- if (empty($this->labelStatus) || empty($this->labelStatusShort))
- {
- global $langs;
- $langs->load("supplier_proposal");
- $this->labelStatus[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraft");
- $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans("SupplierProposalStatusValidated");
- $this->labelStatus[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSigned");
- $this->labelStatus[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSigned");
- $this->labelStatus[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosed");
- $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraftShort");
- $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans("Opened");
- $this->labelStatusShort[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSignedShort");
- $this->labelStatusShort[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSignedShort");
- $this->labelStatusShort[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosedShort");
- }
+ // Init/load array of translation of status
+ if (empty($this->labelStatus) || empty($this->labelStatusShort))
+ {
+ global $langs;
+ $langs->load("supplier_proposal");
+ $this->labelStatus[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraft");
+ $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans("SupplierProposalStatusValidated");
+ $this->labelStatus[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSigned");
+ $this->labelStatus[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSigned");
+ $this->labelStatus[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosed");
+ $this->labelStatusShort[self::STATUS_DRAFT] = $langs->trans("SupplierProposalStatusDraftShort");
+ $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->trans("Opened");
+ $this->labelStatusShort[self::STATUS_SIGNED] = $langs->trans("SupplierProposalStatusSignedShort");
+ $this->labelStatusShort[self::STATUS_NOTSIGNED] = $langs->trans("SupplierProposalStatusNotSignedShort");
+ $this->labelStatusShort[self::STATUS_CLOSE] = $langs->trans("SupplierProposalStatusClosedShort");
+ }
- $statusnew = '';
- if ($status == self::STATUS_DRAFT) $statusnew = 'status0';
- elseif ($status == self::STATUS_VALIDATED) $statusnew = 'status1';
- elseif ($status == self::STATUS_SIGNED) $statusnew = 'status4';
- elseif ($status == self::STATUS_NOTSIGNED) $statusnew = 'status9';
- elseif ($status == self::STATUS_CLOSE) $statusnew = 'status6';
+ $statusnew = '';
+ if ($status == self::STATUS_DRAFT) $statusnew = 'status0';
+ elseif ($status == self::STATUS_VALIDATED) $statusnew = 'status1';
+ elseif ($status == self::STATUS_SIGNED) $statusnew = 'status4';
+ elseif ($status == self::STATUS_NOTSIGNED) $statusnew = 'status9';
+ elseif ($status == self::STATUS_CLOSE) $statusnew = 'status6';
- return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode);
- }
+ return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusnew, $mode);
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
- *
- * @param User $user Object user
- * @param int $mode "opened" for askprice to close, "signed" for proposal to invoice
- * @return int <0 if KO, >0 if OK
- */
- public function load_board($user, $mode)
- {
- // phpcs:enable
- global $conf, $user, $langs;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
+ *
+ * @param User $user Object user
+ * @param int $mode "opened" for askprice to close, "signed" for proposal to invoice
+ * @return int <0 if KO, >0 if OK
+ */
+ public function load_board($user, $mode)
+ {
+ // phpcs:enable
+ global $conf, $user, $langs;
- $now = dol_now();
+ $now = dol_now();
- $this->nbtodo = $this->nbtodolate = 0;
- $clause = " WHERE";
+ $this->nbtodo = $this->nbtodolate = 0;
+ $clause = " WHERE";
- $sql = "SELECT p.rowid, p.ref, p.datec as datec";
- $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
- if (!$user->rights->societe->client->voir && !$user->socid)
- {
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
- $sql .= " WHERE sc.fk_user = ".$user->id;
- $clause = " AND";
- }
- $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")";
- if ($mode == 'opened') $sql .= " AND p.fk_statut = 1";
- if ($mode == 'signed') $sql .= " AND p.fk_statut = 2";
- if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid;
+ $sql = "SELECT p.rowid, p.ref, p.datec as datec";
+ $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
+ if (!$user->rights->societe->client->voir && !$user->socid)
+ {
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON p.fk_soc = sc.fk_soc";
+ $sql .= " WHERE sc.fk_user = ".$user->id;
+ $clause = " AND";
+ }
+ $sql .= $clause." p.entity IN (".getEntity('supplier_proposal').")";
+ if ($mode == 'opened') $sql .= " AND p.fk_statut = 1";
+ if ($mode == 'signed') $sql .= " AND p.fk_statut = 2";
+ if ($user->socid) $sql .= " AND p.fk_soc = ".$user->socid;
- $resql = $this->db->query($sql);
- if ($resql)
- {
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
$label = $labelShort = '';
$status = '';
- if ($mode == 'opened') {
- $delay_warning = $conf->supplier_proposal->cloture->warning_delay;
- $status = self::STATUS_VALIDATED;
- $label = $langs->trans("SupplierProposalsToClose");
- $labelShort = $langs->trans("ToAcceptRefuse");
- }
- if ($mode == 'signed') {
- $delay_warning = $conf->supplier_proposal->facturation->warning_delay;
- $status = self::STATUS_SIGNED;
- $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered
+ if ($mode == 'opened') {
+ $delay_warning = $conf->supplier_proposal->cloture->warning_delay;
+ $status = self::STATUS_VALIDATED;
+ $label = $langs->trans("SupplierProposalsToClose");
+ $labelShort = $langs->trans("ToAcceptRefuse");
+ }
+ if ($mode == 'signed') {
+ $delay_warning = $conf->supplier_proposal->facturation->warning_delay;
+ $status = self::STATUS_SIGNED;
+ $label = $langs->trans("SupplierProposalsToProcess"); // May be billed or ordered
$labelShort = $langs->trans("ToClose");
- }
+ }
- $response = new WorkboardResponse();
- $response->warning_delay = $delay_warning / 60 / 60 / 24;
- $response->label = $label;
- $response->labelShort = $labelShort;
- $response->url = DOL_URL_ROOT.'/supplier_proposal/list.php?search_status='.$status;
- $response->img = img_object('', "propal");
+ $response = new WorkboardResponse();
+ $response->warning_delay = $delay_warning / 60 / 60 / 24;
+ $response->label = $label;
+ $response->labelShort = $labelShort;
+ $response->url = DOL_URL_ROOT.'/supplier_proposal/list.php?search_status='.$status;
+ $response->img = img_object('', "propal");
- // This assignment in condition is not a bug. It allows walking the results.
- while ($obj = $this->db->fetch_object($resql))
- {
- $response->nbtodo++;
- if ($mode == 'opened')
- {
- $datelimit = $this->db->jdate($obj->datefin);
- if ($datelimit < ($now - $delay_warning))
- {
- $response->nbtodolate++;
- }
- }
- // TODO Definir regle des propales a facturer en retard
- // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
- }
- return $response;
- } else {
- $this->error = $this->db->lasterror();
- return -1;
- }
- }
+ // This assignment in condition is not a bug. It allows walking the results.
+ while ($obj = $this->db->fetch_object($resql))
+ {
+ $response->nbtodo++;
+ if ($mode == 'opened')
+ {
+ $datelimit = $this->db->jdate($obj->datefin);
+ if ($datelimit < ($now - $delay_warning))
+ {
+ $response->nbtodolate++;
+ }
+ }
+ // TODO Definir regle des propales a facturer en retard
+ // if ($mode == 'signed' && ! count($this->FactureListeArray($obj->rowid))) $this->nbtodolate++;
+ }
+ return $response;
+ } else {
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ }
- /**
- * Initialise an instance with random values.
- * Used to build previews or test instances.
- * id must be 0 if object instance is a specimen.
- *
- * @return void
- */
- public function initAsSpecimen()
- {
- global $user, $langs, $conf;
+ /**
+ * Initialise an instance with random values.
+ * Used to build previews or test instances.
+ * id must be 0 if object instance is a specimen.
+ *
+ * @return void
+ */
+ public function initAsSpecimen()
+ {
+ global $user, $langs, $conf;
- // Load array of products prodids
- $num_prods = 0;
- $prodids = array();
- $sql = "SELECT rowid";
- $sql .= " FROM ".MAIN_DB_PREFIX."product";
- $sql .= " WHERE entity IN (".getEntity('product').")";
- $sql .= $this->db->plimit(100);
+ // Load array of products prodids
+ $num_prods = 0;
+ $prodids = array();
+ $sql = "SELECT rowid";
+ $sql .= " FROM ".MAIN_DB_PREFIX."product";
+ $sql .= " WHERE entity IN (".getEntity('product').")";
+ $sql .= $this->db->plimit(100);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $num_prods = $this->db->num_rows($resql);
- $i = 0;
- while ($i < $num_prods)
- {
- $i++;
- $row = $this->db->fetch_row($resql);
- $prodids[$i] = $row[0];
- }
- }
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $num_prods = $this->db->num_rows($resql);
+ $i = 0;
+ while ($i < $num_prods)
+ {
+ $i++;
+ $row = $this->db->fetch_row($resql);
+ $prodids[$i] = $row[0];
+ }
+ }
- // Initialise parametres
- $this->id = 0;
- $this->ref = 'SPECIMEN';
- $this->specimen = 1;
- $this->socid = 1;
- $this->date = time();
- $this->cond_reglement_id = 1;
- $this->cond_reglement_code = 'RECEP';
- $this->mode_reglement_id = 7;
- $this->mode_reglement_code = 'CHQ';
- $this->note_public = 'This is a comment (public)';
- $this->note_private = 'This is a comment (private)';
- // Lines
- $nbp = 5;
- $xnbp = 0;
- while ($xnbp < $nbp)
- {
- $line = new SupplierProposalLine($this->db);
- $line->desc = $langs->trans("Description")." ".$xnbp;
- $line->qty = 1;
- $line->subprice = 100;
- $line->tva_tx = 19.6;
- $line->localtax1_tx = 0;
- $line->localtax2_tx = 0;
- if ($xnbp == 2)
- {
- $line->total_ht = 50;
- $line->total_ttc = 59.8;
- $line->total_tva = 9.8;
- $line->remise_percent = 50;
- } else {
- $line->total_ht = 100;
- $line->total_ttc = 119.6;
- $line->total_tva = 19.6;
- $line->remise_percent = 00;
- }
+ // Initialise parametres
+ $this->id = 0;
+ $this->ref = 'SPECIMEN';
+ $this->specimen = 1;
+ $this->socid = 1;
+ $this->date = time();
+ $this->cond_reglement_id = 1;
+ $this->cond_reglement_code = 'RECEP';
+ $this->mode_reglement_id = 7;
+ $this->mode_reglement_code = 'CHQ';
+ $this->note_public = 'This is a comment (public)';
+ $this->note_private = 'This is a comment (private)';
+ // Lines
+ $nbp = 5;
+ $xnbp = 0;
+ while ($xnbp < $nbp)
+ {
+ $line = new SupplierProposalLine($this->db);
+ $line->desc = $langs->trans("Description")." ".$xnbp;
+ $line->qty = 1;
+ $line->subprice = 100;
+ $line->tva_tx = 19.6;
+ $line->localtax1_tx = 0;
+ $line->localtax2_tx = 0;
+ if ($xnbp == 2)
+ {
+ $line->total_ht = 50;
+ $line->total_ttc = 59.8;
+ $line->total_tva = 9.8;
+ $line->remise_percent = 50;
+ } else {
+ $line->total_ht = 100;
+ $line->total_ttc = 119.6;
+ $line->total_tva = 19.6;
+ $line->remise_percent = 00;
+ }
- if ($num_prods > 0)
- {
- $prodid = mt_rand(1, $num_prods);
- $line->fk_product = $prodids[$prodid];
- }
+ if ($num_prods > 0)
+ {
+ $prodid = mt_rand(1, $num_prods);
+ $line->fk_product = $prodids[$prodid];
+ }
- $this->lines[$xnbp] = $line;
+ $this->lines[$xnbp] = $line;
- $this->total_ht += $line->total_ht;
- $this->total_tva += $line->total_tva;
- $this->total_ttc += $line->total_ttc;
+ $this->total_ht += $line->total_ht;
+ $this->total_tva += $line->total_tva;
+ $this->total_ttc += $line->total_ttc;
- $xnbp++;
- }
- }
+ $xnbp++;
+ }
+ }
- // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
- /**
- * Load indicator this->nb of global stats widget
- *
- * @return int <0 if ko, >0 if ok
- */
- public function load_state_board()
- {
- // phpcs:enable
- global $conf, $user;
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+ /**
+ * Load indicator this->nb of global stats widget
+ *
+ * @return int <0 if ko, >0 if ok
+ */
+ public function load_state_board()
+ {
+ // phpcs:enable
+ global $conf, $user;
- $this->nb = array();
- $clause = "WHERE";
+ $this->nb = array();
+ $clause = "WHERE";
- $sql = "SELECT count(p.rowid) as nb";
- $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
- if (!$user->rights->societe->client->voir && !$user->socid)
- {
- $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
- $sql .= " WHERE sc.fk_user = ".$user->id;
- $clause = "AND";
- }
- $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")";
+ $sql = "SELECT count(p.rowid) as nb";
+ $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p";
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid";
+ if (!$user->rights->societe->client->voir && !$user->socid)
+ {
+ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
+ $sql .= " WHERE sc.fk_user = ".$user->id;
+ $clause = "AND";
+ }
+ $sql .= " ".$clause." p.entity IN (".getEntity('supplier_proposal').")";
- $resql = $this->db->query($sql);
- if ($resql)
- {
- // This assignment in condition is not a bug. It allows walking the results.
- while ($obj = $this->db->fetch_object($resql))
- {
- $this->nb["supplier_proposals"] = $obj->nb;
- }
- $this->db->free($resql);
- return 1;
- } else {
- dol_print_error($this->db);
- $this->error = $this->db->lasterror();
- return -1;
- }
- }
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ // This assignment in condition is not a bug. It allows walking the results.
+ while ($obj = $this->db->fetch_object($resql))
+ {
+ $this->nb["supplier_proposals"] = $obj->nb;
+ }
+ $this->db->free($resql);
+ return 1;
+ } else {
+ dol_print_error($this->db);
+ $this->error = $this->db->lasterror();
+ return -1;
+ }
+ }
- /**
- * Returns the reference to the following non used Proposal used depending on the active numbering module
- * defined into SUPPLIER_PROPOSAL_ADDON
- *
- * @param Societe $soc Object thirdparty
- * @return string Reference libre pour la propale
- */
- public function getNextNumRef($soc)
- {
- global $conf, $db, $langs;
- $langs->load("supplier_proposal");
+ /**
+ * Returns the reference to the following non used Proposal used depending on the active numbering module
+ * defined into SUPPLIER_PROPOSAL_ADDON
+ *
+ * @param Societe $soc Object thirdparty
+ * @return string Reference libre pour la propale
+ */
+ public function getNextNumRef($soc)
+ {
+ global $conf, $db, $langs;
+ $langs->load("supplier_proposal");
- if (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON))
- {
- $mybool = false;
+ if (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON))
+ {
+ $mybool = false;
- $file = $conf->global->SUPPLIER_PROPOSAL_ADDON.".php";
- $classname = $conf->global->SUPPLIER_PROPOSAL_ADDON;
+ $file = $conf->global->SUPPLIER_PROPOSAL_ADDON.".php";
+ $classname = $conf->global->SUPPLIER_PROPOSAL_ADDON;
- // Include file with class
- $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
- foreach ($dirmodels as $reldir) {
- $dir = dol_buildpath($reldir."core/modules/supplier_proposal/");
+ // Include file with class
+ $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
+ foreach ($dirmodels as $reldir) {
+ $dir = dol_buildpath($reldir."core/modules/supplier_proposal/");
- // Load file with numbering class (if found)
- $mybool |= @include_once $dir.$file;
- }
+ // Load file with numbering class (if found)
+ $mybool |= @include_once $dir.$file;
+ }
- if (!$mybool)
- {
- dol_print_error('', "Failed to include file ".$file);
- return '';
- }
+ if (!$mybool)
+ {
+ dol_print_error('', "Failed to include file ".$file);
+ return '';
+ }
- $obj = new $classname();
- $numref = "";
- $numref = $obj->getNextValue($soc, $this);
+ $obj = new $classname();
+ $numref = "";
+ $numref = $obj->getNextValue($soc, $this);
- if ($numref != "")
- {
- return $numref;
- } else {
- $this->error = $obj->error;
- return "";
- }
- } else {
- $langs->load("errors");
- print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("SupplierProposal"));
- return "";
- }
- }
+ if ($numref != "")
+ {
+ return $numref;
+ } else {
+ $this->error = $obj->error;
+ return "";
+ }
+ } else {
+ $langs->load("errors");
+ print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("SupplierProposal"));
+ return "";
+ }
+ }
- /**
- * Return clicable link of object (with eventually picto)
- *
- * @param int $withpicto Add picto into link
- * @param string $option Where point the link ('compta', 'expedition', 'document', ...)
- * @param string $get_params Parametres added to url
- * @param int $notooltip 1=Disable tooltip
- * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
- * @param int $addlinktonotes Add link to show notes
- * @return string String with URL
- */
- public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
- {
- global $langs, $conf, $user;
+ /**
+ * Return clicable link of object (with eventually picto)
+ *
+ * @param int $withpicto Add picto into link
+ * @param string $option Where point the link ('compta', 'expedition', 'document', ...)
+ * @param string $get_params Parametres added to url
+ * @param int $notooltip 1=Disable tooltip
+ * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+ * @param int $addlinktonotes Add link to show notes
+ * @return string String with URL
+ */
+ public function getNomUrl($withpicto = 0, $option = '', $get_params = '', $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0)
+ {
+ global $langs, $conf, $user;
- if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
+ if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
- $url = '';
- $result = '';
+ $url = '';
+ $result = '';
- $label = ''.$langs->trans("SupplierProposal").' ';
- if (!empty($this->ref)) $label .= ''.$langs->trans('Ref').': '.$this->ref;
- if (!empty($this->ref_fourn)) $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_fourn;
- if (!empty($this->total_ht)) $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_tva)) $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
- if (!empty($this->total_ttc)) $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
- if (isset($this->status)) {
- $label .= ''.$langs->trans("Status").": ".$this->getLibStatut(5);
- }
+ $label = img_picto('', $this->picto).' '.$langs->trans("SupplierProposal").' ';
+ if (!empty($this->ref)) $label .= ''.$langs->trans('Ref').': '.$this->ref;
+ if (!empty($this->ref_fourn)) $label .= ''.$langs->trans('RefSupplier').': '.$this->ref_fourn;
+ if (!empty($this->total_ht)) $label .= ''.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_tva)) $label .= ''.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
+ if (!empty($this->total_ttc)) $label .= ''.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
+ if (isset($this->status)) {
+ $label .= ''.$langs->trans("Status").": ".$this->getLibStatut(5);
+ }
- if ($option == '') {
- $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params;
- }
- if ($option == 'document') {
- $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params;
- }
+ if ($option == '') {
+ $url = DOL_URL_ROOT.'/supplier_proposal/card.php?id='.$this->id.$get_params;
+ }
+ if ($option == 'document') {
+ $url = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$this->id.$get_params;
+ }
- if ($option !== 'nolink')
- {
- // Add param to save lastsearch_values or not
- $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
- if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
- if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
- }
+ if ($option !== 'nolink')
+ {
+ // Add param to save lastsearch_values or not
+ $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+ if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
+ if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
+ }
- $linkclose = '';
- if (empty($notooltip) && $user->rights->propal->lire)
- {
- if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
- {
- $label = $langs->trans("ShowSupplierProposal");
- $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
- }
- $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
- $linkclose .= ' class="classfortooltip"';
- }
+ $linkclose = '';
+ if (empty($notooltip) && $user->rights->propal->lire)
+ {
+ if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
+ {
+ $label = $langs->trans("ShowSupplierProposal");
+ $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
+ }
+ $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
+ $linkclose .= ' class="classfortooltip"';
+ }
- $linkstart = '';
- $linkend = ' ';
+ $linkstart = '';
+ $linkend = ' ';
- $result .= $linkstart;
- if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
- if ($withpicto != 2) $result .= $this->ref;
- $result .= $linkend;
+ $result .= $linkstart;
+ if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+ if ($withpicto != 2) $result .= $this->ref;
+ $result .= $linkend;
- if ($addlinktonotes)
- {
- $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
- if ($txttoshow)
- {
- $notetoshow = $langs->trans("ViewPrivateNote").': '.dol_string_nohtmltag($txttoshow, 1);
- $result .= ' ';
- $result .= '';
- $result .= img_picto('', 'note');
- $result .= ' ';
- //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
- //$result.=' ';
- $result .= '';
- }
- }
+ if ($addlinktonotes)
+ {
+ $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
+ if ($txttoshow)
+ {
+ $notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1);
+ $result .= '
';
+ $result .= '';
+ $result .= img_picto('', 'note');
+ $result .= ' ';
+ //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
+ //$result.='';
+ $result .= ' ';
+ }
+ }
- return $result;
- }
+ return $result;
+ }
- /**
- * Retrieve an array of supplier proposal lines
- *
- * @return int >0 if OK, <0 if KO
- */
- public function getLinesArray()
- {
- // For other object, here we call fetch_lines. But fetch_lines does not exists on supplier proposal
+ /**
+ * Retrieve an array of supplier proposal lines
+ *
+ * @return int >0 if OK, <0 if KO
+ */
+ public function getLinesArray()
+ {
+ // For other object, here we call fetch_lines. But fetch_lines does not exists on supplier proposal
- $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
- $sql .= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,';
- $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,';
- $sql .= ' pt.product_type, pt.rang, pt.fk_parent_line,';
- $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,';
- $sql .= ' p.description as product_desc, pt.ref_fourn as ref_supplier,';
- $sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit';
- $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt';
- $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
- $sql .= ' WHERE pt.fk_supplier_proposal = '.$this->id;
- $sql .= ' ORDER BY pt.rang ASC, pt.rowid';
+ $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,';
+ $sql .= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,';
+ $sql .= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,';
+ $sql .= ' pt.product_type, pt.rang, pt.fk_parent_line,';
+ $sql .= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,';
+ $sql .= ' p.description as product_desc, pt.ref_fourn as ref_supplier,';
+ $sql .= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc, pt.fk_unit';
+ $sql .= ' FROM '.MAIN_DB_PREFIX.'supplier_proposaldet as pt';
+ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid';
+ $sql .= ' WHERE pt.fk_supplier_proposal = '.$this->id;
+ $sql .= ' ORDER BY pt.rang ASC, pt.rowid';
- dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG);
- $resql = $this->db->query($sql);
- if ($resql)
- {
- $num = $this->db->num_rows($resql);
- $i = 0;
+ dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql)
+ {
+ $num = $this->db->num_rows($resql);
+ $i = 0;
- while ($i < $num)
- {
- $obj = $this->db->fetch_object($resql);
+ while ($i < $num)
+ {
+ $obj = $this->db->fetch_object($resql);
- $this->lines[$i] = new SupplierProposalLine($this->db);
- $this->lines[$i]->id = $obj->rowid; // for backward compatibility
- $this->lines[$i]->rowid = $obj->rowid;
- $this->lines[$i]->label = $obj->custom_label;
- $this->lines[$i]->description = $obj->description;
- $this->lines[$i]->fk_product = $obj->fk_product;
- $this->lines[$i]->ref = $obj->ref;
- $this->lines[$i]->product_label = $obj->product_label;
- $this->lines[$i]->product_desc = $obj->product_desc;
- $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated
- $this->lines[$i]->product_type = $obj->product_type;
- $this->lines[$i]->qty = $obj->qty;
- $this->lines[$i]->subprice = $obj->subprice;
- $this->lines[$i]->fk_remise_except = $obj->fk_remise_except;
- $this->lines[$i]->remise_percent = $obj->remise_percent;
- $this->lines[$i]->tva_tx = $obj->tva_tx;
- $this->lines[$i]->info_bits = $obj->info_bits;
- $this->lines[$i]->total_ht = $obj->total_ht;
- $this->lines[$i]->total_tva = $obj->total_tva;
- $this->lines[$i]->total_ttc = $obj->total_ttc;
- $this->lines[$i]->fk_fournprice = $obj->fk_fournprice;
- $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht);
- $this->lines[$i]->pa_ht = $marginInfos[0];
- $this->lines[$i]->marge_tx = $marginInfos[1];
- $this->lines[$i]->marque_tx = $marginInfos[2];
- $this->lines[$i]->fk_parent_line = $obj->fk_parent_line;
- $this->lines[$i]->special_code = $obj->special_code;
- $this->lines[$i]->rang = $obj->rang;
+ $this->lines[$i] = new SupplierProposalLine($this->db);
+ $this->lines[$i]->id = $obj->rowid; // for backward compatibility
+ $this->lines[$i]->rowid = $obj->rowid;
+ $this->lines[$i]->label = $obj->custom_label;
+ $this->lines[$i]->description = $obj->description;
+ $this->lines[$i]->fk_product = $obj->fk_product;
+ $this->lines[$i]->ref = $obj->ref;
+ $this->lines[$i]->product_label = $obj->product_label;
+ $this->lines[$i]->product_desc = $obj->product_desc;
+ $this->lines[$i]->fk_product_type = $obj->fk_product_type; // deprecated
+ $this->lines[$i]->product_type = $obj->product_type;
+ $this->lines[$i]->qty = $obj->qty;
+ $this->lines[$i]->subprice = $obj->subprice;
+ $this->lines[$i]->fk_remise_except = $obj->fk_remise_except;
+ $this->lines[$i]->remise_percent = $obj->remise_percent;
+ $this->lines[$i]->tva_tx = $obj->tva_tx;
+ $this->lines[$i]->info_bits = $obj->info_bits;
+ $this->lines[$i]->total_ht = $obj->total_ht;
+ $this->lines[$i]->total_tva = $obj->total_tva;
+ $this->lines[$i]->total_ttc = $obj->total_ttc;
+ $this->lines[$i]->fk_fournprice = $obj->fk_fournprice;
+ $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->lines[$i]->fk_fournprice, $obj->pa_ht);
+ $this->lines[$i]->pa_ht = $marginInfos[0];
+ $this->lines[$i]->marge_tx = $marginInfos[1];
+ $this->lines[$i]->marque_tx = $marginInfos[2];
+ $this->lines[$i]->fk_parent_line = $obj->fk_parent_line;
+ $this->lines[$i]->special_code = $obj->special_code;
+ $this->lines[$i]->rang = $obj->rang;
- $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated
- $this->lines[$i]->ref_supplier = $obj->ref_supplier;
+ $this->lines[$i]->ref_fourn = $obj->ref_supplier; // deprecated
+ $this->lines[$i]->ref_supplier = $obj->ref_supplier;
- // Multicurrency
- $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency;
- $this->lines[$i]->multicurrency_code = $obj->multicurrency_code;
- $this->lines[$i]->multicurrency_subprice = $obj->multicurrency_subprice;
- $this->lines[$i]->multicurrency_total_ht = $obj->multicurrency_total_ht;
- $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva;
- $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
- $this->lines[$i]->fk_unit = $obj->fk_unit;
+ // Multicurrency
+ $this->lines[$i]->fk_multicurrency = $obj->fk_multicurrency;
+ $this->lines[$i]->multicurrency_code = $obj->multicurrency_code;
+ $this->lines[$i]->multicurrency_subprice = $obj->multicurrency_subprice;
+ $this->lines[$i]->multicurrency_total_ht = $obj->multicurrency_total_ht;
+ $this->lines[$i]->multicurrency_total_tva = $obj->multicurrency_total_tva;
+ $this->lines[$i]->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
+ $this->lines[$i]->fk_unit = $obj->fk_unit;
- $i++;
- }
- $this->db->free($resql);
+ $i++;
+ }
+ $this->db->free($resql);
- return 1;
- } else {
- $this->error = $this->db->error();
- return -1;
- }
- }
+ return 1;
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
- /**
- * Create a document onto disk according to template module.
- *
- * @param string $modele Force model to use ('' to not force)
- * @param Translate $outputlangs Object langs to use for output
- * @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;
+ /**
+ * Create a document onto disk according to template module.
+ *
+ * @param string $modele Force model to use ('' to not force)
+ * @param Translate $outputlangs Object langs to use for output
+ * @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;
- $langs->load("supplier_proposal");
+ $langs->load("supplier_proposal");
$outputlangs->load("products");
- if (!dol_strlen($modele)) {
- $modele = 'aurore';
+ if (!dol_strlen($modele)) {
+ $modele = 'aurore';
- if ($this->modelpdf) {
- $modele = $this->modelpdf;
- } elseif (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON_PDF)) {
- $modele = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF;
- }
- }
+ if ($this->model_pdf) {
+ $modele = $this->model_pdf;
+ } elseif (!empty($conf->global->SUPPLIER_PROPOSAL_ADDON_PDF)) {
+ $modele = $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF;
+ }
+ }
- $modelpath = "core/modules/supplier_proposal/doc/";
+ $modelpath = "core/modules/supplier_proposal/doc/";
- return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
- }
+ return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
+ }
- /**
- * Function used to replace a thirdparty id with another one.
- *
- * @param DoliDB $db Database handler
- * @param int $origin_id Old thirdparty id
- * @param int $dest_id New thirdparty id
- * @return bool
- */
- public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
- {
- $tables = array(
- 'supplier_proposal'
- );
+ /**
+ * Function used to replace a thirdparty id with another one.
+ *
+ * @param DoliDB $db Database handler
+ * @param int $origin_id Old thirdparty id
+ * @param int $dest_id New thirdparty id
+ * @return bool
+ */
+ public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
+ {
+ $tables = array(
+ 'supplier_proposal'
+ );
- return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
- }
+ return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
+ }
}
diff --git a/htdocs/takepos/admin/receipt.php b/htdocs/takepos/admin/receipt.php
index cff6eabd449..62e08d2084d 100644
--- a/htdocs/takepos/admin/receipt.php
+++ b/htdocs/takepos/admin/receipt.php
@@ -233,6 +233,14 @@ print '
';
print $form->selectyesno("TAKEPOS_AUTO_PRINT_TICKETS", $conf->global->TAKEPOS_AUTO_PRINT_TICKETS, 1);
print " \n";
+if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && filter_var($conf->global->TAKEPOS_PRINT_SERVER, FILTER_VALIDATE_URL) == true) {
+ print '
';
+ print $langs->trans('WeighingScale');
+ print ' ';
+ print ajax_constantonoff("TAKEPOS_WEIGHING_SCALE", array(), $conf->entity, 0, 0, 1, 0);
+ print " \n";
+}
+
print '
';
print '
';
diff --git a/htdocs/takepos/index.php b/htdocs/takepos/index.php
index 82dec49b7db..390f71491ba 100644
--- a/htdocs/takepos/index.php
+++ b/htdocs/takepos/index.php
@@ -747,6 +747,19 @@ function FullScreen() {
document.documentElement.requestFullscreen();
}
+function WeighingScale(){
+ console.log("Weighing Scale");
+ $.ajax({
+ type: "POST",
+ url: 'global->TAKEPOS_PRINT_SERVER; ?>/scale',
+ })
+ .done(function( editnumber ) {
+ $("#poslines").load("invoice.php?action=updateqty&place="+place+"&idline="+selectedline+"&number="+editnumber, function() {
+ editnumber="";
+ });
+ });
+}
+
$( document ).ready(function() {
PrintCategories(0);
LoadProducts(0);
@@ -975,6 +988,11 @@ if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) {
$menus[$r++] = array('title'=>'
'.$langs->trans("Logout").'
', 'action'=>'window.location.href=\''.DOL_URL_ROOT.'/user/logout.php\';');
}
+if ($conf->global->TAKEPOS_WEIGHING_SCALE)
+{
+ $menus[$r++] = array('title'=>'
'.$langs->trans("WeighingScale").'
', 'action'=>'WeighingScale();');
+}
+
?>
diff --git a/htdocs/takepos/invoice.php b/htdocs/takepos/invoice.php
index aaffdd7e01a..2f45d24c401 100644
--- a/htdocs/takepos/invoice.php
+++ b/htdocs/takepos/invoice.php
@@ -369,38 +369,38 @@ if ($action == "freezone") {
$tva_tx = get_default_tva($mysoc, $customer);
}
- // Local Taxes
- $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr);
- $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr);
+ // Local Taxes
+ $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr);
+ $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr);
- $invoice->addline($desc, $number, 1, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', 0, 0, 0, '', 'TTC', $number, 0, -1, 0, '', 0, 0, null, '', '', 0, 100, '', null, 0);
- $invoice->fetch($placeid);
+ $invoice->addline($desc, $number, 1, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', 0, 0, 0, '', 'TTC', $number, 0, -1, 0, '', 0, 0, null, '', '', 0, 100, '', null, 0);
+ $invoice->fetch($placeid);
}
if ($action == "addnote") {
- foreach ($invoice->lines as $line)
- {
- if ($line->id == $number)
+ foreach ($invoice->lines as $line)
+ {
+ if ($line->id == $number)
{
$line->array_options['order_notes'] = $desc;
$result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit);
- }
- }
- $invoice->fetch($placeid);
+ }
+ }
+ $invoice->fetch($placeid);
}
if ($action == "deleteline") {
- if ($idline > 0 and $placeid > 0) { // If invoice exists and line selected. To avoid errors if deleted from another device or no line selected.
- $invoice->deleteline($idline);
- $invoice->fetch($placeid);
- } elseif ($placeid > 0) { // If invoice exists but no line selected, proceed to delete last line.
- $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facturedet where fk_facture='".$placeid."' order by rowid DESC";
- $resql = $db->query($sql);
- $row = $db->fetch_array($resql);
- $deletelineid = $row[0];
- $invoice->deleteline($deletelineid);
- $invoice->fetch($placeid);
- }
+ if ($idline > 0 and $placeid > 0) { // If invoice exists and line selected. To avoid errors if deleted from another device or no line selected.
+ $invoice->deleteline($idline);
+ $invoice->fetch($placeid);
+ } elseif ($placeid > 0) { // If invoice exists but no line selected, proceed to delete last line.
+ $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facturedet where fk_facture='".$placeid."' order by rowid DESC";
+ $resql = $db->query($sql);
+ $row = $db->fetch_array($resql);
+ $deletelineid = $row[0];
+ $invoice->deleteline($deletelineid);
+ $invoice->fetch($placeid);
+ }
if (count($invoice->lines) == 0) $invoice->delete($user);
}
@@ -830,7 +830,7 @@ $( document ).ready(function() {
$s .= '
'.$langs->trans("SubscriptionNotReceived");
if ($adh->statut > 0) $s .= " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated
}
- if (empty($adh->statut)) { $s .= ""; }
+ if (empty($adh->statut)) { $s .= ""; }
} else {
$s .= '
'.$langs->trans("ThirdpartyNotLinkedToMember");
}
@@ -1011,47 +1011,47 @@ if ($placeid > 0)
$htmlsupplements[$line->fk_parent_line] .= ''."\n";
continue;
}
- $htmlforlines = '';
+ $htmlforlines = '';
- $htmlforlines .= '
id.'">';
- $htmlforlines .= '';
+ $htmlforlines .= ' id.'">';
+ $htmlforlines .= '';
if ($_SESSION["basiclayout"] == 1) $htmlforlines .= ''.$line->qty." x ";
- if (isset($line->product_type))
- {
- if (empty($line->product_type)) $htmlforlines .= img_object('', 'product').' ';
- else $htmlforlines .= img_object('', 'service').' ';
- }
- if (empty($conf->global->TAKEPOS_SHOW_N_FIRST_LINES)) {
- $tooltiptext = '';
- if ($line->product_ref) {
- $tooltiptext .= ''.$langs->trans("Ref").' : '.$line->product_ref.' ';
- $tooltiptext .= ''.$langs->trans("Label").' : '.$line->product_label.' ';
- if ($line->product_label != $line->desc) {
- if ($line->desc) $tooltiptext .= ' ';
- $tooltiptext .= $line->desc;
- }
- }
- $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext);
- } else {
- if ($line->product_label) $htmlforlines .= $line->product_label;
- if ($line->product_label != $line->desc)
- {
- if ($line->product_label && $line->desc) $htmlforlines .= ' ';
- $firstline = dolGetFirstLineOfText($line->desc, $conf->global->TAKEPOS_SHOW_N_FIRST_LINES);
- if ($firstline != $line->desc)
- {
- $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc);
- } else {
- $htmlforlines .= $line->desc;
- }
- }
- }
- if (!empty($line->array_options['options_order_notes'])) $htmlforlines .= " (".$line->array_options['options_order_notes'].")";
- if ($_SESSION["basiclayout"] == 1) $htmlforlines .= ' - + ';
+ if (isset($line->product_type))
+ {
+ if (empty($line->product_type)) $htmlforlines .= img_object('', 'product').' ';
+ else $htmlforlines .= img_object('', 'service').' ';
+ }
+ if (empty($conf->global->TAKEPOS_SHOW_N_FIRST_LINES)) {
+ $tooltiptext = '';
+ if ($line->product_ref) {
+ $tooltiptext .= ''.$langs->trans("Ref").' : '.$line->product_ref.' ';
+ $tooltiptext .= ''.$langs->trans("Label").' : '.$line->product_label.' ';
+ if ($line->product_label != $line->desc) {
+ if ($line->desc) $tooltiptext .= ' ';
+ $tooltiptext .= $line->desc;
+ }
+ }
+ $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext);
+ } else {
+ if ($line->product_label) $htmlforlines .= $line->product_label;
+ if ($line->product_label != $line->desc)
+ {
+ if ($line->product_label && $line->desc) $htmlforlines .= ' ';
+ $firstline = dolGetFirstLineOfText($line->desc, $conf->global->TAKEPOS_SHOW_N_FIRST_LINES);
+ if ($firstline != $line->desc)
+ {
+ $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc);
+ } else {
+ $htmlforlines .= $line->desc;
+ }
+ }
+ }
+ if (!empty($line->array_options['options_order_notes'])) $htmlforlines .= " (".$line->array_options['options_order_notes'].")";
+ if ($_SESSION["basiclayout"] == 1) $htmlforlines .= '- + ';
if ($_SESSION["basiclayout"] != 1)
{
$moreinfo = '';
diff --git a/htdocs/theme/eldy/dropdown.inc.php b/htdocs/theme/eldy/dropdown.inc.php
index 3665f43d9c4..12f34ed50ac 100644
--- a/htdocs/theme/eldy/dropdown.inc.php
+++ b/htdocs/theme/eldy/dropdown.inc.php
@@ -217,6 +217,7 @@ a.top-menu-dropdown-link {
}
.dropdown-menu > .user-footer {
+ border-top: 1px solid #f0f0f0;
background-color: #f9f9f9;
padding: 10px;
}
@@ -225,8 +226,9 @@ a.top-menu-dropdown-link {
clear: both;
}
-
.dropdown-menu > .bookmark-footer{
+ border-top: 1px solid #f0f0f0;
+ background-color: #f9f9f9;
padding: 10px;
}
@@ -239,7 +241,6 @@ a.top-menu-dropdown-link {
}
.dropdown-menu > .bookmark-body, .dropdown-body{
- padding: 10px 0;
overflow-y: auto;
max-height: 60vh ; /* fallback for browsers without support for calc() */
max-height: calc(90vh - 110px) ;
@@ -333,7 +334,7 @@ a.top-menu-dropdown-link {
display: block !important;
box-sizing: border-box;
width: 100%;
- padding: .25rem 1.5rem .25rem 1rem;
+ padding: .3em 1.5em .4em 1em;
clear: both;
font-weight: 400;
color: #212529 !important;
diff --git a/htdocs/theme/eldy/global.inc.php b/htdocs/theme/eldy/global.inc.php
index ce6e52cc256..1e4f278afc0 100644
--- a/htdocs/theme/eldy/global.inc.php
+++ b/htdocs/theme/eldy/global.inc.php
@@ -118,7 +118,7 @@ body {
th a { font-weight: !important; }
a.tab { font-weight: 500 !important; }
-a:link, a:visited, a:hover, a:active { font-family: ; color: var(--colortextlink); text-decoration: none; }
+a:link, a:visited, a:hover, a:active { color: var(--colortextlink); text-decoration: none; }
a:hover { text-decoration: underline; color: var(--colortextlink); }
a.commonlink { color: var(--colortextlink) !important; text-decoration: none; }
th.liste_titre a div div:hover, th.liste_titre_sel a div div:hover { text-decoration: underline; }
@@ -534,6 +534,17 @@ div.floatright
.largenumber {
font-size: 1.4em;
}
+button[name='button_search_x'] span.fa.fa-search {
+ font-size: 1.3em;
+}
+button[name='button_removefilter_x'] span.fa.fa-remove {
+ opacity: 0.5;
+ font-size: 1.3em;
+}
+button:focus {
+ outline: none;
+}
+
th .button {
-webkit-box-shadow: none !important;
@@ -3632,8 +3643,8 @@ ul.noborder li:nth-child(even):not(.liste_titre) {
/* padding: 3px; */
}
.boxstats {
- padding-left: 3px;
- padding-right: 3px;
+ padding-left: 6px;
+ padding-right: 6px;
padding-top: 2px;
padding-bottom: 2px;
width: 118px;
@@ -4176,7 +4187,7 @@ div.ui-tooltip {
div.ui-tooltip.mytooltip {
border: none !important;
padding: 10px 15px;
- border-radius: 0;
+ border-radius: 4px;
margin: 2px;
font-stretch: condensed;
-moz-box-shadow: 0.5px 0.5px 4px 0px rgba(0, 0, 0, 0.5);
@@ -4186,6 +4197,8 @@ div.ui-tooltip.mytooltip {
filter:progid:DXImageTransform.Microsoft.Shadow(color=#656565, Direction=134, Strength=5);
background: var(--tooltipbgcolor) !important;
color : var(--tooltipfontcolor);
+ line-height: 1.6em;
+ min-width: 200px;
}
@@ -4447,7 +4460,7 @@ table.cal_event td.cal_event_right { padding: 4px 4px !important; }
.cal_event a:active { color: #111111; font-weight: normal !important; }
.cal_event_notbusy a.cal_event_title:hover { color: #111111; font-weight: normal !important; color:rgba(255,255,255,.75); }
.cal_event_busy { }
-.cal_peruserviewname { max-width: 140px; height: 22px; }
+.cal_peruserviewname { max-width: 140px; height: 30px !important; }
.cal_event span.badge.badge-status { border: 1px solid #aaa; }
table.cal_month tr td table.nobordernopadding tr td { padding: 0 2px 0 2px; }
table.cal_month tr.liste_titre td.tdfordaytitle { min-width: 120px; }
@@ -6269,6 +6282,16 @@ div.tabsElem a.tab {
span.phpdebugbar-tooltip.phpdebugbar-tooltip-extra-wide, span.phpdebugbar-tooltip.phpdebugbar-tooltip-wide {
width: 250px !important;
}
+.phpdebugbar-indicator span.phpdebugbar-tooltip {
+ opacity: .95 !important;
+}
+a.phpdebugbar-tab.phpdebugbar-active {
+ background-image: unset !important;
+}
+.phpdebugbar-indicator .fa {
+ font-family: "Font Awesome 5 Free";
+ font-weight: 600;
+}
/* ============================================================================== */
diff --git a/htdocs/theme/eldy/info-box.inc.php b/htdocs/theme/eldy/info-box.inc.php
index 63f42cdfad8..8146bb2c563 100644
--- a/htdocs/theme/eldy/info-box.inc.php
+++ b/htdocs/theme/eldy/info-box.inc.php
@@ -17,7 +17,7 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?>
min-height: 90px;
/* background: #fff; */
width: 100%;
- box-shadow: 1px 1px 2px rgba(128, 128, 128, 0.2);
+ box-shadow: 1px 1px 15px rgba(192, 192, 192, 0.2);
border-radius: 2px;
border: 1px solid #e9e9e9;
margin-bottom: 15px;
diff --git a/htdocs/theme/md/dropdown.inc.php b/htdocs/theme/md/dropdown.inc.php
index b86b935c5d1..a8d2f77498d 100644
--- a/htdocs/theme/md/dropdown.inc.php
+++ b/htdocs/theme/md/dropdown.inc.php
@@ -218,7 +218,7 @@ a.top-menu-dropdown-link {
.dropdown-menu .dropdown-header{
- padding: 5px 10px 10px 10px;
+ padding: 8px 10px 10px 10px;
}
.dropdown-menu > .user-footer {
@@ -232,6 +232,8 @@ a.top-menu-dropdown-link {
.dropdown-menu > .bookmark-footer{
+ border-top: 1px solid #f0f0f0;
+ background-color: #f9f9f9;
padding: 10px;
}
diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php
index 970c81e9139..4234790cc87 100644
--- a/htdocs/theme/md/style.css.php
+++ b/htdocs/theme/md/style.css.php
@@ -4093,17 +4093,20 @@ div.ui-tooltip {
max-width: px !important;
}
-.mytooltip {
+div.ui-tooltip.mytooltip {
width: px;
border-top: solid 1px #BBBBBB;
border-: solid 1px #BBBBBB;
border-: solid 1px #444444;
border-bottom: solid 1px #444444;
- padding: 5px 20px;
+ padding: 10px 20px;
border-radius: 0;
box-shadow: 0 0 4px grey;
margin: 2px;
font-stretch: condensed;
+ /*background: var(--tooltipbgcolor) !important;
+ color : var(--tooltipfontcolor);*/
+ line-height: 1.6em;
}
@@ -6154,6 +6157,25 @@ border-top-right-radius: 6px;
}
+/* ============================================================================== */
+/* CSS style for debugbar */
+/* ============================================================================== */
+
+span.phpdebugbar-tooltip.phpdebugbar-tooltip-extra-wide, span.phpdebugbar-tooltip.phpdebugbar-tooltip-wide {
+ width: 250px !important;
+}
+.phpdebugbar-indicator span.phpdebugbar-tooltip {
+ opacity: .95 !important;
+}
+a.phpdebugbar-tab.phpdebugbar-active {
+ background-image: unset !important;
+}
+.phpdebugbar-indicator .fa {
+ font-family: "Font Awesome 5 Free";
+ font-weight: 600;
+}
+
+
/* ============================================================================== */
/* CSS style used for jFlot */
/* ============================================================================== */
diff --git a/htdocs/ticket/card.php b/htdocs/ticket/card.php
index f521076e640..fcf1013d982 100644
--- a/htdocs/ticket/card.php
+++ b/htdocs/ticket/card.php
@@ -138,7 +138,7 @@ if (empty($reshook)) {
if ($cancel) {
if (!empty($backtopage)) {
- header("Location: " . $backtopage);
+ header("Location: ".$backtopage);
exit;
}
@@ -227,7 +227,7 @@ if (empty($reshook)) {
$fichinter->fk_project = GETPOST('projectid', 'int');
$fichinter->fk_contrat = $contractid;
$fichinter->author = $user->id;
- $fichinter->modelpdf = 'soleil';
+ $fichinter->model_pdf = 'soleil';
$fichinter->origin = $object->element;
$fichinter->origin_id = $object->id;
@@ -254,10 +254,10 @@ if (empty($reshook)) {
if (!empty($backtopage)) {
$url = $backtopage;
} else {
- $url = 'card.php?track_id=' . $object->track_id;
+ $url = 'card.php?track_id='.$object->track_id;
}
- header("Location: " . $url);
+ header("Location: ".$url);
exit;
} else {
$db->rollback();
@@ -268,53 +268,55 @@ if (empty($reshook)) {
}
}
- if ($action == 'edit' && $user->rights->ticket->write) {
+ if ($action == 'update' && $user->rights->ticket->write && $object->fk_statut < Ticket::STATUS_CLOSED) {
$error = 0;
- if ($object->fetch(GETPOST('id', 'int')) < 0) {
- $error++;
- array_push($object->errors, $langs->trans("ErrorTicketIsNotValid"));
- $_GET["action"] = $_POST["action"] = '';
- }
- }
-
- if (GETPOST('update', 'alpha') && GETPOST('id', 'int') && $user->rights->ticket->write) {
- $error = 0;
-
- $ret = $object->fetch(GETPOST('id', 'int'));
+ $ret = $object->fetch(GETPOST('id', 'int'), GETPOST('ref', 'alpha'), GETPOST('track_id', 'alpha'));
if ($ret < 0) {
$error++;
- array_push($object->errors, $langs->trans("ErrorTicketIsNotValid"));
- $action = '';
- } elseif (!GETPOST("label")) {
- $error++;
- array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")));
- $action = 'edit';
- } elseif (!GETPOST("subject", 'alphanohtml')) {
- $error++;
- array_push($object->errors, $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject")));
- $action = 'edit';
+ array_push($object->errors, $langs->trans('ErrorTicketIsNotValid'));
+ }
+
+ // check fields
+ if (!$error) {
+ if (!GETPOST('subject', 'alpha')) {
+ $error++;
+ array_push($object->errors, $langs->trans('ErrorFieldRequired', $langs->transnoentities('Subject')));
+ }
+ $ret = $extrafields->setOptionalsFromPost(null, $object);
+ if ($ret < 0) $error++;
}
if (!$error) {
$db->begin();
- $object->label = GETPOST("label", 'alphanohtml');
- $object->description = GETPOST("description", 'restricthtml');
+ $object->subject = GETPOST('subject', 'alpha');
+ $object->type_code = GETPOST('type_code', 'alpha');
+ $object->category_code = GETPOST('category_code', 'alpha');
+ $object->severity_code = GETPOST('severity_code', 'alpha');
- //...
$ret = $object->update($user);
- if ($ret <= 0) {
- $error++;
- setEventMessages($object->error, $object->errors, 'errors');
- $action = 'edit';
+ if ($ret <= 0) $error++;
+
+ if ($error) {
+ $db->rollback();
+ } else {
+ $db->commit();
+ }
+ }
+
+ if ($error) {
+ setEventMessages($object->error, $object->errors, 'errors');
+ $action = 'edit';
+ } else {
+ if (!empty($backtopage)) {
+ $url = $backtopage;
+ } else {
+ $url = 'card.php?track_id='.$object->track_id;
}
- if (!$error && $ret > 0) {
- $db->commit();
- } else {
- $db->rollback();
- }
+ header('Location: '.$url);
+ exit();
}
}
@@ -325,7 +327,7 @@ if (empty($reshook)) {
if ($object->markAsRead($user) > 0) {
setEventMessages($langs->trans('TicketMarkedAsRead'), null, 'mesgs');
- header("Location: card.php?track_id=" . $object->track_id . "&action=view");
+ header("Location: card.php?track_id=".$object->track_id."&action=view");
exit;
} else {
setEventMessages($object->error, $object->errors, 'errors');
@@ -376,7 +378,7 @@ if (empty($reshook)) {
setEventMessages($langs->trans('TicketAssigned'), null, 'mesgs');
- header("Location: card.php?track_id=" . $object->track_id . "&action=view");
+ header("Location: card.php?track_id=".$object->track_id."&action=view");
exit;
} else {
array_push($object->errors, $object->error);
@@ -392,10 +394,10 @@ if (empty($reshook)) {
if (!empty($backtopage)) {
$url = $backtopage;
} else {
- $url = 'card.php?action=view&track_id=' . $object->track_id;
+ $url = 'card.php?action=view&track_id='.$object->track_id;
}
- header("Location: " . $url);
+ header("Location: ".$url);
exit;
} else {
setEventMessages($object->error, null, 'errors');
@@ -409,8 +411,8 @@ if (empty($reshook)) {
if ($object->close($user)) {
setEventMessages($langs->trans('TicketMarkedAsClosed'), null, 'mesgs');
- $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha');
- header("Location: " . $url);
+ $url = 'card.php?action=view&track_id='.GETPOST('track_id', 'alpha');
+ header("Location: ".$url);
} else {
$action = '';
setEventMessages($object->error, $object->errors, 'errors');
@@ -425,10 +427,10 @@ if (empty($reshook)) {
// Log action in ticket logs table
$log_action = $langs->trans('TicketLogClosedBy', $_SESSION['email_customer']);
- setEventMessages('' . $langs->trans('TicketMarkedAsClosed') . '
', null, 'mesgs');
+ setEventMessages(''.$langs->trans('TicketMarkedAsClosed').'
', null, 'mesgs');
- $url = 'card.php?action=view_ticket&track_id=' . GETPOST('track_id', 'alpha');
- header("Location: " . $url);
+ $url = 'card.php?action=view_ticket&track_id='.GETPOST('track_id', 'alpha');
+ header("Location: ".$url);
} else {
setEventMessages($object->error, $object->errors, 'errors');
$action = '';
@@ -438,12 +440,12 @@ if (empty($reshook)) {
if ($action == 'confirm_delete_ticket' && GETPOST('confirm', 'alpha') == "yes" && $user->rights->ticket->delete) {
if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) {
if ($object->delete($user) > 0) {
- setEventMessages('' . $langs->trans('TicketDeletedSuccess') . '
', null, 'mesgs');
- Header("Location: " . DOL_URL_ROOT . "/ticket/list.php");
+ setEventMessages(''.$langs->trans('TicketDeletedSuccess').'
', null, 'mesgs');
+ Header("Location: ".DOL_URL_ROOT."/ticket/list.php");
exit;
} else {
$langs->load("errors");
- $mesg = '' . $langs->trans($object->error) . '
';
+ $mesg = ''.$langs->trans($object->error).'
';
$action = '';
}
}
@@ -453,8 +455,8 @@ if (empty($reshook)) {
if ($action == 'set_thirdparty' && $user->rights->societe->creer) {
if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) {
$result = $object->setCustomer(GETPOST('editcustomer', 'int'));
- $url = 'card.php?action=view&track_id=' . GETPOST('track_id', 'alpha');
- header("Location: " . $url);
+ $url = 'card.php?action=view&track_id='.GETPOST('track_id', 'alpha');
+ header("Location: ".$url);
exit();
}
}
@@ -463,8 +465,8 @@ if (empty($reshook)) {
if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) {
$result = $object->setProgression(GETPOST('progress', 'alpha'));
- $url = 'card.php?action=view&track_id=' . $object->track_id;
- header("Location: " . $url);
+ $url = 'card.php?action=view&track_id='.$object->track_id;
+ header("Location: ".$url);
exit();
}
}
@@ -476,12 +478,12 @@ if (empty($reshook)) {
}
if ($action == 'setsubject' && empty($object->subject)) {
- $mesg .= ($mesg ? ' ' : '') . $langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject"));
+ $mesg .= ($mesg ? ' ' : '').$langs->trans("ErrorFieldRequired", $langs->transnoentities("Subject"));
}
if (!$mesg) {
if ($object->update($user) >= 0) {
- header("Location: " . $_SERVER['PHP_SELF'] . "?track_id=" . $object->track_id);
+ header("Location: ".$_SERVER['PHP_SELF']."?track_id=".$object->track_id);
exit;
}
$mesg = $object->error;
@@ -498,8 +500,8 @@ if (empty($reshook)) {
// Log action in ticket logs table
$log_action = $langs->trans('TicketLogReopen');
- $url = 'card.php?action=view&track_id=' . $object->track_id;
- header("Location: " . $url);
+ $url = 'card.php?action=view&track_id='.$object->track_id;
+ header("Location: ".$url);
exit();
}
}
@@ -508,16 +510,16 @@ if (empty($reshook)) {
elseif ($action == 'classin' && $user->rights->ticket->write) {
if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) {
$object->setProject(GETPOST('projectid', 'int'));
- $url = 'card.php?action=view&track_id=' . $object->track_id;
- header("Location: " . $url);
+ $url = 'card.php?action=view&track_id='.$object->track_id;
+ header("Location: ".$url);
exit();
}
} // Categorisation dans contrat
elseif ($action == 'setcontract' && $user->rights->ticket->write) {
if ($object->fetch(GETPOST('id', 'int'), '', GETPOST('track_id', 'alpha')) >= 0) {
$object->setContract(GETPOST('contractid', 'int'));
- $url = 'card.php?action=view&track_id=' . $object->track_id;
- header("Location: " . $url);
+ $url = 'card.php?action=view&track_id='.$object->track_id;
+ header("Location: ".$url);
exit();
}
} elseif ($action == "set_message" && $user->rights->ticket->manage) {
@@ -530,7 +532,7 @@ if (empty($reshook)) {
$object->message = $fieldtomodify;
$ret = $object->update($user);
if ($ret > 0) {
- $log_action = $langs->trans('TicketInitialMessageModified') . " \n";
+ $log_action = $langs->trans('TicketInitialMessageModified')." \n";
// include the Diff class
dol_include_once('/ticket/class/utils_diff.class.php');
// output the result of comparing two files as plain text
@@ -551,8 +553,8 @@ if (empty($reshook)) {
// Log action in ticket logs table
$log_action = $langs->trans('TicketLogStatusChanged', $langs->transnoentities($object->statuts_short[$old_status]), $langs->transnoentities($object->statuts_short[$new_status]));
- $url = 'card.php?action=view&track_id=' . $object->track_id;
- header("Location: " . $url);
+ $url = 'card.php?action=view&track_id='.$object->track_id;
+ header("Location: ".$url);
exit();
}
}
@@ -597,19 +599,19 @@ if (empty($reshook)) {
$permissiondellink = $user->rights->ticket->write;
- include DOL_DOCUMENT_ROOT . '/core/actions_dellink.inc.php'; // Must be include, not include_once
+ include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
// Actions to build doc
$upload_dir = $conf->ticket->dir_output;
$permissiontoadd = $user->rights->ticket->write;
- include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php';
+ include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
// Actions to send emails
$triggersendname = 'TICKET_SENTBYMAIL';
$paramname = 'id';
$autocopy = 'MAIN_MAIL_AUTOCOPY_TICKET_TO'; // used to know the automatic BCC to add
- $trackid = 'tic' . $object->id;
- include DOL_DOCUMENT_ROOT . '/core/actions_sendmails.inc.php';
+ $trackid = 'tic'.$object->id;
+ include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
// Set $action to correct value for the case we used presend action to add a message
if (GETPOSTISSET('actionbis') && $action == 'presend') $action = 'presend_addmessage';
@@ -650,9 +652,63 @@ if ($action == 'create' || $action == 'presend')
}
$formticket->showForm(1, 'create');
-}
+} elseif ($action == 'edit' && $user->rights->ticket->write && $object->fk_statut < Ticket::STATUS_CLOSED) {
+ $formticket = new FormTicket($db);
-if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'dellink' || $action == 'presend' || $action == 'presend_addmessage' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen'
+ $head = ticket_prepare_head($object);
+
+ print '';
+}
+elseif (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'dellink' || $action == 'presend' || $action == 'presend_addmessage' || $action == 'close' || $action == 'delete' || $action == 'editcustomer' || $action == 'progression' || $action == 'reopen'
|| $action == 'editsubject' || $action == 'edit_extras' || $action == 'update_extras' || $action == 'edit_extrafields' || $action == 'set_extrafields' || $action == 'classify' || $action == 'sel_contract' || $action == 'edit_message_init' || $action == 'set_status' || $action == 'dellink')
{
if ($res > 0)
@@ -1027,15 +1083,15 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd
} else {
// Type
print ' '.$langs->trans("Type").' ';
- print $langs->getLabelFromKey($db, 'TicketTypeShort' . $object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code);
+ print $langs->getLabelFromKey($db, 'TicketTypeShort'.$object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code);
print ' ';
// Group
print '
'.$langs->trans("TicketCategory").' ';
- print $langs->getLabelFromKey($db, 'TicketCategoryShort' . $object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code);
+ print $langs->getLabelFromKey($db, 'TicketCategoryShort'.$object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code);
print ' ';
// Severity
print '
'.$langs->trans("TicketSeverity").' ';
- print $langs->getLabelFromKey($db, 'TicketSeverityShort' . $object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code);
+ print $langs->getLabelFromKey($db, 'TicketSeverityShort'.$object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code);
print ' ';
}
print '
'; // End table actions
@@ -1193,6 +1249,10 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd
print '';
}
+ if ($user->rights->ticket->write && $object->fk_statut < Ticket::STATUS_CLOSED) {
+ print '';
+ }
+
// Close ticket if statut is read
if ($object->fk_statut > 0 && $object->fk_statut < Ticket::STATUS_CLOSED && $user->rights->ticket->write) {
print '';
@@ -1299,7 +1359,7 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd
}
// Show messages on card (Note: this is a duplicate of the view Events/Agenda but on the main tab)
- if (! empty($conf->global->TICKET_SHOW_MESSAGES_ON_CARD)) {
+ if (!empty($conf->global->TICKET_SHOW_MESSAGES_ON_CARD)) {
$param = '&id='.$object->id;
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage;
if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit;
@@ -1308,17 +1368,17 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd
$morehtmlright = '';
- $messagingUrl = DOL_URL_ROOT . '/ticket/agenda.php?track_id=' . $object->track_id;
+ $messagingUrl = DOL_URL_ROOT.'/ticket/agenda.php?track_id='.$object->track_id;
$morehtmlright .= dolGetButtonTitle($langs->trans('MessageListViewType'), '', 'fal fa-list-alt imgforviewmode', $messagingUrl, '', 1);
// Show link to add a message (if read and not closed)
$btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage" && $action != "add_message";
- $url = 'card.php?track_id=' . $object->track_id . '&action=presend_addmessage&mode=init';
+ $url = 'card.php?track_id='.$object->track_id.'&action=presend_addmessage&mode=init';
$morehtmlright .= dolGetButtonTitle($langs->trans('TicketAddMessage'), '', 'fal fa-comment-dots', $url, 'add-new-ticket-title-button', $btnstatus);
// Show link to add event (if read and not closed)
- $btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage" && $action != "add_message";;
- $url = dol_buildpath('/comm/action/card.php', 1) . '?action=create&datep=' . date('YmdHi') . '&origin=ticket&originid=' . $object->id . '&projectid=' . $object->fk_project . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?track_id=' . $object->track_id);
+ $btnstatus = $object->fk_statut < Ticket::STATUS_CLOSED && $action != "presend" && $action != "presend_addmessage" && $action != "add_message"; ;
+ $url = dol_buildpath('/comm/action/card.php', 1).'?action=create&datep='.date('YmdHi').'&origin=ticket&originid='.$object->id.'&projectid='.$object->fk_project.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?track_id='.$object->track_id);
$morehtmlright .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fal fa-plus-circle', $url, 'add-new-ticket-even-button', $btnstatus);
print_barre_liste($langs->trans("ActionsOnTicket"), 0, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', 0, -1, '', 0, $morehtmlright, '', 0, 1, 1);
@@ -1352,7 +1412,7 @@ if (empty($action) || $action == 'view' || $action == 'addlink' || $action == 'd
$morehtmlcenter .= dolGetButtonTitle($langs->trans('FullList'), '', 'fa fa-list-alt imgforviewmode', DOL_URL_ROOT.'/ticket/agenda.php?id='.$object->id);
// List of actions on element
- include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
+ include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
$formactions = new FormActions($db);
$somethingshown = $formactions->showactions($object, 'ticket', $socid, 1, 'listactions', $MAXEVENT, '', $morehtmlcenter);
diff --git a/htdocs/ticket/class/ticket.class.php b/htdocs/ticket/class/ticket.class.php
index 6b3b1ea8fd4..6096e1d2d59 100644
--- a/htdocs/ticket/class/ticket.class.php
+++ b/htdocs/ticket/class/ticket.class.php
@@ -1268,9 +1268,8 @@ class Ticket extends CommonObject
if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
$result = '';
- $companylink = '';
- $label = ''.$langs->trans("Ticket").' ';
+ $label = img_picto('', $this->picto).' '.$langs->trans("Ticket").' ';
$label .= ' ';
$label .= ''.$langs->trans('Ref').': '.$this->ref.' ';
$label .= ''.$langs->trans('TicketTrackId').': '.$this->track_id.' ';
@@ -1701,7 +1700,7 @@ class Ticket extends CommonObject
$error = 0;
// Valid and close fichinter linked
- if (!empty($conf->ficheinter->enabled) && ! empty($conf->global->WORKFLOW_TICKET_CLOSE_INTERVENTION)) {
+ if (!empty($conf->ficheinter->enabled) && !empty($conf->global->WORKFLOW_TICKET_CLOSE_INTERVENTION)) {
dol_syslog("We have closed the ticket, so we close all linked interventions");
$this->fetchObjectLinked($this->id, $this->element, null, 'fichinter');
if ($this->linkedObjectsIds)
@@ -2549,23 +2548,23 @@ class Ticket extends CommonObject
// Customer company infos
$message .= ' ';
$message .= "==============================================";
- $message .= !empty($object->thirdparty->name) ? ' ' . $langs->trans('Thirdparty') . " : " . $object->thirdparty->name : '';
- $message .= !empty($object->thirdparty->town) ? ' ' . $langs->trans('Town') . " : " . $object->thirdparty->town : '';
- $message .= !empty($object->thirdparty->phone) ? ' ' . $langs->trans('Phone') . " : " . $object->thirdparty->phone : '';
+ $message .= !empty($object->thirdparty->name) ? ' '.$langs->trans('Thirdparty')." : ".$object->thirdparty->name : '';
+ $message .= !empty($object->thirdparty->town) ? ' '.$langs->trans('Town')." : ".$object->thirdparty->town : '';
+ $message .= !empty($object->thirdparty->phone) ? ' '.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
// Email send to
$message .= ' ';
if (!empty($assigned_user_dont_have_email)) {
- $message .= ' ' . $langs->trans('NoEMail') . ' : ' . $assigned_user_dont_have_email;
+ $message .= ' '.$langs->trans('NoEMail').' : '.$assigned_user_dont_have_email;
}
foreach ($sendto as $val) {
- $message .= ' ' . $langs->trans('TicketNotificationRecipient') . ' : ' . $val;
+ $message .= ' '.$langs->trans('TicketNotificationRecipient').' : '.$val;
}
// URL ticket
- $url_internal_ticket = dol_buildpath('/ticket/card.php', 2) . '?track_id=' . $object->track_id;
+ $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
$message .= ' ';
- $message .= $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . $object->track_id . ' ';
+ $message .= $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : '.$object->track_id.' ';
$this->sendTicketMessageByEmail($subject, $message, '', $sendto, $listofpaths, $listofmimes, $listofnames);
}
@@ -2602,9 +2601,9 @@ class Ticket extends CommonObject
// Coordonnées client
$message .= ' ';
$message .= "============================================== ";
- $message .= !empty($object->thirdparty->name) ? $langs->trans('Thirdparty') . " : " . $object->thirdparty->name : '';
- $message .= !empty($object->thirdparty->town) ? ' ' . $langs->trans('Town') . " : " . $object->thirdparty->town : '';
- $message .= !empty($object->thirdparty->phone) ? ' ' . $langs->trans('Phone') . " : " . $object->thirdparty->phone : '';
+ $message .= !empty($object->thirdparty->name) ? $langs->trans('Thirdparty')." : ".$object->thirdparty->name : '';
+ $message .= !empty($object->thirdparty->town) ? ' '.$langs->trans('Town')." : ".$object->thirdparty->town : '';
+ $message .= !empty($object->thirdparty->phone) ? ' '.$langs->trans('Phone')." : ".$object->thirdparty->phone : '';
// Build array to display recipient list
foreach ($internal_contacts as $key => $info_sendto) {
@@ -2614,19 +2613,19 @@ class Ticket extends CommonObject
}
if ($info_sendto['email'] != '') {
- if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">";
+ if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
//Contact type
- $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')';
- $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . ' ' : '');
+ $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')';
+ $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient.' ' : '');
}
}
$message .= ' ';
// URL ticket
- $url_internal_ticket = dol_buildpath('/ticket/card.php', 2) . '?track_id=' . $object->track_id;
+ $url_internal_ticket = dol_buildpath('/ticket/card.php', 2).'?track_id='.$object->track_id;
// altairis: make html link on url
- $message .= ' ' . $langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal') . ' : ' . $object->track_id . ' ';
+ $message .= ' '.$langs->trans('TicketNotificationEmailBodyInfosTrackUrlinternal').' : '.$object->track_id.' ';
// Add global email address recipient
if ($conf->global->TICKET_NOTIFICATION_ALSO_MAIN_ADDRESS && !in_array($conf->global->TICKET_NOTIFICATION_EMAIL_TO, $sendto)) {
@@ -2688,23 +2687,23 @@ class Ticket extends CommonObject
}
if ($info_sendto['email'] != '' && $info_sendto['email'] != $object->origin_email) {
- if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname'] . " " . $info_sendto['lastname']) . " <" . $info_sendto['email'] . ">";
+ if (!empty($info_sendto['email'])) $sendto[] = trim($info_sendto['firstname']." ".$info_sendto['lastname'])." <".$info_sendto['email'].">";
- $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1') . ' (' . strtolower($info_sendto['libelle']) . ')';
- $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient') . ' : ' . $recipient . ' ' : '');
+ $recipient = dolGetFirstLastname($info_sendto['firstname'], $info_sendto['lastname'], '-1').' ('.strtolower($info_sendto['libelle']).')';
+ $message .= (!empty($recipient) ? $langs->trans('TicketNotificationRecipient').' : '.$recipient.' ' : '');
}
}
// If public interface is not enable, use link to internal page into mail
$url_public_ticket = (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE) ?
- (!empty($conf->global->TICKET_URL_PUBLIC_INTERFACE) ? $conf->global->TICKET_URL_PUBLIC_INTERFACE . '/view.php' : dol_buildpath('/public/ticket/view.php', 2)) : dol_buildpath('/ticket/card.php', 2)) . '?track_id=' . $object->track_id;
- $message .= ' ' . $langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer') . ' : ' . $object->track_id . ' ';
+ (!empty($conf->global->TICKET_URL_PUBLIC_INTERFACE) ? $conf->global->TICKET_URL_PUBLIC_INTERFACE.'/view.php' : dol_buildpath('/public/ticket/view.php', 2)) : dol_buildpath('/ticket/card.php', 2)).'?track_id='.$object->track_id;
+ $message .= ' '.$langs->trans('TicketNewEmailBodyInfosTrackUrlCustomer').' : '.$object->track_id.' ';
// Build final message
- $message = $message_intro . ' ' . $message;
+ $message = $message_intro.' '.$message;
// Add signature
- $message .= ' ' . $message_signature;
+ $message .= ' '.$message_signature;
if (!empty($object->origin_email)) {
$sendto[] = $object->origin_email;
diff --git a/htdocs/ticket/list.php b/htdocs/ticket/list.php
index 184216ea47e..c4c1cbadcc9 100644
--- a/htdocs/ticket/list.php
+++ b/htdocs/ticket/list.php
@@ -100,9 +100,9 @@ foreach ($object->fields as $key => $val)
{
if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
}
-$fieldstosearchall['s.name_alias']="AliasNameShort";
-$fieldstosearchall['s.zip']="Zip";
-$fieldstosearchall['s.town']="Town";
+$fieldstosearchall['s.name_alias'] = "AliasNameShort";
+$fieldstosearchall['s.zip'] = "Zip";
+$fieldstosearchall['s.town'] = "Town";
// Definition of fields for list
$arrayfields = array();
@@ -755,13 +755,13 @@ while ($i < min($num, $limit))
print '>';
if ($key == 'fk_statut') print $object->getLibStatut(5);
elseif ($key == 'type_code') {
- $s = $langs->getLabelFromKey($db, 'TicketTypeShort' . $object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code);
+ $s = $langs->getLabelFromKey($db, 'TicketTypeShort'.$object->type_code, 'c_ticket_type', 'code', 'label', $object->type_code);
print '';
print $s;
print ' ';
}
- elseif ($key == 'category_code') print $langs->getLabelFromKey($db, 'TicketCategoryShort' . $object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code);
- elseif ($key == 'severity_code') print $langs->getLabelFromKey($db, 'TicketSeverityShort' . $object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code);
+ elseif ($key == 'category_code') print $langs->getLabelFromKey($db, 'TicketCategoryShort'.$object->category_code, 'c_ticket_category', 'code', 'label', $object->category_code);
+ elseif ($key == 'severity_code') print $langs->getLabelFromKey($db, 'TicketSeverityShort'.$object->severity_code, 'c_ticket_severity', 'code', 'label', $object->severity_code);
elseif ($key == 'tms') print dol_print_date($db->jdate($obj->$key), 'dayhour', 'tzuser');
elseif ($key == 'fk_user_create') {
if ($object->fk_user_create > 0) {
diff --git a/htdocs/user/card.php b/htdocs/user/card.php
index 9108fce983f..94f801fed6d 100644
--- a/htdocs/user/card.php
+++ b/htdocs/user/card.php
@@ -2719,7 +2719,7 @@ if ($action == 'create' || $action == 'adduserldap')
$genallowed = $user->rights->user->user->lire;
$delallowed = $user->rights->user->user->creer;
- print $formfile->showdocuments('user', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
+ print $formfile->showdocuments('user', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
$somethingshown = $formfile->numoffiles;
// Show links to link elements
diff --git a/htdocs/user/class/api_users.class.php b/htdocs/user/class/api_users.class.php
index c878d7dd376..cab2b56f5d9 100644
--- a/htdocs/user/class/api_users.class.php
+++ b/htdocs/user/class/api_users.class.php
@@ -627,7 +627,7 @@ class Users extends DolibarrApi
unset($object->openid);
unset($object->lines);
- unset($object->modelpdf);
+ unset($object->model_pdf);
unset($object->skype);
unset($object->twitter);
unset($object->facebook);
diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php
index f6a3862d0bb..3672462fe0f 100644
--- a/htdocs/user/class/user.class.php
+++ b/htdocs/user/class/user.class.php
@@ -2244,7 +2244,7 @@ class User extends CommonObject
// Info Login
$label .= '';
- $label .= '
'.$langs->trans("User").' ';
+ $label .= img_picto('', $this->picto).'
'.$langs->trans("User").' ';
$label .= '
'.$langs->trans('Name').': '.$this->getFullName($langs, '');
if (!empty($this->login)) $label .= '
'.$langs->trans('Login').': '.$this->login;
if (!empty($this->job)) $label .= '
'.$langs->trans("Job").': '.$this->job;
@@ -3233,9 +3233,9 @@ class User extends CommonObject
}
return $num;
} else {
- $this->errors[] = $this->db->lasterror();
- return -1;
- }
+ $this->errors[] = $this->db->lasterror();
+ return -1;
+ }
}
/**
diff --git a/htdocs/user/group/card.php b/htdocs/user/group/card.php
index 102fc61d5c1..462ba32e7ba 100644
--- a/htdocs/user/group/card.php
+++ b/htdocs/user/group/card.php
@@ -493,7 +493,7 @@ else {
$genallowed = $user->rights->user->user->creer;
$delallowed = $user->rights->user->user->supprimer;
- $somethingshown = $formfile->showdocuments('usergroup', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
+ $somethingshown = $formfile->showdocuments('usergroup', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
// Show links to link elements
$linktoelem = $form->showLinkToObjectBlock($object, null, null);
diff --git a/htdocs/user/group/perms.php b/htdocs/user/group/perms.php
index d8d6c74f00b..b22dafce758 100644
--- a/htdocs/user/group/perms.php
+++ b/htdocs/user/group/perms.php
@@ -303,7 +303,7 @@ if ($object->id > 0)
print '
';
// Module id
- if ($user->admin) print '
'. $objMod->numero.' ';
+ if ($user->admin) print '
'.$objMod->numero.' ';
print '';
}
diff --git a/htdocs/user/perms.php b/htdocs/user/perms.php
index 4b99cfb7e18..f87785da31f 100644
--- a/htdocs/user/perms.php
+++ b/htdocs/user/perms.php
@@ -365,7 +365,7 @@ if ($result)
print '
';
// Module Id
- if ($user->admin) print '
'. $objMod->numero.' ';
+ if ($user->admin) print '
'.$objMod->numero.' ';
print ''."\n";
}
diff --git a/htdocs/variants/class/ProductCombination.class.php b/htdocs/variants/class/ProductCombination.class.php
index 52884afc875..b4dac8475c0 100644
--- a/htdocs/variants/class/ProductCombination.class.php
+++ b/htdocs/variants/class/ProductCombination.class.php
@@ -165,11 +165,11 @@ class ProductCombination
/**
* for auto retrocompatibility with last behavior
*/
- if ($fk_price_level>0){
+ if ($fk_price_level > 0) {
$combination_price_levels[$fk_price_level] = ProductCombinationLevel::createFromParent($this->db, $this, $fk_price_level);
}
else {
- for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++){
+ for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
$combination_price_levels[$i] = ProductCombinationLevel::createFromParent($this->db, $this, $i);
}
}
@@ -264,7 +264,7 @@ class ProductCombination
$this->fetchCombinationPriceLevels();
}
- return $this->fk_product_parent;
+ return (int) $this->fk_product_parent;
}
/**
@@ -783,16 +783,16 @@ class ProductCombination
$newcomb->variation_weight = $weight_impact;
// Init price level
- if ($conf->global->PRODUIT_MULTIPRICES){
- for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++){
+ if ($conf->global->PRODUIT_MULTIPRICES) {
+ for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
$productCombinationLevel = new ProductCombinationLevel($this->db);
$productCombinationLevel->fk_product_attribute_combination = $newcomb->id;
$productCombinationLevel->fk_price_level = $i;
$productCombinationLevel->variation_price = $price_impact[$i];
- if (is_array($price_var_percent)){
+ if (is_array($price_var_percent)) {
$productCombinationLevel->variation_price_percentage = (empty($price_var_percent[$i]) ? false : $price_var_percent[$i]);
- }else {
+ } else {
$productCombinationLevel->variation_price_percentage = $price_var_percent;
}
@@ -1223,7 +1223,7 @@ class ProductCombinationLevel
$productCombinationLevel->fk_price_level = $fkPriceLevel;
$productCombinationLevel->fk_product_attribute_combination = $productCombination->id;
$productCombinationLevel->variation_price = $productCombination->variation_price;
- $productCombinationLevel->variation_price_percentage = $productCombination->variation_price_percentage;
+ $productCombinationLevel->variation_price_percentage = (bool) $productCombination->variation_price_percentage;
return $productCombinationLevel;
}
diff --git a/htdocs/webservices/server_invoice.php b/htdocs/webservices/server_invoice.php
index 8b15ade0a6a..194a2331b2c 100644
--- a/htdocs/webservices/server_invoice.php
+++ b/htdocs/webservices/server_invoice.php
@@ -778,7 +778,7 @@ function updateInvoice($authentication, $invoice)
{
// Define output language
$outputlangs = $langs;
- $object->generateDocument($object->modelpdf, $outputlangs);
+ $object->generateDocument($object->model_pdf, $outputlangs);
}
}
if ($invoice['status'] == Facture::STATUS_CLOSED)
diff --git a/htdocs/webservices/server_order.php b/htdocs/webservices/server_order.php
index 7018f5fb5c8..98c9be86cfc 100644
--- a/htdocs/webservices/server_order.php
+++ b/htdocs/webservices/server_order.php
@@ -842,7 +842,7 @@ function validOrder($authentication, $id = '', $id_warehouse = 0)
{
// Define output language
$outputlangs = $langs;
- $order->generateDocument($order->modelpdf, $outputlangs);
+ $order->generateDocument($order->model_pdf, $outputlangs);
}
else {
$db->rollback();
@@ -929,7 +929,7 @@ function updateOrder($authentication, $order)
{
// Define output language
$outputlangs = $langs;
- $object->generateDocument($order->modelpdf, $outputlangs);
+ $object->generateDocument($order->model_pdf, $outputlangs);
}
}
if ($order['status'] == 0) $result = $object->set_reopen($fuser);
diff --git a/htdocs/website/websiteaccount_card.php b/htdocs/website/websiteaccount_card.php
index 8494cfb9ae7..d2b592477fd 100644
--- a/htdocs/website/websiteaccount_card.php
+++ b/htdocs/website/websiteaccount_card.php
@@ -348,27 +348,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '
';
print '
'; // ancre
- // Documents
- /*$objref = dol_sanitizeFileName($object->ref);
- $relativepath = $objref . '/' . $objref . '.pdf';
- $filedir = $conf->website->dir_output . '/' . $objref;
- $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
- $genallowed = $user->rights->website->read; // If you can read, you can build the PDF to read content
- $delallowed = $user->rights->website->create; // If you can create/edit, you can remove a file on card
- print $formfile->showdocuments('website', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
- */
-
- // Show links to link elements
- /*$linktoelem = $form->showLinkToObjectBlock($object, null, array('websiteaccount'));
- $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
- */
-
print '
';
+ /*
$MAXEVENT = 10;
// List of actions on element
- /*
include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
$formactions = new FormActions($db);
$somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT);
diff --git a/htdocs/zapier/hook_card.php b/htdocs/zapier/hook_card.php
index 6c098999d58..9d33a9801b0 100644
--- a/htdocs/zapier/hook_card.php
+++ b/htdocs/zapier/hook_card.php
@@ -371,16 +371,6 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
print '
';
print '
'; // ancre
- // Documents
- /*$objref = dol_sanitizeFileName($object->ref);
- $relativepath = $comref . '/' . $comref . '.pdf';
- $filedir = $conf->mymodule->dir_output . '/' . $objref;
- $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
- $genallowed = $user->rights->mymodule->read; // If you can read, you can build the PDF to read content
- $delallowed = $user->rights->mymodule->create; // If you can create/edit, you can remove a file on card
- print $formfile->showdocuments('mymodule', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang);
- */
-
// Show links to link elements
$linktoelem = $form->showLinkToObjectBlock($object, null, array('myobject'));
$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
diff --git a/test/phpunit/DateLibTest.php b/test/phpunit/DateLibTest.php
index 062bdb6dd11..2d5598f49b3 100644
--- a/test/phpunit/DateLibTest.php
+++ b/test/phpunit/DateLibTest.php
@@ -242,29 +242,6 @@ class DateLibTest extends PHPUnit\Framework\TestCase
$result=num_public_holiday($date1, $date2, 'XX', 1);
print __METHOD__." result=".$result."\n";
$this->assertEquals(2, $result, 'NumPublicHoliday for XX'); // 1 opened day, 2 closed days (even if country unknown)
-
-
-
- // Add more holiday with constant HOLIDAY_MORE_PUBLIC_HOLIDAYS
- $conf->global->HOLIDAY_MORE_PUBLIC_HOLIDAYS='12-13,2019-12-14';
-
- $date1=dol_mktime(0, 0, 0, 12, 13, 2018);
- $date2=dol_mktime(0, 0, 0, 12, 13, 2018);
- $result=num_public_holiday($date1, $date2, 'YY', 1);
- print __METHOD__." result=".$result."\n";
- $this->assertEquals(1, $result, 'NumPublicHoliday for YY the 2018-12-13'); // 0 opened day, 1 closed days (even if country unknown)
-
- $date1=dol_mktime(0, 0, 0, 12, 14, 2018);
- $date2=dol_mktime(0, 0, 0, 12, 14, 2018);
- $result=num_public_holiday($date1, $date2, 'YY', 1);
- print __METHOD__." result=".$result."\n";
- $this->assertEquals(0, $result, 'NumPublicHoliday for YY the 2018-12-14'); // 1 opened day, 0 closed days (even if country unknown)
-
- $date1=dol_mktime(0, 0, 0, 12, 14, 2019);
- $date2=dol_mktime(0, 0, 0, 12, 14, 2019);
- $result=num_public_holiday($date1, $date2, 'YY', 1);
- print __METHOD__." result=".$result."\n";
- $this->assertEquals(1, $result, 'NumPublicHoliday for YY the 2019-12-14'); // 0 opened day, 1 closed days (even if country unknown)
}
/**
diff --git a/test/phpunit/FilesLibTest.php b/test/phpunit/FilesLibTest.php
index 9d476953381..ae8ea17efb6 100644
--- a/test/phpunit/FilesLibTest.php
+++ b/test/phpunit/FilesLibTest.php
@@ -1,4 +1,6 @@
* Copyright (C) 2012 Regis Houssin
*
@@ -130,7 +132,7 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
/**
* testDolBasename
*
- * @return int
+ * @return void
*/
public function testDolBasename()
{
@@ -239,7 +241,7 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
/**
* testDolMimeType
*
- * @return string
+ * @return void
*/
public function testDolMimeType()
{
@@ -285,7 +287,7 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
/**
* testDolDeleteDir
*
- * @return int
+ * @return void
*/
public function testDolDeleteDir()
{
@@ -323,10 +325,7 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
/**
* testDolCopyMoveDelete
*
- * @return int
- *
- * @depends testDolDeleteDir
- * The depends says test is run only if previous is ok
+ * @return void
*/
public function testDolCopyMoveDelete()
{
@@ -362,7 +361,7 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
$this->assertTrue($result, 'move with default mask');
// To test a move that should work with forced mask
- $result=dol_move($conf->admin->dir_temp.'/file2.csv', $conf->admin->dir_temp.'/file3.csv', '0754', 1); // file shoutld be rwxr-wr--
+ $result=dol_move($conf->admin->dir_temp.'/file2.csv', $conf->admin->dir_temp.'/file3.csv', '0754', 1); // file should be rwxr-wr--
print __METHOD__." result=".$result."\n";
$this->assertTrue($result, 'move with forced mask');
@@ -395,10 +394,7 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
/**
* testDolCompressUnCompress
*
- * @return string
- *
- * @depends testDolCopyMoveDelete
- * The depends says test is run only if previous is ok
+ * @return void
*/
public function testDolCompressUnCompress()
{
@@ -419,8 +415,13 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
$errorstring = '';
+ dol_mkdir($conf->admin->dir_temp);
+ $conf->global->MAIN_ENABLE_LOG_TO_HTML=1; $conf->syslog->enabled=1; $_REQUEST['logtohtml']=1;
+ $conf->logbuffer=array();
+
$result=dol_compress_file($filein, $fileout, $format, $errorstring);
print __METHOD__." result=".$result."\n";
+ print join(', ', $conf->logbuffer);
$this->assertGreaterThanOrEqual(1, $result, "Pb with dol_compress_file on ".$filein." into ".$fileout." : ".$errorstring);
$result=dol_uncompress($fileout, $dirout);
@@ -431,7 +432,7 @@ class FilesLibTest extends PHPUnit\Framework\TestCase
/**
* testDolDirList
*
- * @return string
+ * @return void
*
* @depends testDolCompressUnCompress
* The depends says test is run only if previous is ok