diff --git a/.travis.yml b/.travis.yml index d66915eb44b..8d5a54b0548 100644 --- a/.travis.yml +++ b/.travis.yml @@ -79,7 +79,7 @@ matrix: notifications: email: on_success: never # [always|never|change] default: change - on_failure: change # [always|never|change] default: always + on_failure: never # [always|never|change] default: always irc: channels: - "chat.freenode.net#dolibarr" @@ -313,13 +313,13 @@ script: php upgrade2.php 3.9.0 4.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade390400-2.log php step5.php 3.9.0 4.0.0 > $TRAVIS_BUILD_DIR/upgrade390400-3.log php upgrade.php 4.0.0 5.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade400500.log - php upgrade2.php 4.0.0 5.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade400500-2.log + php upgrade2.php 4.0.0 5.0.0 > $TRAVIS_BUILD_DIR/upgrade400500-2.log php step5.php 4.0.0 5.0.0 > $TRAVIS_BUILD_DIR/upgrade400500-3.log php upgrade.php 5.0.0 6.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade500600.log - php upgrade2.php 5.0.0 6.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade500600-2.log + php upgrade2.php 5.0.0 6.0.0 > $TRAVIS_BUILD_DIR/upgrade500600-2.log php step5.php 5.0.0 6.0.0 > $TRAVIS_BUILD_DIR/upgrade500600-3.log php upgrade.php 6.0.0 7.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade600700.log - php upgrade2.php 6.0.0 7.0.0 MAIN_MODULE_API,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade600700-2.log + php upgrade2.php 6.0.0 7.0.0 MAIN_MODULE_WEBSITE,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade600700-2.log php step5.php 6.0.0 7.0.0 > $TRAVIS_BUILD_DIR/upgrade600700-3.log cd - set +e diff --git a/COPYRIGHT b/COPYRIGHT index 427784a1552..bd3565c3bd1 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -34,12 +34,11 @@ Swift Mailer 5.4.2-DEV MIT license Yes Stripe 4.7.0 MIT licence Yes Library for Stripe module JS libraries: -jQuery 1.11.3 MIT License Yes JS library -jQuery UI 1.11.4 GPL and MIT License Yes JS library plugin UI -jQuery select2 3.5.2 GPL and Apache License Yes JS library plugin for sexier multiselect +jQuery 3.1.1 MIT License Yes JS library +jQuery UI 1.12.1 GPL and MIT License Yes JS library plugin UI +jQuery select2 4.0.5 GPL and Apache License Yes JS library plugin for sexier multiselect jQuery blockUI 2.70.0 GPL and MIT License Yes JS library plugin blockUI (to use ajax popups) jQuery Colorpicker 1.1 MIT License Yes JS library for color picker for a defined list of colors -jQuery FileUpload 5.0.3 GPL and MIT License Yes JS library to upload files jQuery Flot 0.8.3 MIT License Yes JS library to build graph jQuery JCrop 0.9.8 GPL and MIT License Yes JS library plugin Crop (to crop images) jQuery Jeditable 1.7.1 GPL and MIT License Yes JS library plugin jeditable (to edit in place) @@ -49,8 +48,7 @@ jQuery jqueryFileTree 1.0.1 GPL and MIT License Yes jQuery jquerytreeview 1.4.1 MIT License Yes JS library for filetree jQuery TableDnD 0.6 GPL and MIT License Yes JS library plugin TableDnD (to reorder table rows) jQuery Timepicker 1.1.0 GPL and MIT License Yes JS library Timepicker addon for Datepicker -jQuery Tiptip 1.3 GPL and MIT License Yes JS library for tooltips -jsGanttImproved 1.7.5.2 BSD License Yes JS library (to build Gantt reports) +jsGanttImproved 1.7.5.4 BSD License Yes JS library (to build Gantt reports) JsTimezoneDetect 1.0.6 MIT License Yes JS library to detect user timezone SwaggerUI 2.0.24 GPL-2+ Yes JS library to offer the REST API explorer Ace 1.2.8 BSD Yes JS library to get code syntaxique coloration in a textarea. diff --git a/ChangeLog b/ChangeLog index 9b5eef7aca5..aa600bdacef 100644 --- a/ChangeLog +++ b/ChangeLog @@ -5,6 +5,7 @@ English Dolibarr ChangeLog ***** ChangeLog for 7.0.0 compared to 6.0.* ***** +For users: For developers: NEW: Add hook addAdminLdapOptions and doAction in ldap admin page @@ -23,8 +24,37 @@ Following changes may create regressions for some external modules, but were nec follow page naming conventions (so default filter/sort order features can also work). * The trigger ORDER_SUPPLIER_STATUS_ONPROCESS was renamed into ORDER_SUPPLIER_STATUS_ORDERED * The trigger ORDER_SUPPLIER_STATUS_RECEIVED_ALL was renamed into ORDER_SUPPLIER_STATUS_RECEIVED_COMPLETELY +* The parameter note into method cloture() is added at end of private note (previously in v6, it replaced) +* The parameter $user is now mandatory for method createFromOrder and createFromPropal. +* Remove js library fileupload that was not used by core code. +***** ChangeLog for 6.0.3 compared to 6.0.2 ***** +FIX: #7211 Update qty dispatched on qty change +FIX: #7458 +FIX: #7593 +FIX: #7616 +FIX: #7619 +FIX: #7626 +FIX: #7648 +FIX: #7675 +FIX: Agenda events are not exported in the ICAL, VCAL if begin exactly with the same $datestart +FIX: API to get object does not return data of linked objects +FIX: Bad localtax apply +FIX: Bad ressource list in popup in gantt view +FIX: bankentries search conciliated if val 0 +FIX: hook formObjectOptions() must use $expe and not $object +FIX: make of link to other object during creation +FIX: Missing function getLinesArray +FIX: old batch not shown in multi shipping +FIX: paid supplier invoices are shown as abandoned +FIX: selection of thirdparty was lost on stats page of invoices +FIX: sql syntax error because of old field accountancy_journal +FIX: Stats on invoices show nothing +FIX: substitution in ODT of thirdparties documents +FIX: wrong key in selectarray +FIX: wrong personnal project time spent + ***** ChangeLog for 6.0.2 compared to 6.0.1 ***** FIX: #7148 FIX: #7288 diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index e0fa89d924d..2802e55c702 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -571,6 +571,7 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/mobiledetect/mobiledetectlib/.gitmodules`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/lib/Mail`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/samples`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/parsedown/LICENSE.txt`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/php-iban/docs`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpoffice/phpexcel/.gitattributes`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpoffice/phpexcel/Classes/license.md`; @@ -579,6 +580,7 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpoffice/phpexcel/Examples`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpoffice/phpexcel/unitTests`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpoffice/phpexcel/license.md`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/stripe/LICENSE`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/dejavu-fonts-ttf-*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/freefont-*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/ae_fonts_*`; @@ -590,6 +592,8 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/fonts/utils`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/tools`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/LICENSE.TXT`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/theme/common/octicons/LICENSE`; + print "Remove subdir of custom dir\n"; print "find $BUILDROOT/$PROJECT/htdocs/custom/* -type d -exec rm -fr {} \\;\n"; diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 3b9ef4cc447..945e7d36ca7 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -82,8 +82,14 @@ with // LDR To open in same window //var OpenWindow=window.open(pRef, "newwin", "height="+vHeight+",width="+vWidth); window.location.href=pRef -* Replace hard coded string with i18n["String"]; +* Replace +vTmpDiv=this.newNode(vTmpCell, 'div', null, null, vTaskList[i].getResource()); +with +var vTmpNode=this.newNode(vTmpCell, 'div', null, ''); +vTmpNode=this.newNode(vTmpNode, 'a', null, '', vLangs[vLang]['moreinfo']); +vTmpNode.setAttribute('href',vTaskList[i].getLink()); + JCROP: ------ diff --git a/dev/initdata/purge-data.php b/dev/initdata/purge-data.php index f89a3ba2698..f992dcb2dc6 100755 --- a/dev/initdata/purge-data.php +++ b/dev/initdata/purge-data.php @@ -78,15 +78,17 @@ $sqls=array( 'DELETE FROM '.MAIN_DB_PREFIX.'propaldet', 'DELETE FROM '.MAIN_DB_PREFIX.'propal', ), - 'supplier_order'=>array( + 'supplier_proposal'=>array( + 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposaldet', + 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposal', + ), + 'supplier_order'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet', 'DELETE FROM '.MAIN_DB_PREFIX.'commande_fournisseur', ), - 'supplier_invoice'=>array( + 'supplier_invoice'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det', 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn', - 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposaldet', - 'DELETE FROM '.MAIN_DB_PREFIX.'supplier_proposal', ), 'delivery'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'livraisondet', @@ -114,8 +116,10 @@ $sqls=array( 'DELETE FROM '.MAIN_DB_PREFIX.'product_lang', 'DELETE FROM '.MAIN_DB_PREFIX.'product_price', 'DELETE FROM '.MAIN_DB_PREFIX.'product_fournisseur_price', - 'DELETE FROM '.MAIN_DB_PREFIX.'product_stock', - 'DELETE FROM '.MAIN_DB_PREFIX.'product', + 'DELETE FROM '.MAIN_DB_PREFIX.'product_batch', + 'DELETE FROM '.MAIN_DB_PREFIX.'product_stock', + 'DELETE FROM '.MAIN_DB_PREFIX.'product_lot', + 'DELETE FROM '.MAIN_DB_PREFIX.'product', ), 'project'=>array( 'DELETE FROM '.MAIN_DB_PREFIX.'projet_task_time', @@ -128,12 +132,13 @@ $sqls=array( ), 'thirdparty'=>array( '@contact', - 'DELETE FROM '.MAIN_DB_PREFIX.'cabinetmed_cons', + 'DELETE FROM '.MAIN_DB_PREFIX.'cabinetmed_cons', 'UPDATE '.MAIN_DB_PREFIX.'adherent SET fk_soc = NULL', 'DELETE FROM '.MAIN_DB_PREFIX.'categorie_fournisseur', 'DELETE FROM '.MAIN_DB_PREFIX.'categorie_societe', 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except', - 'DELETE FROM '.MAIN_DB_PREFIX.'societe', + 'DELETE FROM '.MAIN_DB_PREFIX.'societe_rib', + 'DELETE FROM '.MAIN_DB_PREFIX.'societe', ) ); @@ -152,27 +157,37 @@ $mode = $argv[1]; $option = $argv[2]; if (empty($mode) || ! in_array($mode,array('test','confirm'))) { - print "Usage: $script_file (test|confirm) (all|option)\n"; + print "Usage: $script_file (test|confirm) (all|option) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; print "\n"; print "option can be ".implode(',',array_keys($sqls))."\n"; exit(-1); } if (empty($option) || ! in_array($option, array_merge(array('all'),array_keys($sqls))) ) { - print "Usage: $script_file (test|confirm) (all|option)\n"; + print "Usage: $script_file (test|confirm) (all|option) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; print "\n"; print "option can be ".implode(',',array_keys($sqls))."\n"; exit(-1); } +// Replace database handler +if (! empty($argv[3])) +{ + $db->close(); + unset($db); + $db=getDoliDBInstance($argv[3], $argv[4], $argv[5], $argv[6], $argv[7], $argv[8]); + $user=new User($db); +} +//var_dump($user->db->database_name); $ret=$user->fetch('','admin'); if (! $ret > 0) { - print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; + print 'An admin user with login "admin" must exists to use this script.'."\n"; exit; } -$user->getrights(); +//$user->getrights(); + print "Purge all data for this database:\n"; print "Server = ".$db->database_host."\n"; @@ -190,14 +205,14 @@ if (! $confirmed) /** * Process sql requests of a family - * + * * @param string $family Name of family key of array $sqls * @return int -1 if KO, 1 if OK */ function processfamily($family) { global $db, $sqls; - + $error=0; foreach($sqls[$family] as $sql) { @@ -207,7 +222,7 @@ function processfamily($family) processfamily($newfamily); continue; } - + print "Run sql: ".$sql."\n"; $resql=$db->query($sql); if (! $resql) @@ -217,7 +232,7 @@ function processfamily($family) $error++; } } - + if ($error) { print $db->lasterror(); @@ -225,7 +240,7 @@ function processfamily($family) break; } } - + if ($error) return -1; else return 1; } @@ -242,7 +257,7 @@ foreach($sqls as $family => $familysql) $oldfamily = $family; $result=processfamily($family); - if ($result < 0) + if ($result < 0) { $error++; break; diff --git a/dev/resources/sepa/test.xml b/dev/resources/sepa/test.xml new file mode 100644 index 00000000000..fc969a7624c --- /dev/null +++ b/dev/resources/sepa/test.xml @@ -0,0 +1,133 @@ + + + + + PREL20171012/REF10 + 2017-10-12T00:08:30 + 2 + 734.4 + + MyBigCompany + + + + FR76AAAAA + + + + + + + PREL20171012/ID00010-T171001 + DD + 2 + 734.4 + + + SEPA + + + CORE + + RCUR + + 2017-10-12 + + MyBigCompany + + FR + Address1 + Address2 + + + + + FR76123456 + + + + + BICABCDEF + + + SLEV + + + + + FR76AAAAA + + SEPA + + + + + + + + AS-FA1710-0416-000679 + + 540 + + + RUM-CU1610-0001-3-1476058417 + 2016-10-10 + false + + + + + BICXYZ + + + + CUSTOMER A + + FR + Mr abc + + + + + FR123456 + + + + FA1710-0416 + + + + + AS-FA1710-0415-000683 + + 194.4 + + + RUM-CU1709-0011-4-1506525346 + 2017-09-27 + false + + + + + BICJKL + + + + CUSTOMER2 + + FR + + + + + FR76123456 + + + + FA1710-0415 + + + + + diff --git a/dev/setup/apache/virtualhost b/dev/setup/apache/virtualhost new file mode 100644 index 00000000000..c3a2dff3e43 --- /dev/null +++ b/dev/setup/apache/virtualhost @@ -0,0 +1,62 @@ + +#php_admin_value sendmail_path "/usr/sbin/sendmail -t -i" +#php_admin_value mail.force_extra_parameters "-f postmaster@mydomain.com" +php_admin_value sendmail_path "/usr/sbin/sendmail -t -i -f postmaster@mydomain.com" +php_admin_value open_basedir /tmp/:/home/../htdocs + +ServerName myvirtualalias +ServerAlias myvirtualalias + +UseCanonicalName On + +AddDefaultCharset UTF-8 + +DocumentRoot "/home/.../htdocs" + + + AllowOverride None + Options -Indexes -MultiViews +FollowSymLinks -ExecCGI + Require all granted + + + + Deny from all + RemoveHandler .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml + AddType application/x-httpd-php-source .phtml .php .php3 .php4 .php5 .php6 .phps .cgi .exe .pl .asp .aspx .shtml .shtm .fcgi .fpl .jsp .htm .html .wml + + + +ErrorLog /var/log/apache2/myvirtualalias_error_log +TransferLog /var/log/apache2/myvirtualalias_access_log + +# Compress returned resources of type php pages, text file export, css and javascript +AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript + +AddType text/javascript .jgz +AddEncoding gzip .jgz +ExpiresActive On +ExpiresByType image/x-icon A2592000 +ExpiresByType image/gif A2592000 +ExpiresByType image/png A2592000 +ExpiresByType image/jpeg A2592000 +ExpiresByType text/css A2592000 +ExpiresByType text/javascript A2592000 +ExpiresByType application/x-javascript A2592000 +ExpiresByType application/javascript A2592000 + +SSLEngine On + +# A self-signed (snakeoil) certificate can be created by installing +# the ssl-cert package. See +# /usr/share/doc/apache2.2-common/README.Debian.gz for more info. +# If both key and certificate are stored in the same file, only the +# SSLCertificateFile directive is needed. +SSLCertificateFile /etc/letsencrypt/live/www.mydomain.com/cert.pem +SSLCertificateKeyFile /etc/letsencrypt/live/www.mydomain.com/privkey.pem +SSLCertificateChainFile /etc/letsencrypt/live/www.mydomain.com/chain.pem + +#RewriteEngine on +#RewriteCond %{SERVER_PORT} ^80$ +#RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [L,R] + + diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index fb48bc8094f..4dcc4be7b01 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2016 Laurent Destailleur + * Copyright (C) 2016-2017 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 @@ -67,8 +67,8 @@ $arrayfields=array( 'aa.account_number'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), 'aa.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), 'aa.account_parent'=>array('label'=>$langs->trans("Accountparent"), 'checked'=>0), - 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>0, 'help'=>'PcgtypeDesc'), - 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>0, 'help'=>'PcgtypeDesc'), + 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), + 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), 'aa.active'=>array('label'=>$langs->trans("Activated"), 'checked'=>1) ); @@ -105,14 +105,32 @@ if (empty($reshook)) $search_array_options=array(); } - if (GETPOST('change_chart')) + if (GETPOST('change_chart','alpha')) { $chartofaccounts = GETPOST('chartofaccounts', 'int'); - if (! empty($chartofaccounts)) { + if ($chartofaccounts > 0) + { + // Get language code for this $chartofaccounts + $sql ='SELECT code FROM '.MAIN_DB_PREFIX.'c_country as c, '.MAIN_DB_PREFIX.'accounting_system as a'; + $sql.=' WHERE c.rowid = a.fk_country AND a.rowid = '.(int) $chartofaccounts; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $country_code = $obj->code; + } + else dol_print_error($db); + + // Try to load sql file + if ($country_code) + { + $sqlfile = DOL_DOCUMENT_ROOT.'/install/mysql/data/llx_accounting_account_'.strtolower($country_code).'.sql'; + $result = run_sql($sqlfile, 1, 0, 1); + } if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { - $error ++; + $error++; } } else { $error ++; @@ -216,25 +234,29 @@ if ($resql) // Box to select active chart of account print $langs->trans("Selectchartofaccounts") . " : "; print '"; + print ajax_combobox("chartofaccounts"); print ''; print '
'; print '
'; diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 03565528fc1..5adb9760c9c 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -41,14 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -$langs->load("errors"); -$langs->load("admin"); -$langs->load("main"); -$langs->load("companies"); -$langs->load("resource"); -$langs->load("holiday"); -$langs->load("accountancy"); -$langs->load("hrm"); +$langs->loadLangs(array("errors","admin","companies","resource","holiday","compta","accountancy","hrm")); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; $confirm=GETPOST('confirm','alpha'); @@ -100,7 +93,7 @@ $tablib[32]= "DictionaryAccountancyCategory"; // Requests to extract data $tabsql=array(); -$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s"; +$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.fk_country as country_id, c.code as country_code, c.label as country, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s, ".MAIN_DB_PREFIX."c_country as c WHERE s.fk_country=c.rowid and c.active=1"; $tabsql[32]= "SELECT a.rowid as rowid, a.code as code, a.label, a.range_account, a.sens, a.category_type, a.formula, a.position as position, a.fk_country as country_id, c.code as country_code, c.label as country, a.active FROM ".MAIN_DB_PREFIX."c_accounting_category as a, ".MAIN_DB_PREFIX."c_country as c WHERE a.fk_country=c.rowid and c.active=1"; // Criteria to sort dictionaries @@ -110,17 +103,17 @@ $tabsqlsort[32]="position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[31]= "pcg_version,label"; +$tabfield[31]= "pcg_version,label,country_id,country"; $tabfield[32]= "code,label,range_account,sens,category_type,formula,position,country_id,country"; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[31]= "pcg_version,label"; +$tabfieldvalue[31]= "pcg_version,label,country"; $tabfieldvalue[32]= "code,label,range_account,sens,category_type,formula,position,country"; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[31]= "pcg_version,label"; +$tabfieldinsert[31]= "pcg_version,label,fk_country"; $tabfieldinsert[32]= "code,label,range_account,sens,category_type,formula,position,fk_country"; // Nom du rowid si le champ n'est pas de type autoincrement @@ -173,7 +166,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $ok=1; foreach ($listfield as $f => $value) { - if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancysystem','DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory + if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancyCategory','Pcg_version'))) continue; // For some pages, country is not mandatory if ($value == 'country' && in_array($tablib[$id],array('DictionaryCanton','DictionaryCompanyType','DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; @@ -188,6 +181,8 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $ok=0; $fieldnamekey=$listfield[$f]; // We take translate key of field + + if ($fieldnamekey == 'pcg_version') $fieldnamekey='Pcg_version'; if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; if ($fieldnamekey == 'nbjour') $fieldnamekey='NbOfDays'; diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index 53569c50b00..d5fb2175b5f 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -569,6 +569,7 @@ if ($id) print ""; $colspan=count($fieldlist)+3; + if ($id == 32) $colspan++; print ' '; // Keep   to have a line with enough height } diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index ce99bd6296c..c4b31c0f169 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -77,7 +77,7 @@ $list_account = array ( * Actions */ -$accounting_mode = defined('ACCOUNTING_MODE') ? ACCOUNTING_MODE : 'RECETTES-DEPENSES'; +$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; if (GETPOST('change_chart')) diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 5ce7d6c0413..a6215383f35 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -60,7 +60,7 @@ $list = array ( * Actions */ -$accounting_mode = defined('ACCOUNTING_MODE') ? ACCOUNTING_MODE : 'RECETTES-DEPENSES'; +$accounting_mode = empty($conf->global->ACCOUNTING_MODE) ? 'RECETTES-DEPENSES' : $conf->global->ACCOUNTING_MODE; if ($action == 'update') { $error = 0; diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 382d0697b6a..0dea177f00e 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -1,7 +1,7 @@ - * Copyright (C) 2016 Florian Henry - * Copyright (C) 2016 Alexandre Spangaro +/* Copyright (C) 2016 Olivier Geffroy + * Copyright (C) 2016 Florian Henry + * Copyright (C) 2016-2017 Alexandre Spangaro * * 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 @@ -125,9 +125,8 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', if ($action == 'export_csv') { $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - if ($conf->global->ACCOUNTING_EXPORT_MODELCSV == AccountancyExport::$EXPORT_TYPE_CEGID) $sep = ";"; // For CEGID, we force separator. - $journal = 'bookkepping'; + $journal = 'balance'; include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; @@ -138,10 +137,11 @@ if ($action == 'export_csv') { foreach ($object->lines as $line) { print length_accountg($line->numero_compte) . $sep; - print $line->debit . $sep; - print $line->credit . $sep; - print $line->debit . $sep; - print $line->credit - $line->debit . $sep; + print $object->get_compte_desc($line->numero_compte) . $sep; + print price($line->debit) . $sep; + print price($line->credit) . $sep; + print price($line->debit) . $sep; + print price($line->credit - $line->debit) . $sep; print "\n"; } } diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 30db29db927..eb991d55543 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -1,7 +1,7 @@ - * Copyright (C) 2013-2016 Florian Henry - * Copyright (C) 2013-2017 Alexandre Spangaro +/* Copyright (C) 2013-2016 Olivier Geffroy + * Copyright (C) 2013-2016 Florian Henry + * Copyright (C) 2013-2017 Alexandre Spangaro * Copyright (C) 2016-2017 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify @@ -44,6 +44,10 @@ $search_doc_ref = GETPOST("search_doc_ref"); $search_date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); $search_date_end = dol_mktime(0, 0, 0, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int')); $search_doc_date = dol_mktime(0, 0, 0, GETPOST('doc_datemonth', 'int'), GETPOST('doc_dateday', 'int'), GETPOST('doc_dateyear', 'int')); +$search_date_creation_start = dol_mktime(0, 0, 0, GETPOST('date_creation_startmonth', 'int'), GETPOST('date_creation_startday', 'int'), GETPOST('date_creation_startyear', 'int')); +$search_date_creation_end = dol_mktime(0, 0, 0, GETPOST('date_creation_endmonth', 'int'), GETPOST('date_creation_endday', 'int'), GETPOST('date_creation_endyear', 'int')); +$search_date_modification_start = dol_mktime(0, 0, 0, GETPOST('date_modification_startmonth', 'int'), GETPOST('date_modification_startday', 'int'), GETPOST('date_modification_startyear', 'int')); +$search_date_modification_end = dol_mktime(0, 0, 0, GETPOST('date_modification_endmonth', 'int'), GETPOST('date_modification_endday', 'int'), GETPOST('date_modification_endyear', 'int')); if (GETPOST("button_delmvt_x") || GETPOST("button_delmvt.x") || GETPOST("button_delmvt")) { $action = 'delbookkeepingyear'; @@ -53,7 +57,6 @@ if (GETPOST("button_export_file_x") || GETPOST("button_export_file.x") || GETPOS } $search_accountancy_code = GETPOST("search_accountancy_code"); - $search_accountancy_code_start = GETPOST('search_accountancy_code_start', 'alpha'); if ($search_accountancy_code_start == - 1) { $search_accountancy_code_start = ''; @@ -64,7 +67,6 @@ if ($search_accountancy_code_end == - 1) { } $search_accountancy_aux_code = GETPOST("search_accountancy_aux_code"); - $search_accountancy_aux_code_start = GETPOST('search_accountancy_aux_code_start', 'alpha'); if ($search_accountancy_aux_code_start == - 1) { $search_accountancy_aux_code_start = ''; @@ -102,15 +104,30 @@ if ($action != 'export_file' && ! isset($_POST['begin']) && ! isset($_GET['begin $search_date_end = dol_mktime(0, 0, 0, 12, 31, dol_print_date(dol_now(), '%Y')); } +$arrayfields=array( + 't.piece_num'=>array('label'=>$langs->trans("TransactionNumShort"), 'checked'=>1), + 't.doc_date'=>array('label'=>$langs->trans("Docdate"), 'checked'=>1), + 't.doc_ref'=>array('label'=>$langs->trans("Docref"), 'checked'=>1), + 't.numero_compte'=>array('label'=>$langs->trans("AccountAccountingShort"), 'checked'=>1), + 't.subledger_account'=>array('label'=>$langs->trans("SubledgerAccount"), 'checked'=>1), + 't.label_operation'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 't.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1), + 't.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1), + 't.code_journal'=>array('label'=>$langs->trans("Codejournal"), 'checked'=>1), + 't.date_creation'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0), + 't.tms'=>array('label'=>$langs->trans("DateModification"), 'checked'=>0), +); /* - * Action + * Actions */ if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + 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_mvt_num = ''; @@ -128,6 +145,10 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_ledger_code = ''; $search_date_start = ''; $search_date_end = ''; + $search_date_creation_start = ''; + $search_date_creation_end = ''; + $search_date_modification_start = ''; + $search_date_modification_end = ''; } // Must be after the remove filter action, before the export. @@ -196,6 +217,26 @@ if (! empty($search_mvt_num)) { $filter['t.piece_num'] = $search_mvt_num; $param .= '&search_mvt_num=' . $search_mvt_num; } +if (! empty($search_date_creation_start)) { + $filter['t.date_creation>='] = $search_date_creation_start; + $tmp=dol_getdate($search_date_creation_start); + $param .= '&date_creation_startmonth=' . $tmp['mon'] . '&date_creation_startday=' . $tmp['mday'] . '&date_creation_startyear=' . $tmp['year']; +} +if (! empty($search_date_creation_end)) { + $filter['t.date_creation<='] = $search_date_creation_end; + $tmp=dol_getdate($search_date_creation_end); + $param .= '&date_creation_endmonth=' . $tmp['mon'] . '&date_creation_endday=' . $tmp['mday'] . '&date_creation_endyear=' . $tmp['year']; +} +if (! empty($search_date_modification_start)) { + $filter['t.tms>='] = $search_date_modification_start; + $tmp=dol_getdate($search_date_modification_start); + $param .= '&date_modification_startmonth=' . $tmp['mon'] . '&date_modification_startday=' . $tmp['mday'] . '&date_modification_startyear=' . $tmp['year']; +} +if (! empty($search_date_modification_end)) { + $filter['t.tms<='] = $search_date_modification_end; + $tmp=dol_getdate($search_date_modification_end); + $param .= '&date_modification_endmonth=' . $tmp['mon'] . '&date_modification_endday=' . $tmp['mday'] . '&date_modification_endyear=' . $tmp['year']; +} if ($action == 'delbookkeeping') { @@ -370,137 +411,288 @@ print '
'; -print ''; +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); +print '
'; +print '
'; + +// Filters lines print ''; -print ''; -print ''; -print ''; -print ''; -print ''; } -else +// Date document +if (! empty($arrayfields['t.doc_date']['checked'])) { - print ''; + print ''; } -print ''; -print '
'; -print $langs->trans('to').' '; -// TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not -// use setup of keypress to select thirdparty and this hang browser on large database. -if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) +// Ref document +if (! empty($arrayfields['t.doc_ref']['checked'])) { - print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); + print '
'; } -else +// Accountancy account +if (! empty($arrayfields['t.numero_compte']['checked'])) { - print ''; + print ''; } -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; +// Subledger account +if (! empty($arrayfields['t.subledger_account']['checked'])) +{ + print ''; +} +// Label operation +if (! empty($arrayfields['t.label_operation']['checked'])) +{ + print ''; +} +// Debit +if (! empty($arrayfields['t.debit']['checked'])) +{ + print ''; +} +// Credit +if (! empty($arrayfields['t.credit']['checked'])) +{ + print ''; +} +// Code journal +if (! empty($arrayfields['t.code_journal']['checked'])) +{ + print ''; +} +// Date creation +if (! empty($arrayfields['t.date_creation']['checked'])) +{ + print ''; +} +// Date modification +if (! empty($arrayfields['t.tms']['checked'])) +{ + print ''; +} +// Action column print ''; -print ''; +print "\n"; print ''; -print_liste_field_titre("TransactionNumShort", $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("Docdate", $_SERVER['PHP_SELF'], "t.doc_date", "", $param, 'align="center"', $sortfield, $sortorder); -print_liste_field_titre("Docref", $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("AccountAccountingShort", $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("SubledgerAccount", $_SERVER['PHP_SELF'], "t.subledger_account", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("Label", $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("Debit", $_SERVER['PHP_SELF'], "t.debit", "", $param, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre("Credit", $_SERVER['PHP_SELF'], "t.credit", "", $param, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre("Codejournal", $_SERVER['PHP_SELF'], "t.code_journal", "", $param, 'align="center"', $sortfield, $sortorder); -$checkpicto=''; -if ($massactionbutton) $checkpicto=$form->showCheckAddButtons('checkforselect', 1); -print_liste_field_titre($checkpicto, $_SERVER["PHP_SELF"], "", $param, "", 'width="60" align="center"', $sortfield, $sortorder); +if (! empty($arrayfields['t.piece_num']['checked'])) print_liste_field_titre("TransactionNumShort", $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder); +if (! empty($arrayfields['t.doc_date']['checked'])) print_liste_field_titre("Docdate", $_SERVER['PHP_SELF'], "t.doc_date", "", $param, 'align="center"', $sortfield, $sortorder); +if (! empty($arrayfields['t.doc_ref']['checked'])) print_liste_field_titre("Docref", $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); +if (! empty($arrayfields['t.numero_compte']['checked'])) print_liste_field_titre("AccountAccountingShort", $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); +if (! empty($arrayfields['t.subledger_account']['checked'])) print_liste_field_titre("SubledgerAccount", $_SERVER['PHP_SELF'], "t.subledger_account", "", $param, "", $sortfield, $sortorder); +if (! empty($arrayfields['t.label_operation']['checked'])) print_liste_field_titre("Label", $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); +if (! empty($arrayfields['t.debit']['checked'])) print_liste_field_titre("Debit", $_SERVER['PHP_SELF'], "t.debit", "", $param, 'align="right"', $sortfield, $sortorder); +if (! empty($arrayfields['t.credit']['checked'])) print_liste_field_titre("Credit", $_SERVER['PHP_SELF'], "t.credit", "", $param, 'align="right"', $sortfield, $sortorder); +if (! empty($arrayfields['t.code_journal']['checked'])) print_liste_field_titre("Codejournal", $_SERVER['PHP_SELF'], "t.code_journal", "", $param, 'align="center"', $sortfield, $sortorder); +if (! empty($arrayfields['t.date_creation']['checked'])) print_liste_field_titre("DateCreation", $_SERVER['PHP_SELF'], "t.date_creation", "", $param, 'align="center"', $sortfield, $sortorder); +if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre("DateModification", $_SERVER['PHP_SELF'], "t.tms", "", $param, 'align="center"', $sortfield, $sortorder); +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; -$total_debit = 0; -$total_credit = 0; - -$i=0; -while ($i < min($num, $limit)) +if ($num > 0) { - $line = $object->lines[$i]; + $i=0; + $totalarray=array(); + while ($i < min($num, $limit)) + { + $line = $object->lines[$i]; - $total_debit += $line->debit; - $total_credit += $line->credit; + $total_debit += $line->debit; + $total_credit += $line->credit; - print ''; + print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + // Piece number + if (! empty($arrayfields['t.piece_num']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - $accountingjournal = new AccountingJournal($db); - $result = $accountingjournal->fetch('',$line->code_journal); - $journaltoshow = (($result > 0)?$accountingjournal->getNomUrl(0,0,0,'',0) : $line->code_journal); - print ''; + // Document date + if (! empty($arrayfields['t.doc_date']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - print ''; - print "\n"; + // Document ref + if (! empty($arrayfields['t.doc_ref']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } - $i++; + // Account number + if (! empty($arrayfields['t.numero_compte']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Subledger account + if (! empty($arrayfields['t.subledger_account']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Label operation + if (! empty($arrayfields['t.label_operation']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Amount debit + if (! empty($arrayfields['t.debit']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totaldebitfield']=$totalarray['nbfield']; + $totalarray['totaldebit'] += $line->debit; + } + + // Amount credit + if (! empty($arrayfields['t.credit']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalcreditfield']=$totalarray['nbfield']; + $totalarray['totalcredit'] += $line->credit; + } + + // Journal code + if (! empty($arrayfields['t.code_journal']['checked'])) + { + $accountingjournal = new AccountingJournal($db); + $result = $accountingjournal->fetch('',$line->code_journal); + $journaltoshow = (($result > 0)?$accountingjournal->getNomUrl(0,0,0,'',0) : $line->code_journal); + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Creation operation date + if (! empty($arrayfields['t.date_creation']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Modification operation date + if (! empty($arrayfields['t.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print "\n"; + + $i++; + } + + // Show total line + if (isset($totalarray['totaldebitfield']) || isset($totalarray['totalcreditfield'])) + { + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } + elseif ($totalarray['totaldebitfield'] == $i) print ''; + elseif ($totalarray['totalcreditfield'] == $i) print ''; + else print ''; + } + print ''; + + } } -print ''; -if ($num < $limit) print ''; -else print ''; -print ''; -print ''; -print ''; -print ''; -print ''; - print "
'; -print '
'; -print $langs->trans('From') . ' '; -print $form->select_date($search_date_start, 'date_start', 0, 0, 1); -print '
'; -print '
'; -print $langs->trans('to') . ' '; -print $form->select_date($search_date_end, 'date_end', 0, 0, 1); -print '
'; -print '
'; -print '
'; -print $langs->trans('From').' '; -print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, 'maxwidth200'); -print '
'; -print '
'; -print $langs->trans('to').' '; -print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array (), 1, 1, 'maxwidth200'); -print '
'; -print '
'; -print '
'; -print $langs->trans('From').' '; -// TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not -// use setup of keypress to select thirdparty and this hang browser on large database. -if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) +// Movement number +if (! empty($arrayfields['t.piece_num']['checked'])) { - print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1); + print '
'; + print '
'; + print $langs->trans('From') . ' '; + print $form->select_date($search_date_start, 'date_start', 0, 0, 1); + print '
'; + print '
'; + print $langs->trans('to') . ' '; + print $form->select_date($search_date_end, 'date_end', 0, 0, 1); + print '
'; + print '
'; + print '
'; + print $langs->trans('From').' '; + print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, 'maxwidth200'); + print '
'; + print '
'; + print $langs->trans('to').' '; + print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array (), 1, 1, 'maxwidth200'); + print '
'; + print '
'; -print ''; -print '  '; + print '
'; + print $langs->trans('From').' '; + // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not + // use setup of keypress to select thirdparty and this hang browser on large database. + if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) + { + print $formaccounting->select_auxaccount($search_accountancy_aux_code_start, 'search_accountancy_aux_code_start', 1); + } + else + { + print ''; + } + print '
'; + print '
'; + print $langs->trans('to').' '; + // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not + // use setup of keypress to select thirdparty and this hang browser on large database. + if (! empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) + { + print $formaccounting->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); + } + else + { + print ''; + } + print '
'; + print '
'; + print ''; + print '  '; + print '
'; + print $langs->trans('From') . ' '; + print $form->select_date($search_date_creation_start, 'date_creation_start', 0, 0, 1); + print '
'; + print '
'; + print $langs->trans('to') . ' '; + print $form->select_date($search_date_creation_end, 'date_creation_end', 0, 0, 1); + print '
'; + print '
'; + print '
'; + print $langs->trans('From') . ' '; + print $form->select_date($search_date_modification_start, 'date_modification_start', 0, 0, 1); + print '
'; + print '
'; + print $langs->trans('to') . ' '; + print $form->select_date($search_date_modification_end, 'date_modification_end', 0, 0, 1); + print '
'; + print '
'; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '
' . $line->piece_num . '' . dol_print_date($line->doc_date, 'day') . '' . $line->doc_ref . '' . length_accountg($line->numero_compte) . '' . length_accounta($line->subledger_account) . '' . $line->label_operation . '' . ($line->debit ? price($line->debit) : ''). '' . ($line->credit ? price($line->credit) : '') . '' . $line->piece_num . '' . $journaltoshow . '' . dol_print_date($line->doc_date, 'day') . ''; - print '' . img_edit() . ' '; - print '' . img_delete() . ''; - print '
' . $line->doc_ref . '' . length_accountg($line->numero_compte) . '' . length_accounta($line->subledger_account) . '' . $line->label_operation . '' . ($line->debit ? price($line->debit) : ''). '' . ($line->credit ? price($line->credit) : '') . '' . $journaltoshow . '' . dol_print_date($line->date_creation, 'day') . '' . dol_print_date($line->date_modification, 'day') . ''; + print '' . img_edit() . ' '; + print '' . img_delete() . ''; + print '
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totaldebit']).''.price($totalarray['totalcredit']).'
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''; -print price($total_debit); -print ''; -print price($total_credit); -print '
"; print '
'; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php index e80634ad7f6..782a7de7aa4 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php @@ -21,11 +21,10 @@ */ /** - * \file accounting/bookkeeping/thirdparty_lettrage.php + * \file accounting/bookkeeping/thirdparty_lettrage.php * \ingroup Advanced accountancy - * \brief Onglet de gestion de parametrages des ventilations + * \brief Onglet de gestion de parametrages des ventilations */ - require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; @@ -34,52 +33,71 @@ require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; -$action=GETPOST('action','aZ09'); -$massaction=GETPOST('massaction','alpha'); -$show_files=GETPOST('show_files','int'); -$confirm=GETPOST('confirm','alpha'); +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = GETPOST("page",'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOST("page", 'int'); +if (empty($page) || $page == - 1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($sortorder == "") $sortorder = "ASC"; -if ($sortfield == "") $sortfield = "bk.rowid"; +if ($sortorder == "") + $sortorder = "DESC"; +if ($sortfield == "") + $sortfield = "bk.doc_date"; -$search_year = GETPOST ( "search_year" ); +$search_year = GETPOST("search_year", 'int'); +$search_doc_type = GETPOST("search_doc_type", 'alpha'); +$search_doc_ref = GETPOST("search_doc_ref", 'alpha'); + +$lettering = GETPOST('lettering'); +if (! empty($lettering)) { + $action = $lettering; +} +$toselect = GETPOST('toselect', 'array'); + +// Did we click on purge search criteria ? +// All tests are required to be compatible with all browsers +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $search_year = ''; + $search_doc_type = ''; + $search_doc_ref = ''; +} // Security check -$socid = GETPOST("socid",'int'); +$socid = GETPOST("socid", 'int'); // if ($user->societe_id) $socid=$user->societe_id; $object = new Societe($db); $object->id = $socid; -$object->fetch($socid); - +$result = $object->fetch($socid); +if ($result < 0) { + setEventMessage($object->error, 'errors'); +} $form = new Form($db); $BookKeeping = new lettering($db); $formaccounting = new FormAccounting($db); - /* * Action */ if ($action == 'lettering') { - $result = $BookKeeping->updatelettrage($_POST['ids']); - -// var_dump($result); - if( $result < 0 ){ - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + $result = $BookKeeping->updateLettrage($toselect); + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } } @@ -87,243 +105,214 @@ if ($action == 'autolettrage') { $result = $BookKeeping->lettrageTiers($socid); - if( $result < 0 ) - { - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } - } +llxHeader('', 'Compta - Grand Livre'); -llxHeader ( '', 'Compta - Grand Livre' ); +/* + * Affichage onglets + */ +$head = societe_prepare_head($object); +dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error'); - /* - * Affichage onglets - */ - $head = societe_prepare_head($object); +dol_fiche_head($head, 'accounting', $langs->trans("ThirdParty"), 0, 'company'); - dol_htmloutput_mesg(is_numeric($error)?'':$error, $errors, 'error'); +print ''; +print ''; - dol_fiche_head($head, 'TabAccounting', $langs->trans("ThirdParty"),0,'company'); +if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field +{ + print ''; +} +print ''; +print ''; +print ''; +$langs->load('compta'); +print ''; +print ''; +print ''; +// Address +print ''; - print '
' . $langs->trans("ThirdPartyName") . ''; +$object->next_prev_filter = "te.fournisseur = 1"; +print $form->showrefnav($object, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom', '', ''); +print '
' . $langs->trans('Prefix') . '' . $object->prefix_comm . '
' . $langs->trans("CustomerCode") . ''; +print $object->code_client; +if ($object->check_codeclient() != 0) + print ' (' . $langs->trans("WrongCustomerCode") . ')'; +print '
'; +print $form->editfieldkey("CustomerAccountancyCode", 'customeraccountancycode', $object->code_compta, $object, $user->rights->societe->creer); +print ''; +print $form->editfieldval("CustomerAccountancyCode", 'customeraccountancycode', $object->code_compta, $object, $user->rights->societe->creer); +print '
' . $langs->trans("Address") . ''; +dol_print_address($object->address, 'gmap', 'thirdparty', $object->id); +print '
'; - print ''; +// Zip / Town +print ''; +print ''; - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { - print ''; - } +// Country +print ''; +print '
'.$langs->trans("ThirdPartyName").''; - $object->next_prev_filter="te.fournisseur = 1"; - print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom','',''); - print '
' . $langs->trans("Zip") . ' / ' . $langs->trans("Town") . '' . $object->zip . (($object->zip && $object->town) ? ' / ' : '') . $object->town . '
'.$langs->trans('Prefix').''.$object->prefix_comm.'
' . $langs->trans("Country") . ''; +// $img=picto_from_langcode($object->country_code); +$img = ''; +if ($object->isInEEC()) + print $form->textwithpicto(($img ? $img . ' ' : '') . $object->country, $langs->trans("CountryIsInEEC"), 1, 0); +else + print ($img ? $img . ' ' : '') . $object->country; +print '
'; - print ''; - print ''.$langs->trans("CustomerCode"). ''; - print $object->code_client; - if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; - print ''; - print ''; +$sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, "; +$sql .= " bk.thirdparty_code, bk.numero_compte , bk.label_compte, bk.debit, "; +$sql .= " bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code "; +$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; +$sql .= " WHERE (bk.thirdparty_code = '" . $object->code_compta . "' AND bk.numero_compte = '" . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . "' )"; - $langs->load('compta'); - print ''; - print ''; - print $form->editfieldkey("CustomerAccountancyCode",'customeraccountancycode',$object->code_compta,$object,$user->rights->societe->creer); - print ''; - print $form->editfieldval("CustomerAccountancyCode",'customeraccountancycode',$object->code_compta,$object,$user->rights->societe->creer); - print ''; - print ''; +if (dol_strlen($search_year)) { + $date_start = dol_mktime(0, 0, 0, 1, 1, $search_year); + $date_end = dol_mktime(23, 59, 59, 12, 31, $search_year); + $sql .= " AND ( bk.doc_date BETWEEN '" . $db->idate($date_start) . "' AND '" . $db->idate($date_end) . "' )"; +} +$sql .= $db->order($sortfield, $sortorder); - // Address - print ''.$langs->trans("Address").''; - dol_print_address($object->address,'gmap','thirdparty',$object->id); - print ''; +$debit = 0; +$credit = 0; +$solde = 0; +// Count total nb of records and calc total sum +$nbtotalofrecords = ''; +$resql = $db->query($sql); +if (! $resql) { + dol_print_error($db); + exit(); +} +$nbtotalofrecords = $db->num_rows($resql); - // Zip / Town - print ''.$langs->trans("Zip").' / '.$langs->trans("Town").''.$object->zip.(($object->zip && $object->town)?' / ':'').$object->town.''; +while ( $obj = $db->fetch_object($resql) ) { + $debit += $obj->debit; + $credit += $obj->credit; + + $solde += ($obj->credit - $obj->debit); +} + +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog("/accountancy/bookkeeping/thirdparty_lettrage.php", LOG_DEBUG); +$resql = $db->query($sql); +if (! $resql) { + dol_print_error($db); + exit(); +} + +$num = $db->num_rows($resql); + +dol_syslog("/accountancy/bookkeeping/thirdparty_lettrage.php", LOG_DEBUG); +if ($resql) { + $i = 0; + + print '
'; + print ''; + + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + + print ""; + print ''; + print_liste_field_titre("Doctype", $_SERVER["PHP_SELF"], "bk.doc_type", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Docdate", $_SERVER["PHP_SELF"], "bk.doc_date", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Docref", $_SERVER["PHP_SELF"], "bk.doc_ref", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Labelcompte", $_SERVER["PHP_SELF"], "bk.label_compte", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Debit", $_SERVER["PHP_SELF"], "bk.debit", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Credit", $_SERVER["PHP_SELF"], "bk.credit", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "bk.montant", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Sens", $_SERVER["PHP_SELF"], "bk.sens", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Codejournal", $_SERVER["PHP_SELF"], "bk.code_journal", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("Solde", $_SERVER["PHP_SELF"], "", "", $param, "", $sortfield, $sortorder); + print ''; + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; - // Country - print ''; + $var = false; + $solde = 0; + $tmp = ''; + while ( $obj = $db->fetch_object($resql) ) { - print '
 '; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print '
'.$langs->trans("Country").''; - //$img=picto_from_langcode($object->country_code); - $img=''; - if ($object->isInEEC()) print $form->textwithpicto(($img?$img.' ':'').$object->country,$langs->trans("CountryIsInEEC"),1,0); - else print ($img?$img.' ':'').$object->country; - print '
'; + if ($tmp != $obj->lettering_code || empty($tmp)) + $tmp = $obj->lettering_code; + if ($tmp != $obj->lettering_code || empty($obj->lettering_code)) + $var = ! $var; + $solde += ($obj->credit - $obj->debit); + print ""; + if (empty($obj->lettering_code)) { + print '
'; + print img_edit(); + print ' ' . $obj->doc_type . '' . "\n"; + } else + print '' . $obj->doc_type . '' . "\n"; - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE (bk.code_tiers = '" . $object->code_compta . "' AND bk.numero_compte = '" .$conf->global->ACCOUNTING_ACCOUNT_CUSTOMER. "' )" ; + print '' . dol_print_date($db->jdate($obj->doc_date), 'day') . ''; + print '' . $obj->doc_ref . ''; + print '' . $obj->label_compte . ''; + print '' . price($obj->debit) . ''; + print '' . price($obj->credit) . ''; + print '' . price($obj->montant) . ''; + print '' . $obj->sens . ''; + print '' . $obj->code_journal . ''; + print '' . round($solde, 2) . ''; + if (empty($obj->lettering_code)) { + print ''; + } else + print '' . $obj->lettering_code . ''; - - if (dol_strlen ( $search_year )) { - $sql .= " AND ( bk.doc_date BETWEEN '" . $search_year . "-0-0' AND '" . ($search_year+1). "-0-0' )"; - } - - - $sql .= " ORDER BY bk.lettering_code ASC, bk.doc_date ASC" ;//. $db->plimit ( $conf->liste_limit + 1, $offset ); - -// echo $sql; -// dol_syslog ( "bookkeping:liste:create sql=" . $sql, LOG_DEBUG ); - $resql = $db->query ( $sql ); - if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; - - - print ''; - print ''; - print ''; - - print ""; - print ''; - print ''; - print_liste_field_titre("Doctype", "liste.php", "bk.doc_type" ); - print_liste_field_titre("Docdate", "liste.php", "bk.doc_date" ); - print_liste_field_titre("Docref", "liste.php", "bk.doc_ref" ); -// print_liste_field_titre("Numerocompte", "liste.php", "bk.numero_compte" ); -// print_liste_field_titre("Code_tiers", "liste.php", "bk.code_tiers" ); - print_liste_field_titre("LabelAccount", "liste.php", "bk_label_compte" ); - print_liste_field_titre("Debit", "liste.php", "bk.debit" ); - print_liste_field_titre("Credit", "liste.php", "bk.credit" ); -// print_liste_field_titre("Amount", "liste.php", "bk.montant" ); -// print_liste_field_titre("Sens", "liste.php", "bk.sens" ); - print_liste_field_titre("Codejournal", "liste.php", "bk.code_journal" ); - print ''; - print ''; print "\n"; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $var = false; - - $debit = 0; - $credit = 0; - $solde = 0; - $tmp = ''; - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); - - if($tmp !=$obj->lettering_code || empty($tmp) ) - $tmp =$obj->lettering_code; - - if($tmp !=$obj->lettering_code || empty($obj->lettering_code)) - $var = ! $var; - - - $debit+= $obj->debit; - $credit+= $obj->credit; - - $solde+=($obj->credit-$obj->debit); - print ""; - - print ''; - if(empty($obj->lettering_code)){ - print '' . "\n"; - } - else - print '' . "\n"; - - - - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - - if(empty($obj->lettering_code)){ - print ''; - } - else - print ''; - - print "\n"; - - $i ++; - - - - - } - - print ''; - - print '' . "\n"; - print ''; - // print ''; - // print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print ""; - print '' . "\n"; - // print ''; - // print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print "
     '; - print ''; - print '   
' . $obj->rowid . ''; - print img_edit (); - print ' ' . $obj->doc_type . ''.$obj->doc_type . '' . dol_print_date ( $db->jdate ( $obj->doc_date ), 'day' ) . '' . $obj->doc_ref . '' . $obj->numero_compte . '' . $obj->code_tiers . '' . $obj->label_compte . '' . $obj->debit . '' . $obj->credit . '' . $obj->montant . '' . $obj->sens . '' . $obj->code_journal . '' . round($solde, 2) . '' . $obj->lettering_code . '
Mouvement totaux' . $debit . '' . $credit . ' 
Solde Comptable' . ($credit-$debit) . ' 
"; - - print ''; - print 'auto lettering'; - print ""; - $db->free($resql); - } else { - dol_print_error($db); } + print ''; + + print 'Mouvement totaux' . "\n"; + print '' . price($debit) . ''; + print '' . price($credit) . ''; + print ''; + print "\n"; + + print ""; + print 'Solde Comptable' . "\n"; + print '' . price($credit - $debit) . ''; + print ''; + print "\n"; + + print ""; + + print ''; + print '' . $langs->trans('AccountancyAutoLettering') . ''; + print ""; + $db->free($resql); +} else { + dol_print_error($db); +} // End of page llxFooter(); diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php index 99374a97118..5ac224673aa 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php @@ -21,9 +21,9 @@ */ /** - * \file accounting/bookkeeping/thirdparty_lettrage.php + * \file accounting/bookkeeping/thirdparty_lettrage.php * \ingroup Advanced accountancy - * \brief Tab to setup lettering + * \brief Tab to setup lettering */ // Dolibarr environment @@ -35,52 +35,73 @@ require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; - -$action=GETPOST('action','aZ09'); -$massaction=GETPOST('massaction','alpha'); -$show_files=GETPOST('show_files','int'); -$confirm=GETPOST('confirm','alpha'); +$action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = GETPOST("page",'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOST("page", 'int'); +if (empty($page) || $page == - 1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($sortorder == "") $sortorder = "ASC"; -if ($sortfield == "") $sortfield = "bk.rowid"; +if ($sortorder == "") + $sortorder = "DESC"; +if ($sortfield == "") + $sortfield = "bk.doc_date"; -$search_year = GETPOST ( "search_year" ); +$search_year = GETPOST("search_year",'int'); +$search_doc_type = GETPOST("search_doc_type",'alpha'); +$search_doc_ref = GETPOST("search_doc_ref",'alpha'); + +$lettering = GETPOST('lettering'); +if (!empty($lettering)) { + $action=$lettering; +} +$toselect = GETPOST('toselect','array'); + +// Did we click on purge search criteria ? +// All tests are required to be compatible with all browsers +if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) +{ + $search_year=''; + $search_doc_type=''; + $search_doc_ref=''; +} // Security check -$socid = GETPOST("socid",'int'); +$socid = GETPOST("socid", 'int'); // if ($user->societe_id) $socid=$user->societe_id; $object = new Societe($db); $object->id = $socid; -$object->fetch($socid); +$result = $object->fetch($socid); +if ($result<0) { + setEventMessage($object->error,'errors'); +} $form = new Form($db); $BookKeeping = new lettering($db); $formaccounting = new FormAccounting($db); - /* * Action */ if ($action == 'lettering') { - $result = $BookKeeping->updatelettrage($_POST['ids']); - -// var_dump($result); - if( $result < 0 ){ - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + $result = $BookKeeping->updateLettrage($toselect); + // var_dump($result); + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } } @@ -88,247 +109,230 @@ if ($action == 'autolettrage') { $result = $BookKeeping->lettrageTiers($socid); - if ( $result < 0 ) - { - setEventMessages('', $BookKeeping->errors, 'errors' ); - $error++; + if ($result < 0) { + setEventMessages('', $BookKeeping->errors, 'errors'); + $error ++; } - } +$title = 'AccountancyLettrage'; -llxHeader ( '', 'Compta - Grand Livre' ); +llxHeader('', $title); - /* - * Affichage onglets - */ - $head = societe_prepare_head($object); +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if (!empty($search_year)) $param.='&search_year='.$search_year; +if (!empty($socid)) $param.='&socid='.$socid; +if (!empty($search_doc_type)) $param.='&search_doc_type='.$search_doc_type; +if (!empty($search_doc_ref)) $param.='&search_doc_ref='.$search_doc_ref; - dol_htmloutput_mesg(is_numeric($error)?'':$error, $errors, 'error'); - - dol_fiche_head($head, 'TabAccounting', $langs->trans("ThirdParty"),0,'company'); - - - - - print ''; - print ''; - - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { - print ''; - } - - - print ''; - print ''; - print ''; - - $langs->load('compta'); - print ''; - print ''; - print ''; - - - // Address - print ''; - - // Zip / Town - print ''; - print ''; - - // Country - print ''; - - print '
'.$langs->trans("ThirdPartyName").''; - $object->next_prev_filter="te.fournisseur = 1"; - print $form->showrefnav($object,'socid','',($user->societe_id?0:1),'rowid','nom','',''); - print '
'.$langs->trans('Prefix').''.$object->prefix_comm.'
'.$langs->trans("SupplierCode"). ''; - print $object->code_fournisseur; - if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; - print '
'; - print $form->editfieldkey("SupplierAccountancyCode",'supplieraccountancycode',$object->code_compta_fournisseur,$object,$user->rights->societe->creer); - print ''; - print $form->editfieldval("SupplierAccountancyCode",'supplieraccountancycode',$object->code_compta_fournisseur,$object,$user->rights->societe->creer); - print '
'.$langs->trans("Address").''; - dol_print_address($object->address,'gmap','thirdparty',$object->id); - print '
'.$langs->trans("Zip").' / '.$langs->trans("Town").''.$object->zip.(($object->zip && $object->town)?' / ':'').$object->town.'
'.$langs->trans("Country").''; - //$img=picto_from_langcode($object->country_code); - $img=''; - if ($object->isInEEC()) print $form->textwithpicto(($img?$img.' ':'').$object->country,$langs->trans("CountryIsInEEC"),1,0); - else print ($img?$img.' ':'').$object->country; - print '
'; - -// print_r($soc); -// exit; -// [code_compta] => 411DOUA -// [code_compta_fournisseur] => 401SUPPCODE /* - * Mode Liste - * - * - * + * Affichage onglets */ +$head = societe_prepare_head($object); - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE (bk.code_tiers = '" . $object->code_compta_fournisseur . "' AND bk.numero_compte = '" .$conf->global->ACCOUNTING_ACCOUNT_SUPPLIER. "' )" ; +dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error'); +dol_fiche_head($head, 'accounting_supplier', $langs->trans("ThirdParty"), 0, 'company'); +print ''; +print ''; - if (dol_strlen ( $search_year )) { - $sql .= " AND ( bk.doc_date BETWEEN '" . $search_year . "-0-0' AND '" . ($search_year+1). "-0-0' )"; - } +if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field +{ + print ''; +} +print ''; +print ''; +print ''; - $sql .= " ORDER BY bk.lettering ASC, bk.doc_date ASC" ;//. $db->plimit ( $conf->liste_limit + 1, $offset ); +$langs->load('compta'); +print ''; +print ''; +print ''; -// echo $sql; -// dol_syslog ( "bookkeping:liste:create sql=" . $sql, LOG_DEBUG ); - $resql = $db->query ( $sql ); - if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; +// Address +print ''; +// Zip / Town +print ''; +print ''; - print ''; - print ''; - print ''; +// Country +print ''; + +print '
' . $langs->trans("ThirdPartyName") . ''; +$object->next_prev_filter = "te.fournisseur = 1"; +print $form->showrefnav($object, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom', '', ''); +print '
' . $langs->trans('Prefix') . '' . $object->prefix_comm . '
' . $langs->trans("SupplierCode") . ''; +print $object->code_fournisseur; +if ($object->check_codefournisseur() != 0) + print ' (' . $langs->trans("WrongSupplierCode") . ')'; +print '
'; +print $form->editfieldkey("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer); +print ''; +print $form->editfieldval("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer); +print '
' . $langs->trans("Address") . ''; +dol_print_address($object->address, 'gmap', 'thirdparty', $object->id); +print '
' . $langs->trans("Zip") . ' / ' . $langs->trans("Town") . '' . $object->zip . (($object->zip && $object->town) ? ' / ' : '') . $object->town . '
' . $langs->trans("Country") . ''; +// $img=picto_from_langcode($object->country_code); +$img = ''; +if ($object->isInEEC()) + print $form->textwithpicto(($img ? $img . ' ' : '') . $object->country, $langs->trans("CountryIsInEEC"), 1, 0); +else + print ($img ? $img . ' ' : '') . $object->country; +print '
'; + +$sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, "; +$sql .= " bk.thirdparty_code, bk.numero_compte , bk.label_compte, bk.debit, "; +$sql .= " bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.lettering_code "; +$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; +$sql .= " WHERE (bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' AND bk.numero_compte = '" . $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER . "' )"; + +if (dol_strlen($search_year)) { + $date_start = dol_mktime(0, 0, 0, 1, 1, $search_year); + $date_end = dol_mktime(23, 59, 59, 12, 31, $search_year); + $sql .= " AND ( bk.doc_date BETWEEN '".$db->idate($date_start)."' AND '".$db->idate($date_end)."' )"; +} + +$sql.= $db->order($sortfield,$sortorder); + +$debit = 0; +$credit = 0; +$solde = 0; +// Count total nb of records and calc total sum +$nbtotalofrecords = ''; +$resql = $db->query($sql); +if (! $resql) +{ + dol_print_error($db); + exit; +} +$nbtotalofrecords = $db->num_rows($resql); + +while ($obj = $db->fetch_object($resql)) { + $debit += $obj->debit; + $credit += $obj->credit; + + $solde += ($obj->credit - $obj->debit); +} + +$sql.= $db->plimit($limit+1, $offset); + +dol_syslog ( "/accountancy/bookkeeping/thirdparty_lettrage_supplier.php", LOG_DEBUG ); +$resql = $db->query($sql); +if (! $resql) +{ + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + +dol_syslog ( "/accountancy/bookkeeping/thirdparty_lettrage_supplier.php", LOG_DEBUG ); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + + print ''; + print ''; + + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + + print ""; + print ''; + print_liste_field_titre("Doctype", $_SERVER["PHP_SELF"], "bk.doc_type","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Docdate", $_SERVER["PHP_SELF"], "bk.doc_date","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Docref", $_SERVER["PHP_SELF"], "bk.doc_ref","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Labelcompte", $_SERVER["PHP_SELF"], "bk.label_compte","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Debit", $_SERVER["PHP_SELF"], "bk.debit","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Credit", $_SERVER["PHP_SELF"], "bk.credit","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "bk.montant","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Sens", $_SERVER["PHP_SELF"], "bk.sens","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Codejournal", $_SERVER["PHP_SELF"], "bk.code_journal","",$param,"",$sortfield,$sortorder); + print_liste_field_titre("Solde", $_SERVER["PHP_SELF"], "","",$param,"",$sortfield,$sortorder); + print ''; + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $var = false; + $solde = 0; + $tmp = ''; + while ($obj = $db->fetch_object($resql)) { + + if ($tmp != $obj->lettering_code || empty($tmp)) + $tmp = $obj->lettering_code; + + if ($tmp != $obj->lettering_code || empty($obj->lettering_code)) + $var = ! $var; + + $solde += ($obj->credit - $obj->debit); + + print ""; + + if (empty($obj->lettering_code)) { + print '' . "\n"; + } else + print '' . "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + if (empty($obj->lettering_code)) { + print ''; + } else + print ''; - print "
 '; + $searchpicto=$form->showFilterButtons(); + print $searchpicto; + print '
'; + print img_edit(); + print ' ' . $obj->doc_type . '' . $obj->doc_type . '' . dol_print_date($db->jdate($obj->doc_date), 'day') . '' . $obj->doc_ref . '' . $obj->label_compte . '' . price($obj->debit) . '' . price($obj->credit) . '' . price($obj->montant) . '' . $obj->sens . '' . $obj->code_journal . '' . round($solde, 2) . '' . $obj->lettering_code . '
"; - print ''; - print ''; - print_liste_field_titre("Doctype", "liste.php", "bk.doc_type" ); - print_liste_field_titre("Docdate", "liste.php", "bk.doc_date" ); - print_liste_field_titre("Docref", "liste.php", "bk.doc_ref" ); -// print_liste_field_titre("Numerocompte", "liste.php", "bk.numero_compte" ); -// print_liste_field_titre("Code_tiers", "liste.php", "bk.code_tiers" ); - print_liste_field_titre("LabelAccount", "liste.php", "bk_label_compte" ); - print_liste_field_titre("Debit", "liste.php", "bk.debit" ); - print_liste_field_titre("Credit", "liste.php", "bk.credit" ); - print_liste_field_titre("Amount", "liste.php", "bk.montant" ); - print_liste_field_titre("Sens", "liste.php", "bk.sens" ); - print_liste_field_titre("Codejournal", "liste.php", "bk.code_journal" ); - print ''; - print ''; print "\n"; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $var = false; - - $debit = 0; - $credit = 0; - $solde = 0; - $tmp = ''; - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); - - if($tmp !=$obj->lettering || empty($tmp) ) - $tmp =$obj->lettering; - - if($tmp !=$obj->lettering || empty($obj->lettering)) - $var = ! $var; - - - $debit+= $obj->debit; - $credit+= $obj->credit; - - $solde+=($obj->credit-$obj->debit); - print ""; - - print ''; - if(empty($obj->lettering)){ - print '' . "\n"; - } - else - print '' . "\n"; - - - - print ''; - print ''; -// print ''; -// print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - if(empty($obj->lettering)){ - print ''; - } - else - print ''; - - print "\n"; - - $i ++; - } - - print ''; - - print '' . "\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print ""; - print '' . "\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print "
     '; - print ''; - print '   
' . $obj->rowid . ''; - print img_edit (); - print ' ' . $obj->doc_type . ''.$obj->doc_type . '' . dol_print_date ( $db->jdate ( $obj->doc_date ), 'day' ) . '' . $obj->doc_ref . '' . $obj->numero_compte . '' . $obj->code_tiers . '' . $obj->label_compte . '' . $obj->debit . '' . $obj->credit . '' . $obj->montant . '' . $obj->sens . '' . $obj->code_journal . '' . round($solde, 2) . '' . $obj->lettering . '
Mouvement totaux' . $debit . '' . $credit . ' 
Solde Comptable' . ($credit-$debit) . ' 
"; - - print ''; - print 'auto lettering'; - print ""; - $db->free ( $resql ); - } else { - dol_print_error ( $db ); } + print ''; + + print 'Mouvement totaux' . "\n"; + print '' . price($debit) . ''; + print '' . price($credit) . ''; + print ''; + print "\n"; + + print ""; + print 'Solde Comptable' . "\n"; + print '' . price($credit - $debit) . ''; + print ''; + print "\n"; + + print ""; + + print ''; + print ''.$langs->trans('AccountancyAutoLettering').''; + print ""; + $db->free($resql); +} else { + dol_print_error($db); +} // End of page llxFooter(); diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php index cb72c321118..41cce96995f 100644 --- a/htdocs/accountancy/class/accountingjournal.class.php +++ b/htdocs/accountancy/class/accountingjournal.class.php @@ -29,7 +29,7 @@ class AccountingJournal extends CommonObject public $element='accounting_journal'; public $table_element='accounting_journal'; public $fk_element = ''; - protected $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe var $rowid; diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 52f7a473bed..bb6f6949cbb 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -279,7 +279,7 @@ class BookKeeping extends CommonObject $sql .= ', entity'; $sql .= ") VALUES ("; $sql .= "'" . $this->db->idate($this->doc_date) . "'"; - $sql .= ",'" . $this->db->idate($this->date_lim_reglement) . "'"; + $sql .= ", ".(! isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'" . $this->db->idate($this->date_lim_reglement) . "'"); $sql .= ",'" . $this->db->escape($this->doc_type) . "'"; $sql .= ",'" . $this->db->escape($this->doc_ref) . "'"; $sql .= "," . $this->fk_doc; @@ -564,7 +564,8 @@ class BookKeeping extends CommonObject $sql .= " t.import_key,"; $sql .= " t.code_journal,"; $sql .= " t.journal_label,"; - $sql .= " t.piece_num"; + $sql .= " t.piece_num,"; + $sql .= " t.date_creation"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element.$mode. ' as t'; $sql .= ' WHERE 1 = 1'; $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; @@ -603,6 +604,7 @@ class BookKeeping extends CommonObject $this->code_journal = $obj->code_journal; $this->journal_label = $obj->journal_label; $this->piece_num = $obj->piece_num; + $this->date_creation = $this->db->jdate($obj->date_creation); } $this->db->free($resql); @@ -658,7 +660,8 @@ class BookKeeping extends CommonObject $sql .= " t.import_key,"; $sql .= " t.code_journal,"; $sql .= " t.journal_label,"; - $sql .= " t.piece_num"; + $sql .= " t.piece_num,"; + $sql .= " t.date_creation"; // Manage filter $sqlwhere = array (); if (count($filter) > 0) { @@ -675,6 +678,8 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; } elseif ($key == 't.label_operation') { $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; + } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') { + $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; } else { $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; } @@ -725,6 +730,7 @@ class BookKeeping extends CommonObject $line->code_journal = $obj->code_journal; $line->journal_label = $obj->journal_label; $line->piece_num = $obj->piece_num; + $line->date_creation = $obj->date_creation; $this->lines[] = $line; } @@ -777,7 +783,8 @@ class BookKeeping extends CommonObject $sql .= " t.import_key,"; $sql .= " t.code_journal,"; $sql .= " t.journal_label,"; - $sql .= " t.piece_num"; + $sql .= " t.piece_num,"; + $sql .= " t.date_creation"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; // Manage filter $sqlwhere = array (); @@ -793,6 +800,10 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key . '=' . $value; } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') { $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; + } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') { + $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + } elseif ($key == 't.tms>=' || $key == 't.tms<=') { + $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; } else { $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; } @@ -841,6 +852,7 @@ class BookKeeping extends CommonObject $line->code_journal = $obj->code_journal; $line->journal_label = $obj->journal_label; $line->piece_num = $obj->piece_num; + $line->date_creation = $obj->date_creation; $this->lines[] = $line; } @@ -1079,22 +1091,26 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return number <0 if KO, >0 if OK */ - public function updateByMvt($piece_num='', $field='', $value='', $mode='') { + public function updateByMvt($piece_num='', $field='', $value='', $mode='') + { + $error=0; + $this->db->begin(); + $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . $mode . " as ab"; $sql .= ' SET ab.' . $field . '=' . (is_numeric($value)?$value:"'".$value."'"); $sql .= ' WHERE ab.piece_num=' . $piece_num ; $resql = $this->db->query($sql); if (! $resql) { - $error ++; + $error++; $this->errors[] = 'Error ' . $this->db->lasterror(); dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); } if ($error) { $this->db->rollback(); - return - 1 * $error; + return -1 * $error; } else { $this->db->commit(); @@ -1332,6 +1348,7 @@ class BookKeeping extends CommonObject $this->code_journal = 'VT'; $this->journal_label = 'Journal de vente'; $this->piece_num = ''; + $this->date_creation = $now; } /** @@ -1344,7 +1361,7 @@ class BookKeeping extends CommonObject public function fetchPerMvt($piecenum, $mode='') { global $conf; - $sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type"; + $sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type,date_creation"; $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode; $sql .= " WHERE piece_num = " . $piecenum; $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; @@ -1360,6 +1377,7 @@ class BookKeeping extends CommonObject $this->doc_date = $this->db->jdate($obj->doc_date); $this->doc_ref = $obj->doc_ref; $this->doc_type = $obj->doc_type; + $this->date_creation = $obj->date_creation; } else { $this->error = "Error " . $this->db->lasterror(); dol_syslog(get_class($this) . "::" . __METHOD__ . $this->error, LOG_ERR); @@ -1410,7 +1428,7 @@ class BookKeeping extends CommonObject $sql = "SELECT rowid, doc_date, doc_type,"; $sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,"; $sql .= " numero_compte, label_compte, label_operation, debit, credit,"; - $sql .= " montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num"; + $sql .= " montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num, date_creation"; $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode; $sql .= " WHERE piece_num = " . $piecenum; $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; @@ -1443,6 +1461,7 @@ class BookKeeping extends CommonObject $line->code_journal = $obj->code_journal; $line->journal_label = $obj->journal_label; $line->piece_num = $obj->piece_num; + $line->date_creation = $obj->date_creation; $this->linesmvt[] = $line; } @@ -1521,11 +1540,16 @@ class BookKeeping extends CommonObject * @param string $piece_num Piece num * @return void */ - public function transformTransaction($direction=0,$piece_num='') { + public function transformTransaction($direction=0,$piece_num='') + { + $error = 0; + $this->db->begin(); - if ($direction==0) { + + if ($direction==0) + { $next_piecenum=$this->getNextNumMvt(); - if ($result < 0) { + if ($next_piecenum < 0) { $error++; } $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element.'(doc_date, doc_type,'; @@ -1776,4 +1800,5 @@ class BookKeepingLine public $code_journal; public $journal_label; public $piece_num; + public $date_creation; } diff --git a/htdocs/accountancy/class/lettering.class.php b/htdocs/accountancy/class/lettering.class.php index f3d9359b19d..81e0ad5e20e 100644 --- a/htdocs/accountancy/class/lettering.class.php +++ b/htdocs/accountancy/class/lettering.class.php @@ -18,321 +18,287 @@ */ /** - * \file accountancy/class/bookkeeping.class.php - * \ingroup Advanced accountancy - * \brief File of class for lettering + * \file accountancy/class/bookkeeping.class.php + * \ingroup Advanced accountancy + * \brief File of class for lettering */ - -include_once DOL_DOCUMENT_ROOT."/accountancy/class/bookkeeping.class.php"; -include_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"; -include_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; - +include_once DOL_DOCUMENT_ROOT . "/accountancy/class/bookkeeping.class.php"; +include_once DOL_DOCUMENT_ROOT . "/societe/class/societe.class.php"; +include_once DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php"; /** * Class lettering */ class lettering extends BookKeeping { - /** - * lettrageTiers - * - * @param int $socid Thirdparty id - * @return int <0 if KO, >0 if OK - */ + /** + * lettrageTiers + * + * @param int $socid Thirdparty id + * @return void + */ public function lettrageTiers($socid) { - $db = $this->db; $object = new Societe($this->db); $object->id = $socid; $object->fetch($socid); - - if( $object->code_compta == '411CUSTCODE') + if ($object->code_compta == '411CUSTCODE') { $object->code_compta = ''; - - if( $object->code_compta_fournisseur == '401SUPPCODE') - $object->code_compta_fournisseur = ''; - - - - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.lettering_code, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE code_journal = 'BQ' AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - - $sql .= " ) AND ( bk.date_lettering ='' OR bk.date_lettering IS NULL ) AND bk.lettering_code !='' "; - - $sql .= " GROUP BY bk.lettering_code "; - - - $resql = $db->query ( $sql ); - if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; - - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); - $i++; - - $sql = "SELECT bk.rowid "; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; - $sql .= " WHERE bk.lettering_code = '".$obj->lettering_code."' "; - $sql .= " AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) "; -// echo $sql; - $resql2 = $db->query ( $sql ); - if ($resql2) { - $num2 = $db->num_rows ( $resql2 ); - $i2 = 0; - $ids = array(); - while ( $i2 < $num2 ) { - $obj2 = $db->fetch_object ( $resql2 ); - $i2++; - $ids[] = $obj2->rowid; - } - - - if(count($ids) > 1 ){ - $result = $this->updatelettrage($ids); - - // var_dump($result); -// if( $result < 0 ){ -// setEventMessages('', $BookKeeping->errors, 'errors' ); -// $error++; -// -// } - } - } - } } + if ($object->code_compta_fournisseur == '401SUPPCODE') { + $object->code_compta_fournisseur = ''; + } /** - Prise en charge des lettering complexe avec prelevment , virement - */ - $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering, bu.url_id , bu.type "; + * Prise en charge des lettering complexe avec prelevment , virement + */ + $sql = "SELECT DISTINCT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.thirdparty_code, "; + $sql .= " bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant "; + $sql .= " , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering, bu.url_id , bu.type "; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url as bu ON(bk.fk_doc = bu.fk_bank AND bu.type IN ('payment', 'payment_supplier') ) "; - $sql .= " WHERE code_journal = 'BQ' AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) + $sql .= " WHERE ( "; + if (! empty($object->code_compta)) + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; + if (! empty($object->code_compta_fournisseur)) + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) AND date_lettering ='' "; - $sql .= " GROUP BY bk.lettering_code "; + $sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) "; + $sql .= " AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) "; + $sql .= $db->order('bk.doc_date', 'DESC'); -// echo $sql; -// - $resql = $db->query ( $sql ); + // echo $sql; + // + $resql = $db->query($sql); if ($resql) { - $num = $db->num_rows ( $resql ); - $i = 0; + $num = $db->num_rows($resql); - while ( $i < $num ) { - $obj = $db->fetch_object ( $resql ); + while ( $obj = $db->fetch_object($resql) ) { $ids = array(); - $i++; + $ids_fact = array(); - // print_r($obj); + if ($obj->type == 'payment_supplier') { - - - if($obj->type =='payment_supplier' ) { - $ids[] = $obj->rowid; - - $sql= 'SELECT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank '; - $sql.= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; - $sql.= " INNER JOIN " .MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = facf.ref) "; - // $sqlmid.= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as soc ON soc.rowid=facf.fk_soc"; - // $sqlmid.= " INNER JOIN " . MAIN_DB_PREFIX . "c_paiement as payc ON payc.id=payf.fk_paiement"; - $sql .= " WHERE 1 "; - $sql .= " AND fk_paiementfourn = '".$obj->url_id."' "; - // $sql .= " AND (bk.numero_compte = '" . $object->code_compta . "' OR bk.numero_compte = '" . $object->code_compta_fournisseur . "') "; - $sql .= " AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) "; - // echo $sql; - // exit; + $sql = 'SELECT DISTINCT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank, facf.rowid as fact_id'; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON (bk.fk_doc = payf.fk_bank AND bk.code_journal='" . $obj->code_journal . "')"; + $sql .= " WHERE payfacf.fk_paiementfourn = '" . $obj->url_id . "' "; + $sql .= " AND code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=4) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; } - elseif($obj->type =='payment' ){ - $ids[] = $obj->rowid; - - $sql= 'SELECT bk.rowid,fac.facnumber , pay.fk_bank '; - $sql.= " FROM " . MAIN_DB_PREFIX . "facture fac "; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; - $sql.= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; - $sql.= " INNER JOIN " .MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = fac.rowid) "; - $sql .= " WHERE 1 "; - $sql .= " AND payfac.fk_paiement = '".$obj->url_id."' "; - $sql .= " AND ( "; - if(!empty($object->code_compta) ) - $sql .= " bk.code_tiers = '" . $object->code_compta . "' "; - if(!empty($object->code_compta) && !empty($object->code_compta_fournisseur) ) - $sql .= " OR "; - if(!empty($object->code_compta_fournisseur) ) - $sql .= " bk.code_tiers = '" . $object->code_compta_fournisseur . "' "; - $sql .= " ) "; - - // echo $sql; + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - - - $resql2 = $db->query ( $sql ); + $resql2 = $db->query($sql); if ($resql2) { - $num2 = $db->num_rows ( $resql2 ); - $i2 = 0; - - while ( $i2 < $num2 ) { - $obj2 = $db->fetch_object ( $resql2 ); - $i2++; - $ids[] = $obj2->rowid; + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + $ids_fact[] = $obj2->fact_id; } - - // print_r($ids); - // exit; - if(count($ids) > 1 ){ - $result = $this->updatelettrage($ids); - - // var_dump($result); -// if( $result < 0 ){ -// setEventMessages('', $BookKeeping->errors, 'errors' ); -// $error++; -// -// } - } - - // exit; + } else { + $this->errors[] = $this->db->lasterror; + return - 1; } - } - } + if (count($ids_fact)) { + $sql = 'SELECT bk.rowid, facf.ref, facf.ref_supplier '; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = facf.rowid AND facf.rowid IN (" . implode(',', $ids_fact) . "))"; + $sql .= " WHERE bk.code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=3) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + } + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; + } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - return 1; - } + $resql2 = $db->query($sql); + if ($resql2) { + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + } + } else { + $this->errors[] = $this->db->lasterror; + return - 1; + } + } + } elseif ($obj->type == 'payment') { + $sql = 'SELECT DISTINCT bk.rowid, fac.ref, fac.ref, pay.fk_bank, fac.rowid as fact_id'; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON (bk.fk_doc = pay.fk_bank AND bk.code_journal='" . $obj->code_journal . "')"; + $sql .= " WHERE payfac.fk_paiement = '" . $obj->url_id . "' "; + $sql .= " AND bk.code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=4) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + } + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; + } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - public function updatelettrage($ids, $notrigger=false){ - $error = 0; + $resql2 = $db->query($sql); + if ($resql2) { + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + $ids_fact[] = $obj2->fact_id; + } + } else { + $this->errors[] = $this->db->lasterror; + return - 1; + } + if (count($ids_fact)) { + $sql = 'SELECT bk.rowid, fac.ref, fac.ref_supplier '; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk ON( bk.fk_doc = fac.rowid AND fac.rowid IN (" . implode(',', $ids_fact) . "))"; + $sql .= " WHERE code_journal IN (SELECT code FROM " . MAIN_DB_PREFIX . "accounting_journal WHERE nature=2) "; + $sql .= " AND ( "; + if (! empty($object->code_compta)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta . "' "; + } + if (! empty($object->code_compta) && ! empty($object->code_compta_fournisseur)) { + $sql .= " OR "; + } + if (! empty($object->code_compta_fournisseur)) { + $sql .= " bk.thirdparty_code = '" . $object->code_compta_fournisseur . "' "; + } + $sql .= " ) "; - $lettre=''; + $resql2 = $db->query($sql); + if ($resql2) { + while ( $obj2 = $db->fetch_object($resql2) ) { + $ids[$obj2->rowid] = $obj2->rowid; + } + } else { + $this->errors[] = $this->db->lasterror; + return - 1; + } + } + } - $sql = "SELECT lettering_code FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; - $sql .= " lettering_code != '' GROUP BY lettering_code ORDER BY lettering_code DESC limit 1; "; -// echo $sql; - $result = $this->db->query ( $sql ); - if ($result) { - $obj = $this->db->fetch_object ( $result ); - $lettre = (empty($obj->lettering_code)? 'AAA' : $obj->lettering_code ); - if(!empty($obj->lettering_code)) - $lettre++; - } - else{ - $this->errors[] = 'Error'.$this->db->lasterror();; - $error++; - } -// var_dump(__line__, $error); - - if (! $error) - { - $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; - $sql .= " rowid IN (".implode(',', $ids).") "; - $result = $this->db->query ( $sql ); - if ($result) { - $obj = $this->db->fetch_object ( $result ); - // print_r($obj); - if( !(round(abs($obj->deb),2) === round(abs($obj->cred),2)) ){ - // echo $sql; - // print_r($obj); - $this->errors[] = 'Total not exacts '.round(abs($obj->deb),2).' vs '. round(abs($obj->cred),2); - $error++; + if (count($ids) > 1) { + $result = $this->updatelettrage($ids); } } - else{ - $this->errors[] = 'Erreur sql'.$this->db->lasterror();; - $error++; - } } + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::" . __METHOD__ . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + return - 1 * $error; + } else { + return 1; + } + } + + /** + * + * @param array $ids ids array + * @param boolean $notrigger no trigger + * @return number + */ + public function updateLettrage($ids = array(), $notrigger = false) { + $error = 0; + + dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG); + + $sql = "SELECT DISTINCT lettering_code FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; + $sql .= " lettering_code != '' ORDER BY lettering_code DESC limit 1; "; + + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + $lettre = (empty($obj->lettering_code) ? 'AAA' : $obj->lettering_code); + if (! empty($obj->lettering_code)) + $lettre ++; + } else { + $this->errors[] = 'Error' . $this->db->lasterror(); + ; + $error ++; + } + + $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE "; + $sql .= " rowid IN (" . implode(',', $ids) . ") "; + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + if (! (round(abs($obj->deb), 2) === round(abs($obj->cred), 2))) { + $this->errors[] = 'Total not exacts ' . round(abs($obj->deb), 2) . ' vs ' . round(abs($obj->cred), 2); + $error ++; + } + } else { + $this->errors[] = 'Erreur sql' . $this->db->lasterror(); + ; + $error ++; + } + + // Update request $now = dol_now(); - // Update request - if (! $error) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET"; - $sql.= " lettering_code='".$lettre."'"; - $sql.= " , date_lettering = " .$now ; // todo correct date it's false - $sql.= " WHERE rowid IN (".implode(',', $ids).") "; - // echo $sql ; - // - // var_dump(__line__, $error); - // print_r($this->errors); - // exit; - $this->db->begin(); + $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET"; + $sql .= " lettering_code='" . $lettre . "'"; + $sql .= " , date_lettering = '" . $this->db->idate($now) . "'"; // todo correct date it's false + $sql .= " WHERE rowid IN (" . implode(',', $ids) . ") "; + $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); - $resql = $this->db->query($sql); - if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } - if (! $error) - { - if (! $notrigger) - { - // Uncomment this and change MYOBJECT to your own tag if you - // want this action calls a trigger. + if (! $error) { + if (! $notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. - //// Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers - } - } -// var_dump(__line__, $error); - - // 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(); -// echo $this->error; -// var_dump(__line__, $error); - return -1*$error; - } - else - { - $this->db->commit(); - return 1; + // // Call triggers + // include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + // $interface=new Interfaces($this->db); + // $result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + // if ($result < 0) { $error++; $this->errors=$interface->errors; } + // // End call triggers } } - 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; + } } - } diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index 0e3e71c1527..13602160c48 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -32,6 +32,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; // Langs $langs->load("bills"); @@ -51,6 +53,9 @@ $search_desc = GETPOST('search_desc', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', 'alpha'); +$search_day=GETPOST("search_day","int"); +$search_month=GETPOST("search_month","int"); +$search_year=GETPOST("search_year","int"); $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); @@ -95,6 +100,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_amount = ''; $search_account = ''; $search_vat = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; $search_country = ''; $search_tvaintra = ''; } @@ -131,6 +139,7 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { */ $form = new Form($db); +$formother = new FormOther($db); llxHeader('', $langs->trans("CustomersVentilation") . ' - ' . $langs->trans("Dispatched")); @@ -197,6 +206,19 @@ if (strlen(trim($search_account))) { if (strlen(trim($search_vat))) { $sql .= natural_search("fd.tva_tx", $search_vat); } +if ($search_month > 0) +{ + if ($search_year > 0 && empty($search_day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($search_year,$search_month,false))."' AND '".$db->idate(dol_get_last_day($search_year,$search_month,false))."'"; + else if ($search_year > 0 && ! empty($search_day)) + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $search_year))."'"; + else + $sql.= " AND date_format(f.datef, '%m') = '".$db->escape($search_month)."'"; +} +else if ($search_year > 0) +{ + $sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($search_year,1,false))."' AND '".$db->idate(dol_get_last_day($search_year,12,false))."'"; +} if (strlen(trim($search_country))) { $sql .= natural_search("co.label", $search_country); } @@ -237,6 +259,9 @@ if ($result) { $param .= "&search_account=" . $search_account; if ($search_vat) $param .= "&search_vat=" . $search_vat; + if ($search_day) $param.='&search_day='.urlencode($search_day); + if ($search_month) $param.='&search_month='.urlencode($search_month); + if ($search_year) $param.='&search_year='.urlencode($search_year); if ($search_country) $param .= "&search_country=" . $search_country; if ($search_tvaintra) @@ -267,7 +292,11 @@ if ($result) { print ''; print ''; print ''; - print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year,'search_year',1, 20, 5); + print ''; print ''; //print ''; print ''; diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index 51f62ecabf6..2d26a2d06d8 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -115,6 +115,7 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_amount = ''; $search_account = ''; $search_vat = ''; + $search_day = ''; $search_month = ''; $search_year = ''; } diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php index 156d80f09e4..750a5bc9f25 100644 --- a/htdocs/accountancy/expensereport/lines.php +++ b/htdocs/accountancy/expensereport/lines.php @@ -31,6 +31,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; // Langs $langs->load("compta"); @@ -50,6 +52,9 @@ $search_desc = GETPOST('search_desc', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', 'alpha'); +$search_day=GETPOST("search_day","int"); +$search_month=GETPOST("search_month","int"); +$search_year=GETPOST("search_year","int"); // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit', 'int'):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); @@ -90,6 +95,9 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_amount = ''; $search_account = ''; $search_vat = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; } if (is_array($changeaccount) && count($changeaccount) > 0) { @@ -123,6 +131,9 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { * View */ +$form = new Form($db); +$formother = new FormOther($db); + llxHeader('', $langs->trans("ExpenseReportsVentilation") . ' - ' . $langs->trans("Dispatched")); print ''; } - $ret.= ''; - $ret.= ''; - - $ret.=ajax_combobox('boxbookmark'); - - $ret.=''; - $ret .= ''; + $ret.= ''."\n"; return $ret; } diff --git a/htdocs/bookmarks/class/bookmark.class.php b/htdocs/bookmarks/class/bookmark.class.php index b72089e61b8..1beb4b36871 100644 --- a/htdocs/bookmarks/class/bookmark.class.php +++ b/htdocs/bookmarks/class/bookmark.class.php @@ -30,7 +30,7 @@ class Bookmark extends CommonObject { public $element='bookmark'; public $table_element='bookmark'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'bookmark'; var $db; diff --git a/htdocs/cashdesk/affPied.php b/htdocs/cashdesk/affPied.php index efe56ac2762..8f54dd732a7 100644 --- a/htdocs/cashdesk/affPied.php +++ b/htdocs/cashdesk/affPied.php @@ -24,17 +24,24 @@ ?>
-use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) { - print "\n\n"; + print "\n\n"; print '' . "\n"; + jQuery(".classfortooltip").tooltip({ + show: { collision: "flipfit", effect:\'toggle\', delay:50 }, + hide: { effect:\'toggle\', delay: 50 }, + tooltipClass: "mytooltip", + content: function () { + return $(this).prop(\'title\'); /* To force to get title as is */ + } + }); + }); + ' . "\n"; } printCommonFooter('private'); diff --git a/htdocs/cashdesk/class/Facturation.class.php b/htdocs/cashdesk/class/Facturation.class.php index b55524a874a..8bfd1d3082c 100644 --- a/htdocs/cashdesk/class/Facturation.class.php +++ b/htdocs/cashdesk/class/Facturation.class.php @@ -117,7 +117,7 @@ class Facturation } // Define part of HT, VAT, TTC - $resultarray=calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $use_npr, $product->type, $mysoc, $localtaxarray); + $resultarray=calcul_price_total($this->qte, $this->prix(), $this->remisePercent(), $txtva, -1, -1, 0, 'HT', $vat_npr, $product->type, $mysoc, $localtaxarray); // Calcul du total ht sans remise $total_ht = $resultarray[0]; @@ -207,6 +207,9 @@ class Facturation $total_ht=0; $total_ttc=0; + $total_vat = 0; + $total_localtax1 = 0; + $total_localtax2 = 0; $tab=array(); $tab = $_SESSION['poscart']; @@ -309,7 +312,7 @@ class Facturation public function ref($aRef=null) { - if ( !$aRef ) + if (is_null($aRef)) { return $this->ref; } @@ -330,9 +333,9 @@ class Facturation * @param int $aQte Qty * @return int Qty */ - public function qte( $aQte=null ) + public function qte($aQte=null) { - if ( !$aQte ) + if (is_null($aQte)) { return $this->qte; } @@ -357,7 +360,7 @@ class Facturation public function stock($aStock=null) { - if ( !$aStock ) + if (is_null($aStock)) { return $this->stock; } @@ -381,7 +384,7 @@ class Facturation public function remisePercent($aRemisePercent=null) { - if ( !$aRemisePercent ) + if (is_null($aRemisePercent)) { return $this->remise_percent; } @@ -405,7 +408,7 @@ class Facturation public function montantRemise($aMontantRemise=null) { - if ( !$aMontantRemise ) { + if (is_null($aMontantRemise)) { return $this->montant_remise; @@ -427,10 +430,10 @@ class Facturation * @param int $aPrix Price * @return string Stock */ - public function prix ( $aPrix=null ) + public function prix($aPrix=null) { - if ( !$aPrix ) { + if (is_null($aPrix)) { return $this->prix; @@ -454,7 +457,7 @@ class Facturation */ public function tva($aTva=null) { - if ( !$aTva ) { + if (is_null($aTva)) { return $this->tva; @@ -478,7 +481,7 @@ class Facturation */ public function numInvoice($aNumFacture=null) { - if ( !$aNumFacture ) { + if (is_null($aNumFacture)) { return $this->num_facture; @@ -499,10 +502,10 @@ class Facturation * @param int $aModeReglement Payment mode * @return int Payment mode */ - public function getSetPaymentMode( $aModeReglement=null ) + public function getSetPaymentMode($aModeReglement=null) { - if ( !$aModeReglement ) { + if (is_null($aModeReglement)) { return $this->mode_reglement; @@ -524,10 +527,10 @@ class Facturation * @param int $aMontantEncaisse Amount * @return int Amount */ - public function montantEncaisse( $aMontantEncaisse=null ) + public function montantEncaisse($aMontantEncaisse=null) { - if ( !$aMontantEncaisse ) { + if (is_null($aMontantEncaisse)) { return $this->montant_encaisse; @@ -549,10 +552,10 @@ class Facturation * @param int $aMontantRendu Amount * @return int Amount */ - public function montantRendu( $aMontantRendu=null ) + public function montantRendu($aMontantRendu=null) { - if ( !$aMontantRendu ) { + if (is_null($aMontantRendu)) { return $this->montant_rendu; } else if ( $aMontantRendu == 'RESET' ) { @@ -573,9 +576,9 @@ class Facturation * @param date $aPaiementLe Date * @return date Date */ - public function paiementLe( $aPaiementLe=null ) + public function paiementLe($aPaiementLe=null) { - if ( !$aPaiementLe ) { + if (is_null($aPaiementLe)) { return $this->paiement_le; @@ -596,9 +599,9 @@ class Facturation * @param int $aTotalHt Total amount * @return int Total amount */ - public function prixTotalHt( $aTotalHt=null ) + public function prixTotalHt($aTotalHt=null) { - if ( !$aTotalHt ) { + if (is_null($aTotalHt)) { return $this->prix_total_ht; @@ -619,9 +622,9 @@ class Facturation * @param int $aMontantTva Amount vat * @return int Amount vat */ - public function montantTva( $aMontantTva=null ) + public function montantTva($aMontantTva=null) { - if ( !$aMontantTva ) { + if (is_null($aMontantTva)) { return $this->montant_tva; @@ -643,9 +646,9 @@ class Facturation * @param int $aTotalTtc Amount ttc * @return int Amount ttc */ - public function prixTotalTtc( $aTotalTtc=null ) + public function prixTotalTtc($aTotalTtc=null) { - if ( !$aTotalTtc ) + if (is_null($aTotalTtc)) { return $this->prix_total_ttc; } diff --git a/htdocs/categories/admin/categorie_extrafields.php b/htdocs/categories/admin/categorie_extrafields.php index c72ef73e970..c20dff5db42 100644 --- a/htdocs/categories/admin/categorie_extrafields.php +++ b/htdocs/categories/admin/categorie_extrafields.php @@ -37,7 +37,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index 1c8d9fcfe50..edbc4fa68ce 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -103,7 +103,7 @@ class Categories extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type = '', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 6242691d1f1..2e69626c1aa 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -163,7 +163,7 @@ class Categorie extends CommonObject */ public $socid; /** - * @var int Category type + * @var string Category type * * @see Categorie::TYPE_PRODUCT * @see Categorie::TYPE_SUPPLIER @@ -766,12 +766,10 @@ class Categorie extends CommonObject // For backward compatibility if ($type == 'societe') { $type = 'customer'; - dol_syslog( get_class( $this ) . "::del_type(): type 'societe' is deprecated, please use 'customer' instead", - LOG_WARNING ); + dol_syslog( get_class( $this ) . "::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING); } elseif ($type == 'fournisseur') { $type = 'supplier'; - dol_syslog( get_class( $this ) . "::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", - LOG_WARNING ); + dol_syslog( get_class( $this ) . "::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING); } $this->db->begin(); @@ -1327,6 +1325,7 @@ class Categorie extends CommonObject { $w = array(); $i = 0; + $forced_color=''; foreach ($way as $cat) { $i++; @@ -1340,12 +1339,7 @@ class Categorie extends CommonObject $forced_color='categtextwhite'; if ($cat->color) { - $hex=$cat->color; - $r = hexdec($hex[0].$hex[1]); - $g = hexdec($hex[2].$hex[3]); - $b = hexdec($hex[4].$hex[5]); - $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright >= 0.5) $forced_color='categtextblack'; // Higher than 60% + if (colorIsLight($cat->color)) $forced_color='categtextblack'; } } } @@ -1602,12 +1596,7 @@ class Categorie extends CommonObject $forced_color='categtextwhite'; if ($this->color) { - $hex=$this->color; - $r = hexdec($hex[0].$hex[1]); - $g = hexdec($hex[2].$hex[3]); - $b = hexdec($hex[4].$hex[5]); - $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright >= 0.5) $forced_color='categtextblack'; // Higher than 60% + if (colorIsLight($this->color)) $forced_color='categtextblack'; } $link = ''; diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index a3ca8053281..daa5ade05b5 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -88,13 +88,13 @@ if ($id > 0 && $removeelem > 0) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); - $elementtype = 'fournisseur'; + $elementtype = 'supplier'; } else if ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); - $elementtype = 'societe'; + $elementtype = 'customer'; } else if ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) { diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index 3cba48cfc07..2c056cd0e07 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -36,7 +36,7 @@ if (! $user->admin) accessforbidden(); if (! ((GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))) { - $conf->dol_hide_leftmenu = 1; // Force hide of left menu. + $conf->dol_hide_leftmenu = 1; // Force hide of left menu. } $error=0; @@ -71,33 +71,33 @@ if (GETPOST('refreshpage')) $action='preview'; // Add a collab page if ($action == 'add') { - $db->begin(); + $db->begin(); - $objectpage->title = GETPOST('WEBSITE_TITLE'); - $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); + $objectpage->title = GETPOST('WEBSITE_TITLE'); + $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); - if (empty($objectpage->title)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); - $error++; - } + if (empty($objectpage->title)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); + $error++; + } - if (! $error) - { - $res = $objectpage->create($user); - if ($res <= 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - } + if (! $error) + { + $res = $objectpage->create($user); + if ($res <= 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } + } if (! $error) { $db->commit(); - setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); - $action=''; + setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); + $action=''; } else { @@ -111,38 +111,38 @@ if ($action == 'add') // Update page if ($action == 'delete') { - $db->begin(); + $db->begin(); - $res = $object->fetch(0, $website); + $res = $object->fetch(0, $website); - $res = $objectpage->fetch($pageid, $object->fk_website); + $res = $objectpage->fetch($pageid, $object->fk_website); - if ($res > 0) - { - $res = $objectpage->delete($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } + if ($res > 0) + { + $res = $objectpage->delete($user); + if (! $res > 0) + { + $error++; + setEventMessages($objectpage->error, $objectpage->errors, 'errors'); + } - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); - header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); - exit; - } - else - { - $db->rollback(); - } - } - else - { - dol_print_error($db); - } + header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website); + exit; + } + else + { + $db->rollback(); + } + } + else + { + dol_print_error($db); + } } @@ -155,13 +155,13 @@ $form = new Form($db); $help_url=''; -llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', ''."\n".'
'); +llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', '', ''."\n".'
'); print "\n".'
'; print ''; if ($action == 'create') { - print ''; + print ''; } @@ -174,225 +174,225 @@ print '
'; if (count($object->records) > 0) { - // ***** Part for web sites + // ***** Part for web sites - print '
'; - print $langs->trans("Website").': '; - print '
'; + print '
'; + print $langs->trans("WebSite").': '; + print '
'; - // List of websites - print '
'; - $out=''; - $out.=''; + if (empty($object->records)) $out.=''; + // Loop on each sites + $i=0; + foreach($object->records as $key => $valwebsite) + { + if (empty($website)) $website=$valwebsite->ref; - $out.=''; - $i++; - } - $out.=''; - $out.=ajax_combobox('website'); - print $out; - print ''; + $out.=''; + $i++; + } + $out.=''; + $out.=ajax_combobox('website'); + print $out; + print ''; - if ($website) - { - $virtualurl=''; - $dataroot=DOL_DATA_ROOT.'/websites/'.$website; - if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; - } + if ($website) + { + $virtualurl=''; + $dataroot=DOL_DATA_ROOT.'/collab/'.$website; + if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; + } - if ($website && $action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; + if ($website && $action == 'preview') + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - print '   '; + print '   '; - //print ''; - print ''; - print ''; - print ''; - } + //print ''; + print ''; + print ''; + print ''; + } - print '
'; + print '
'; - // Button for websites - print '
'; + // Button for websites + print '
'; - if ($action == 'preview') - { - print '
'; - print ''; - //print ''; - $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); - print $form->textwithpicto('', $htmltext); - print '
'; + if ($action == 'preview') + { + print '
'; + print ''; + //print ''; + $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); + print $form->textwithpicto('', $htmltext); + print '
'; - $urlext=$virtualurl; - $urlint=$urlwithroot.'/public/websites/index.php?website='.$website; - //if (! empty($object->virtualhost)) - //{ - print '
transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - //} + $urlext=$virtualurl; + $urlint=$urlwithroot.'/public/collab/index.php?website='.$website; + //if (! empty($object->virtualhost)) + //{ + print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + //} - print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); - print ''; - } + print 'transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview'); + print ''; + } - if (in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } + if (in_array($action, array('editcss','editmenu','create'))) + { + if ($action != 'preview') print ''; + if (preg_match('/^create/',$action)) print ''; + if (preg_match('/^edit/',$action)) print ''; + } - print '
'; + print '
'; - // ***** Part for pages + // ***** Part for pages - if ($website) - { - print '
'; + if ($website) + { + print '
'; - $array=$objectpage->fetchAll($object->id); - if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); - $atleastonepage=(is_array($array) && count($array) > 0); + $array=$objectpage->fetchAll($object->id); + if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + $atleastonepage=(is_array($array) && count($array) > 0); - print '
'; - print '
'; - print $langs->trans("Page").': '; - print '
'; - print '
'; + print '
'; + print '
'; + print $langs->trans("Page").': '; + print '
'; + print '
'; - if ($action != 'add') - { - $out=''; - $out.=''; + if ($atleastonepage) + { + if (empty($pageid) && $action != 'create') // Page id is not defined, we try to take one + { + $firstpageid=0;$homepageid=0; + foreach($array as $key => $valpage) + { + if (empty($firstpageid)) $firstpageid=$valpage->id; + if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid=$valpage->id; + } + $pageid=$homepageid?$homepageid:$firstpageid; // We choose home page and if not defined yet, we take first page + } - foreach($array as $key => $valpage) - { - $out.=''; - } - } - else $out.=''; - $out.=''; - $out.=ajax_combobox('pageid'); - print $out; - } - else - { - print $langs->trans("New"); - } + foreach($array as $key => $valpage) + { + $out.=''; + } + } + else $out.=''; + $out.=''; + $out.=ajax_combobox('pageid'); + print $out; + } + else + { + print $langs->trans("New"); + } - print ''; - //print $form->selectarray('page', $array); + print ''; + //print $form->selectarray('page', $array); - if ($action == 'preview') - { - $disabled=''; - if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; + if ($action == 'preview') + { + $disabled=''; + if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"'; - if ($pageid > 0) - { - print '   '; + if ($pageid > 0) + { + print '   '; - if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; - else print ''; - print ''; - print ''; - //print ''.dol_escape_htmltag($langs->trans("EditPageMeta")).''; - //print ''.dol_escape_htmltag($langs->trans("EditPageContent")).''; - print ''; - } - } + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; + else print ''; + print ''; + print ''; + //print ''.dol_escape_htmltag($langs->trans("EditPageMeta")).''; + //print ''.dol_escape_htmltag($langs->trans("EditPageContent")).''; + print ''; + } + } - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print '
'; + print '
'; - if ($website && $pageid > 0 && $action == 'preview') - { - $websitepage = new WebSitePage($db); - $websitepage->fetch($pageid); + if ($website && $pageid > 0 && $action == 'preview') + { + $websitepage = new WebSitePage($db); + $websitepage->fetch($pageid); - $realpage=$urlwithroot.'/public/websites/index.php?website='.$website.'&page='.$pageid; - $pagealias = $websitepage->pageurl; + $realpage=$urlwithroot.'/public/collab/index.php?website='.$website.'&page='.$pageid; + $pagealias = $websitepage->pageurl; - print '
'; - print ''; - //print ''; - $htmltext=$langs->trans("WEBSITE_PAGENAME", $pagealias); - print $form->textwithpicto('', $htmltext); - print '
'; + print '
'; + print ''; + //print ''; + $htmltext=$langs->trans("WEBSITE_PAGENAME", $pagealias); + print $form->textwithpicto('', $htmltext); + print '
'; - if (! empty($object->virtualhost)) - { - $urlext=$virtualurl.'/'.$pagealias.'.php'; - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } - else - { - print ''; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); - print ''; - } + if (! empty($object->virtualhost)) + { + $urlext=$virtualurl.'/'.$pagealias.'.php'; + print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + } + else + { + print ''; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext?$urlext:$langs->trans("VirtualHostUrlNotDefined")), 1, 'preview_ext'); + print ''; + } - print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; - print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); - print ''; // View page in new Tab - //print ''; + print 'transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">'; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview'); + print ''; // View page in new Tab + //print ''; - // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext - } - if (! in_array($action, array('editcss','editmenu','create'))) - { - if ($action != 'preview') print ''; - if (preg_match('/^create/',$action)) print ''; - if (preg_match('/^edit/',$action)) print ''; - } + // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext + } + if (! in_array($action, array('editcss','editmenu','create'))) + { + if ($action != 'preview') print ''; + if (preg_match('/^create/',$action)) print ''; + if (preg_match('/^edit/',$action)) print ''; + } - print '
'; + print '
'; - if ($action == 'preview') - { - // Adding jquery code to change on the fly url of preview ext - if (! empty($conf->use_javascript_ajax)) - { - print ''; - } - } - } + } + } + } } else { - print '
'; - $langs->load("errors"); - print $langs->trans("ErrorModuleSetupNotComplete"); - print '
'; - $action=''; + print '
'; + $langs->load("errors"); + print $langs->trans("ErrorModuleSetupNotComplete"); + print '
'; + $action=''; } @@ -437,21 +437,21 @@ $head = array(); if ($action == 'editcontent') { - /* + /* * Editing global variables not related to a specific theme */ - $csscontent = @file_get_contents($filecss); + $csscontent = @file_get_contents($filecss); - $contentforedit = ''; - /*$contentforedit.=''."\n";*/ - $contentforedit .= $objectpage->content; + $contentforedit .= $objectpage->content; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); - $doleditor->Create(0, '', false); + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%'); + $doleditor->Create(0, '', false); } print "
\n\n"; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index c8b92acd5fc..15218406a94 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -199,8 +199,8 @@ if ($action == 'add') $percentage=in_array(GETPOST('status'),array(-1,100))?GETPOST('status'):(in_array(GETPOST('complete'),array(-1,100))?GETPOST('complete'):GETPOST("percentage")); // If status is -1 or 100, percentage is not defined and we must use status // Clean parameters - $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour"), $fulldayevent?'00':GETPOST("apmin"), 0, GETPOST("apmonth"), GETPOST("apday"), GETPOST("apyear")); - $datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour"), $fulldayevent?'59':GETPOST("p2min"), $fulldayevent?'59':'0', GETPOST("p2month"), GETPOST("p2day"), GETPOST("p2year")); + $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour",'int'), $fulldayevent?'00':GETPOST("apmin",'int'), $fulldayevent?'00':GETPOST("apsec",'int'), GETPOST("apmonth",'int'), GETPOST("apday",'int'), GETPOST("apyear",'int')); + $datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour",'int'), $fulldayevent?'59':GETPOST("p2min",'int'), $fulldayevent?'59':GETPOST("apsec",'int'), GETPOST("p2month",'int'), GETPOST("p2day",'int'), GETPOST("p2year",'int')); // Check parameters if (! $datef && $percentage == 100) @@ -577,7 +577,7 @@ if ($action == 'mupdate') // Actions to delete doc $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); -$permissioncreate = ($user->rights->agenda->allactions->delete || (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->delete)); +$permissioncreate = ($user->rights->agenda->allactions->create || (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->read)); include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; @@ -1478,8 +1478,8 @@ if ($id > 0) $filedir=$conf->agenda->multidir_output[$conf->entity].'/'.$object->id; $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->agenda->myactions->create; - $delallowed=$user->rights->agenda->myactions->delete; + $genallowed=$user->rights->agenda->myactions->read; + $delallowed=$user->rights->agenda->myactions->create; $var=true; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 12c11f863f1..a66a4635281 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -2,8 +2,8 @@ /* Copyright (C) 2002-2004 Rodolphe Quiedeville * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2015 Marcos García + * Copyright (C) 2011-2017 Juanjo Menent + * Copyright (C) 2015 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -36,7 +36,7 @@ class ActionComm extends CommonObject public $element='action'; public $table_element = 'actioncomm'; public $table_rowid = 'id'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='action'; /** @@ -907,7 +907,7 @@ class ActionComm extends CommonObject return $db->lasterror(); } } - + /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * @@ -918,7 +918,7 @@ class ActionComm extends CommonObject function load_board($user, $load_state_board=0) { global $conf, $langs; - + if(empty($load_state_board)) $sql = "SELECT a.id, a.datep as dp"; else { $this->nb=array(); @@ -928,13 +928,13 @@ class ActionComm extends CommonObject $sql.= ")"; if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; - $sql.= " WHERE 1"; + $sql.= " WHERE 1 = 1"; if(empty($load_state_board)) $sql.= " AND a.percent >= 0 AND a.percent < 100"; $sql.= " AND a.entity IN (".getEntity('agenda').")"; if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")"; if ($user->societe_id) $sql.=" AND a.fk_soc = ".$user->societe_id; if (! $user->rights->agenda->allactions->read) $sql.= " AND (a.fk_user_author = ".$user->id . " OR a.fk_user_action = ".$user->id . " OR a.fk_user_done = ".$user->id . ")"; - + $resql=$this->db->query($sql); if ($resql) { @@ -956,7 +956,7 @@ class ActionComm extends CommonObject if ($agenda_static->hasDelay()) $response->nbtodolate++; } else $this->nb["actionscomm"]=$obj->nb; } - + $this->db->free($resql); if(empty($load_state_board)) return $response; else return 1; @@ -1135,7 +1135,6 @@ class ActionComm extends CommonObject if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL'); } - $tooltip = '' . $langs->trans('ShowAction'.$objp->code) . ''; if (! empty($this->ref)) $tooltip .= '
' . $langs->trans('Ref') . ': ' . $this->ref; @@ -1204,10 +1203,13 @@ class ActionComm extends CommonObject { $libelle.=(($this->type_code && $libelle!=$langs->transnoentities("Action".$this->type_code) && $langs->transnoentities("Action".$this->type_code)!="Action".$this->type_code)?' ('.$langs->transnoentities("Action".$this->type_code).')':''); } - $result.=$linkstart.img_object(($notooltip?'':$langs->trans("ShowAction").': '.$libelle), ($overwritepicto?$overwritepicto:'action'), ($notooltip?'class="valigntextbottom"':'class="classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1).$linkend; } - if ($withpicto==1) $result.=' '; - $result.=$linkstart.$libelleshort.$linkend; + + $result.=$linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$langs->trans("ShowAction").': '.$libelle), ($overwritepicto?$overwritepicto:'action'), ($notooltip?'class="'.(($withpicto != 2) ? 'paddingright ' : '').'valigntextbottom"':'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1); + $result.=$libelleshort; + $result.=$linkend; + return $result; } @@ -1341,6 +1343,7 @@ class ActionComm extends CommonObject { // Note: Output of sql request is encoded in $conf->file->character_set_client // This assignment in condition is not a bug. It allows walking the results. + $diff = 0; while ($obj=$this->db->fetch_object($resql)) { $qualified=true; @@ -1375,8 +1378,9 @@ class ActionComm extends CommonObject if ($qualified && $datestart) { - $eventarray[$datestart]=$event; + $eventarray[]=$event; } + $diff++; } } else @@ -1528,10 +1532,18 @@ class ActionComm extends CommonObject return 0; } + $now = dol_now(); + dol_syslog(__METHOD__, LOG_DEBUG); + // TODO Scan events of type 'email' into table llx_actioncomm_reminder with status todo, send email, then set status to done + + // 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 WHERE dateremind < '".$this->db->jdate($now - (3600 * 24 * 32))."'"; + $this->db->query($sql); + return 0; } diff --git a/htdocs/comm/action/class/actioncommreminder.class.php b/htdocs/comm/action/class/actioncommreminder.class.php new file mode 100644 index 00000000000..4873db461f6 --- /dev/null +++ b/htdocs/comm/action/class/actioncommreminder.class.php @@ -0,0 +1,229 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/actioncommreminder.class.php + * \ingroup agenda + * \brief This file is a CRUD class file for ActionCommReminder (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; + + +/** + * Class for ActionCommReminder + */ +class ActionCommReminder extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'actioncomm_reminder'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'actioncomm_reminder'; + /** + * @var array Does actioncommreminder support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 0; + /** + * @var string String with name of icon for actioncommreminder. Must be the part after the 'object_' into object_actioncommreminder.png + */ + public $picto = 'generic'; + + + /** + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * '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. Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * '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_...). + * 'position' is the sort order of field. + * '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). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * 'showoncombobox' if field must be shown into the label of combobox + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), + 'dateremind' => array('type'=>'datetime', 'label'=>'DateRemind', 'visible'=>1, 'enabled'=>1, 'position'=>60, 'notnull'=>1, 'index'=>1,), + 'typeremind' => array('type'=>'varchar(32)', 'label'=>'TypeRemind', 'visible'=>-1, 'enabled'=>1, 'position'=>55, 'notnull'=>1, 'comment'=>"email, browser, sms",), + 'fk_user' => array('type'=>'integer', 'label'=>'User', 'visible'=>-1, 'enabled'=>1, 'position'=>65, 'notnull'=>1, 'index'=>1,), + 'offsetvalue' => array('type'=>'integer', 'label'=>'OffsetValue', 'visible'=>1, 'enabled'=>1, 'position'=>56, 'notnull'=>1,), + 'offsetunit' => array('type'=>'varchar(1)', 'label'=>'OffsetUnit', 'visible'=>1, 'enabled'=>1, 'position'=>57, 'notnull'=>1, 'comment'=>"m, h, d, w",), + 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'default'=>0, 'index'=>0, 'arrayofkeyval'=>array('0'=>'ToDo', '1'=>'Done')), + ); + public $rowid; + public $dateremind; + public $typeremind; + public $fk_user; + public $offsetvalue; + public $offsetunit; + public $status; + // END MODULEBUILDER PROPERTIES + + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + return $result; + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * Retourne le libelle du status d'un user (actif, inactif) + * + * @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 + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + if ($mode == 0) + { + $prefix=''; + if ($status == 1) return $langs->trans('Done'); + if ($status == 0) return $langs->trans('ToDo'); + } + if ($mode == 1) + { + if ($status == 1) return $langs->trans('Done'); + if ($status == 0) return $langs->trans('ToDo'); + } + if ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Done'),'statut4').' '.$langs->trans('Done'); + if ($status == 0) return img_picto($langs->trans('ToDo'),'statut5').' '.$langs->trans('ToDo'); + } + if ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Done'),'statut4'); + if ($status == 0) return img_picto($langs->trans('ToDo'),'statut5'); + } + if ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Done'),'statut4').' '.$langs->trans('Done'); + if ($status == 0) return img_picto($langs->trans('ToDo'),'statut5').' '.$langs->trans('ToDo'); + } + if ($mode == 5) + { + if ($status == 1) return $langs->trans('Done').' '.img_picto($langs->trans('Done'),'statut4'); + if ($status == 0) return $langs->trans('ToDo').' '.img_picto($langs->trans('ToDo'),'statut5'); + } + if ($mode == 6) + { + if ($status == 1) return $langs->trans('Done').' '.img_picto($langs->trans('Done'),'statut4'); + if ($status == 0) return $langs->trans('ToDo').' '.img_picto($langs->trans('ToDo'),'statut5'); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + +} + diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 68a36844e39..981ae1025cf 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -75,7 +75,7 @@ if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="name"; $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); -$modulepart='contract'; +$modulepart='actions'; /* diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index bda7dd7a594..7004457b97d 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -1364,7 +1364,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '>'; print ' $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); @@ -87,7 +87,7 @@ if ($action != 'create' && $action != 'edit') /* ************************************************************************** */ /* */ -/* Creation of an optional field */ +/* Creation of an optional field */ /* */ /* ************************************************************************** */ diff --git a/htdocs/comm/admin/propaldet_extrafields.php b/htdocs/comm/admin/propaldet_extrafields.php index 80f5afdaeed..270274327e6 100644 --- a/htdocs/comm/admin/propaldet_extrafields.php +++ b/htdocs/comm/admin/propaldet_extrafields.php @@ -45,7 +45,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 1b3d231382c..8fb590d61b4 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -186,8 +186,12 @@ if (empty($reshook)) if ($ret < 0) $error++; if (! $error) { - $result = $object->insertExtraFields(); - if ($result < 0) $error++; + $result = $object->insertExtraFields(); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } if ($error) $action = 'edit_extras'; } diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index 5a5ef5fa90c..cdfd3e526cd 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -224,6 +224,8 @@ if ($object->fetch($id) >= 0) dol_fiche_end(); + print '
'; + $allowaddtarget=($object->statut == 0); diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 35767c16167..63a12e5d25a 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -44,6 +44,7 @@ require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/modules/propale/modules_propale.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/propal.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/signature.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; if (! empty($conf->projet->enabled)) { @@ -612,14 +613,14 @@ if (empty($reshook)) // Close proposal else if ($action == 'setstatut' && $user->rights->propal->cloturer && ! GETPOST('cancel','alpha')) { - if (! GETPOST('statut')) { + if (! GETPOST('statut','int')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CloseAs")), null, 'errors'); $action = 'statut'; } else { // prevent browser refresh from closing proposal several times if ($object->statut == Propal::STATUS_VALIDATED) { - $result=$object->cloture($user, GETPOST('statut','int'), GETPOST('note_private','alpha')); + $result=$object->cloture($user, GETPOST('statut','int'), GETPOST('note_private','none')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -1175,7 +1176,11 @@ if (empty($reshook)) if (! $error) { $result = $object->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } if ($error) $action = 'edit_extras'; } @@ -1687,8 +1692,8 @@ if ($action == 'create') //Form to close proposal (signed or not) $formquestion = array( array('type' => 'select','name' => 'statut','label' => $langs->trans("CloseAs"),'values' => array(2=>$object->labelstatut [2],3=>$object->labelstatut [3])), - //array('type' => 'other','name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '')); - array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => $object->note_private)); + array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '') // Field to complete private note (not replace) + ); if (! empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; @@ -2190,7 +2195,7 @@ if ($action == 'create') // Show object lines $result = $object->getLinesArray(); - print ' + print ' @@ -2284,6 +2289,14 @@ if ($action == 'create') } } + // Create an intervention + if (! empty($conf->service->enabled) && ! empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) { + if ($user->rights->ficheinter->creer) { + $langs->load("interventions"); + print ''; + } + } + // Create contract if ($conf->contrat->enabled && $object->statut == Propal::STATUS_SIGNED) { $langs->load("contracts"); @@ -2343,8 +2356,8 @@ if ($action == 'create') $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->propal->dir_output . "/" . dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->propal->creer; - $delallowed = $user->rights->propal->supprimer; + $genallowed = $user->rights->propal->lire; + $delallowed = $user->rights->propal->creer; $var = true; @@ -2354,6 +2367,15 @@ if ($action == 'create') $linktoelem = $form->showLinkToObjectBlock($object, null, array('propal')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show online signature link + $useonlinepayment = $conf->global->MAIN_FEATURES_LEVEL; + + if ($object->statut != Propal::STATUS_DRAFT && $useonlinepayment) + { + print '
'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + print showOnlineSignatureUrl('proposal', $object->ref); + } print '
'; diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 325fad1a326..364f63bd4e4 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -90,11 +90,11 @@ class Proposals extends DolibarrApi * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter commercial proposal of. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} + * @param string $thirdparty_ids Thirdparty ids to filter commercial proposal of. Example: '1' or '1,2,3' {@pattern /^2|3$/i} * @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 order objects */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -257,39 +257,39 @@ class Proposals extends DolibarrApi $request_data = (object) $request_data; - $updateRes = $this->propal->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - 'HT', - 0, - $request_data->info_bits, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->date_start, - $request_data->date_end, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id, - $request_data->multicurrency_subprice, - $request_data->fk_remise_except - ); - - if ($updateRes > 0) { - return $this->get($id)->line->rowid; + $updateRes = $this->propal->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + 'HT', + 0, + $request_data->info_bits, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->date_start, + $request_data->date_end, + $request_data->array_options, + $request_data->fk_unit, + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice, + $request_data->fk_remise_except + ); + if ($updateRes > 0) { + return $updateRes; } + return false; } @@ -507,6 +507,49 @@ class Proposals extends DolibarrApi ); } + /** + * Close (Accept or refuse) a quote / commercial proposal + * + * @param int $id Commercial proposal ID + * @param int $status Must be 2 (accepted) or 3 (refused) {@min 2}{@max 3} + * @param string $note_private Add this mention at end of private note + * @param int $notrigger Disabled triggers + * + * @url POST {id}/close + * + * @return array + */ + function close($id, $status, $note_private='', $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Commercial Proposal not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->propal->cloture(DolibarrApiAccess::$user, $status, $note_private, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Commercial Proposal: '.$this->propal->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal closed (Ref='.$this->propal->ref.')' + ) + ); + } + + /** * Validate fields before create or update object * @@ -526,6 +569,7 @@ class Proposals extends DolibarrApi return $propal; } + /** * Clean sensible object datas * diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index cd5f81783b7..b94045ee747 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -48,7 +48,7 @@ class Propal extends CommonObject public $table_element='propal'; public $table_element_line='propaldet'; public $fk_element='fk_propal'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='propal'; /** @@ -569,28 +569,33 @@ class Propal extends CommonObject // Reorder if child line if (! empty($fk_parent_line)) $this->line_order(true,'DESC'); - // Mise a jour informations denormalisees au niveau de la propale meme - $result=$this->update_price(1,'auto',0,$mysoc); // 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->rowid; - } - else - { - $this->error=$this->db->error(); - $this->db->rollback(); - return -1; - } - } - else - { - $this->error=$this->line->error; - $this->db->rollback(); - return -2; - } + // Mise a jour informations denormalisees au niveau de la propale meme + $result=$this->update_price(1,'auto',0,$mysoc); // 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->rowid; + } + else + { + $this->error=$this->db->error(); + $this->db->rollback(); + return -1; + } + } + else + { + $this->error=$this->line->error; + $this->db->rollback(); + return -2; + } + } + else + { + dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); + return -3; } - } + } /** @@ -955,13 +960,55 @@ class Propal extends CommonObject $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 + } + + // 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) + { + $this->error=$this->db->lasterror(); + $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) + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + } + + // Add linked object (deprecated, use ->linkedObjectsIds instead) + if (! $error && $this->origin && $this->origin_id) + { + $ret = $this->add_object_linked(); + if (! $ret) dol_print_error($this->db); + } + + /* * 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++) { @@ -1252,7 +1299,7 @@ class Propal extends CommonObject $sql.= ", p.datep as dp"; $sql.= ", p.fin_validite as dfv"; $sql.= ", p.date_livraison as date_livraison"; - $sql.= ", p.model_pdf, p.ref_client, p.extraparams"; + $sql.= ", p.model_pdf, p.last_main_doc, p.ref_client, p.extraparams"; $sql.= ", p.note_private, p.note_public"; $sql.= ", p.fk_projet, p.fk_statut"; $sql.= ", p.fk_user_author, p.fk_user_valid, p.fk_user_cloture"; @@ -1306,6 +1353,7 @@ class Propal extends CommonObject $this->socid = $obj->fk_soc; $this->fk_project = $obj->fk_projet; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->note = $obj->note_private; // TODO deprecated $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; @@ -1505,48 +1553,6 @@ class Propal extends CommonObject } } - /** - * Update value of extrafields on the proposal - * - * @param User $user Object user that modify - * @return int <0 if ko, >0 if ok - */ - function update_extrafields($user) - { - global $conf, $hookmanager; - - $action='update'; - $error = 0; - - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('propaldao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (!$error) - { - return 1; - } - else - { - return -1; - } - - } - /** * Set status to validated * @@ -2257,8 +2263,8 @@ class Propal extends CommonObject * * @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 + * @param string $note Complete private note with this note + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @return int <0 if KO, >0 if OK */ function cloture($user, $statut, $note, $notrigger=0) @@ -2270,8 +2276,10 @@ class Propal extends CommonObject $this->db->begin(); + $newprivatenote = dol_concatdesc($this->note_private, $note); + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($note)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; + $sql.= " SET fk_statut = ".$statut.", note_private = '".$this->db->escape($newprivatenote)."', date_cloture='".$this->db->idate($now)."', fk_user_cloture=".$user->id; $sql.= " WHERE rowid = ".$this->id; $resql=$this->db->query($sql); @@ -2297,7 +2305,7 @@ class Propal extends CommonObject return -2; } } - if ($statut == self::STATUS_BILLED) + if ($statut == self::STATUS_BILLED) // Why this ? { $trigger_name='PROPAL_CLASSIFY_BILLED'; } @@ -3349,11 +3357,11 @@ class Propal extends CommonObject $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) - $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) - $result.=' '; - $result.=$linkstart.$this->ref.$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; } diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index bb8e0d880b9..a7fe6b05201 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -158,7 +158,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -947,7 +947,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->propal->lire; - $delallowed=$user->rights->propal->lire; + $delallowed=$user->rights->propal->creer; print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index c385fe9a6ae..0d73b288f0b 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -170,7 +170,7 @@ if (empty($reshook)) $result = $object->set_reopen($user); if ($result > 0) { - setEventMessages($langs->trans('OrderReopened', $object->ref), null); + setEventMessages($langs->trans('OrderReopened', $object->ref), null); } else { @@ -264,12 +264,12 @@ if (empty($reshook)) $object->modelpdf = GETPOST('model'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->date_livraison = $datelivraison; - $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); - $object->warehouse_id = GETPOST('warehouse_id', 'int'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); + $object->warehouse_id = GETPOST('warehouse_id', 'int'); $object->fk_delivery_address = GETPOST('fk_address'); $object->contactid = GETPOST('contactid'); $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -279,8 +279,8 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form if (! $error) { - $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) $error++; + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) $error++; } // If creation from another object of another module (Example: origin=propal, originid=1) @@ -366,7 +366,7 @@ if (empty($reshook)) // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if - // trigger used + // trigger used { $lines[$i]->fetch_optionals($lines[$i]->rowid); $array_options = $lines[$i]->array_options; @@ -423,7 +423,7 @@ if (empty($reshook)) $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook if ($reshook < 0) - $error++; + $error++; } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -491,10 +491,10 @@ if (empty($reshook)) } else if ($action == 'classifyunbilled' && $user->rights->commande->creer) { - $ret=$object->classifyUnBilled(); - if ($ret < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $ret=$object->classifyUnBilled(); + if ($ret < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Positionne ref commande client @@ -502,7 +502,7 @@ if (empty($reshook)) $result = $object->set_ref_client($user, GETPOST('ref_client')); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -510,7 +510,7 @@ if (empty($reshook)) $result = $object->set_remise($user, GETPOST('remise')); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -563,7 +563,7 @@ if (empty($reshook)) else if ($action == 'setavailability' && $user->rights->commande->creer) { $result = $object->availability(GETPOST('availability_id')); if ($result < 0) - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else if ($action == 'setdemandreason' && $user->rights->commande->creer) { @@ -596,36 +596,36 @@ if (empty($reshook)) // Set incoterm elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { - $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } // bank account else if ($action == 'setbankaccount' && $user->rights->commande->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // shipping method else if ($action == 'setshippingmethod' && $user->rights->commande->creer) { - $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - // warehouse - else if ($action == 'setwarehouse' && $user->rights->commande->creer) { - $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + // warehouse + else if ($action == 'setwarehouse' && $user->rights->commande->creer) { + $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else if ($action == 'setremisepercent' && $user->rights->commande->creer) { $result = $object->set_remise($user, GETPOST('remise_percent')); @@ -898,18 +898,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); } else { setEventMessages($object->error, $object->errors, 'errors'); } @@ -1062,13 +1062,13 @@ if (empty($reshook)) } else if ($action == 'confirm_validate' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1121,7 +1121,7 @@ if (empty($reshook)) else if ($action == 'confirm_modif' && $user->rights->commande->creer) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1174,13 +1174,13 @@ if (empty($reshook)) } else if ($action == 'confirm_cancel' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -1223,10 +1223,12 @@ if (empty($reshook)) $hookmanager->initHooks(array('orderdao')); $parameters = array('id' => $object->id); $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by - // some hooks + // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); $error++; } } else if ($reshook < 0) @@ -1393,10 +1395,10 @@ if ($action == 'create' && $user->rights->commande->creer) $soc = $objectsrc->thirdparty; $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); - $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); - $warehouse_id = (! empty($objectsrc->warehouse_id)?$objectsrc->warehouse_id:(! empty($soc->warehouse_id)?$soc->warehouse_id:0)); + $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); + $warehouse_id = (! empty($objectsrc->warehouse_id)?$objectsrc->warehouse_id:(! empty($soc->warehouse_id)?$soc->warehouse_id:0)); $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1421,10 +1423,10 @@ if ($action == 'create' && $user->rights->commande->creer) { $cond_reglement_id = $soc->cond_reglement_id; $mode_reglement_id = $soc->mode_reglement_id; - $fk_account = $soc->fk_account; + $fk_account = $soc->fk_account; $availability_id = $soc->availability_id; - $shipping_method_id = $soc->shipping_method_id; - $warehouse_id = $soc->warehouse_id; + $shipping_method_id = $soc->shipping_method_id; + $warehouse_id = $soc->warehouse_id; $demand_reason_id = $soc->demand_reason_id; $remise_percent = $soc->remise_percent; $remise_absolue = 0; @@ -1537,12 +1539,12 @@ if ($action == 'create' && $user->rights->commande->creer) $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); print ''; - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { print '
'; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; } // Delivery delay @@ -1550,21 +1552,21 @@ if ($action == 'create' && $user->rights->commande->creer) $form->selectAvailabilityDelay($availability_id, 'availability_id', '', 1); print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + } - // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); - print ''; - } + // Warehouse + if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct=new FormProduct($db); + print ''; + } // What trigger creation print ''; print ''; - print ''; } // Other attributes $parameters = array('objectsrc' => $objectsrc, 'socid'=>$socid); $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) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1623,8 +1625,8 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; print ''; - print ''; } @@ -1686,6 +1688,8 @@ if ($action == 'create' && $user->rights->commande->creer) } print ''; + + // Amount print ''; print '"; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE @@ -1918,69 +1922,69 @@ if ($action == 'create' && $user->rights->commande->creer) // Ref customer $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); + // Thirdparty + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $soc->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 ($user->rights->commande->creer) - { - 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.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.=''; + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->commande->creer) + { + 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.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.=''; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print '
' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print '
' . $langs->trans('SendingMethod') . ''; - print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); - print '
' . $langs->trans('SendingMethod') . ''; + print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); + print '
' . $langs->trans('Warehouse') . ''; - print $formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1); - print '
' . $langs->trans('Warehouse') . ''; + print $formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1); + print '
' . $langs->trans('Source') . ''; @@ -1590,22 +1592,22 @@ if ($action == 'create' && $user->rights->commande->creer) { print '
'; - $incoterm_id = GETPOST('incoterm_id'); - $incoterm_location = GETPOST('location_incoterms'); - if (empty($incoterm_id)) - { - $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); - $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); - } - print $form->select_incoterms($incoterm_id, $incoterm_location); + print ''; + $incoterm_id = GETPOST('incoterm_id'); + $incoterm_location = GETPOST('location_incoterms'); + if (empty($incoterm_id)) + { + $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); + $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); + } + print $form->select_incoterms($incoterm_id, $incoterm_location); print '
'.fieldLabel('Currency','multicurrency_code').''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print '
' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . '
' . $langs->trans('TotalVAT') . '' . price($objectsrc->total_tva) . "
'; + print '
'; if ($soc->outstanding_limit) { - // Outstanding Bill - print ''; - print ''; + // Outstanding Bill + print ''; + print ''; } // Relative and absolute discounts if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final - // invoice + // invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; @@ -2037,7 +2041,7 @@ if ($action == 'create' && $user->rights->commande->creer) } else { print $object->date ? dol_print_date($object->date, 'day') : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; @@ -2062,51 +2066,51 @@ if ($action == 'create' && $user->rights->commande->creer) } else { print $object->date_livraison ? dol_print_date($object->date_livraison, 'daytext') : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; print ''; - // Shipping Method - if (! empty($conf->expedition->enabled)) { - print ''; - print ''; - } + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + print ''; + } - // Warehouse - if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct=new FormProduct($db); - print ''; - print ''; - } + // Warehouse + if (! empty($conf->expedition->enabled) && ! empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct=new FormProduct($db); + print ''; + print ''; + } // Terms of payment print '
'; - print $langs->trans('OutstandingBill'); - print ''; - print price($soc->get_OutstandingBill()) . ' / '; - print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); - print '
'; + print $langs->trans('OutstandingBill'); + print ''; + print price($soc->get_OutstandingBill()) . ' / '; + print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); + print '
'; - print ''; - if ($action != 'editshippingmethod' && $user->rights->commande->creer) - print ''; - print '
'; - print $langs->trans('SendingMethod'); - print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; - print '
'; - if ($action == 'editshippingmethod') { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); - } else { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); - } - print '
'; + print ''; + if ($action != 'editshippingmethod' && $user->rights->commande->creer) + print ''; + print '
'; + print $langs->trans('SendingMethod'); + print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; + print '
'; + if ($action == 'editshippingmethod') { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); + } + print '
'; - print ''; - if ($action != 'editwarehouse' && $user->rights->commande->creer) - print ''; - print '
'; - print $langs->trans('Warehouse'); - print 'id.'">'.img_edit($langs->trans('SetWarehouse'),1).'
'; - print '
'; - if ($action == 'editwarehouse') { - $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); - } else { - $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none'); - } - print '
'; + print ''; + if ($action != 'editwarehouse' && $user->rights->commande->creer) + print ''; + print '
'; + print $langs->trans('Warehouse'); + print 'id.'">'.img_edit($langs->trans('SetWarehouse'),1).'
'; + print '
'; + if ($action == 'editwarehouse') { + $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); + } else { + $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none'); + } + print '
'; @@ -2173,9 +2177,9 @@ if ($action == 'create' && $user->rights->commande->creer) print '
'; print ''; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { - list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); - } + if($action == 'actualizemulticurrencyrate') { + list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); + } $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); @@ -2243,30 +2247,30 @@ if ($action == 'create' && $user->rights->commande->creer) $totalVolume=$tmparray['volume']; if ($totalWeight || $totalVolume) { - print ''.$langs->trans("CalculatedWeight").''; - print ''; - print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); - print ''; - print ''.$langs->trans("CalculatedVolume").''; - print ''; - print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); - print ''; + print ''.$langs->trans("CalculatedWeight").''; + print ''; + print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); + print ''; + print ''.$langs->trans("CalculatedVolume").''; + print ''; + print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); + print ''; } - // TODO How record was recorded OrderMode (llx_c_input_method) + // TODO How record was recorded OrderMode (llx_c_input_method) // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; - print '
'; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->commande->creer) print ''.img_edit().''; - else print ' '; - print '
'; - print ''; - print ''; + print '
'; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->commande->creer) print ''.img_edit().''; + else print ' '; + print '
'; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2275,27 +2279,27 @@ if ($action == 'create' && $user->rights->commande->creer) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { - print ''; - print ''; - print '
'; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->commande->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ''; - print ''; + print ''; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->commande->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ''; + print ''; } // Other attributes @@ -2312,20 +2316,20 @@ if ($action == 'create' && $user->rights->commande->creer) if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Total HT @@ -2357,7 +2361,7 @@ if ($action == 'create' && $user->rights->commande->creer) // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } @@ -2384,7 +2388,7 @@ if ($action == 'create' && $user->rights->commande->creer) */ $result = $object->getLinesArray(); - print '
+ print ' @@ -2395,7 +2399,7 @@ if ($action == 'create' && $user->rights->commande->creer) include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
'; + print '
'; print ''; // Show object lines @@ -2421,7 +2425,7 @@ if ($action == 'create' && $user->rights->commande->creer) } } print '
'; - print '
'; + print '
'; print "
\n"; @@ -2435,7 +2439,7 @@ if ($action == 'create' && $user->rights->commande->creer) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { // Send if ($object->statut > Commande::STATUS_DRAFT) { @@ -2445,10 +2449,10 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; } - // Valid + // Valid if ($object->statut == Commande::STATUS_DRAFT && $object->total_ttc >= 0 && $numlines > 0 && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))) ) { print ''; @@ -2459,8 +2463,8 @@ if ($action == 'create' && $user->rights->commande->creer) } // Create event if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a - // "workflow" action so should appears somewhere else on - // page. + // "workflow" action so should appears somewhere else on + // page. { print '' . $langs->trans("AddAction") . ''; } @@ -2480,11 +2484,11 @@ if ($action == 'create' && $user->rights->commande->creer) // Create contract if ($conf->contrat->enabled && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS || $object->statut == Commande::STATUS_CLOSED)) { - $langs->load("contracts"); + $langs->load("contracts"); - if ($user->rights->contrat->creer) { - print ''; - } + if ($user->rights->contrat->creer) { + print ''; + } } // Ship @@ -2527,9 +2531,9 @@ if ($action == 'create' && $user->rights->commande->creer) } } if ($object->statut > Commande::STATUS_DRAFT && $object->billed) { - if ($user->rights->commande->creer && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { - print ''; - } + if ($user->rights->commande->creer && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) { + print ''; + } } // Clone if ($user->rights->commande->creer) { @@ -2538,8 +2542,8 @@ if ($action == 'create' && $user->rights->commande->creer) // Cancel order if ($object->statut == Commande::STATUS_VALIDATED && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->cloturer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->annuler))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->cloturer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->annuler))) ) { print ''; @@ -2571,8 +2575,8 @@ if ($action == 'create' && $user->rights->commande->creer) $relativepath = $comref . '/' . $comref . '.pdf'; $filedir = $conf->commande->dir_output . '/' . $comref; $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->commande->creer; - $delallowed = $user->rights->commande->supprimer; + $genallowed = $user->rights->commande->lire; + $delallowed = $user->rights->commande->creer; print $formfile->showdocuments('commande', $comref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); diff --git a/htdocs/commande/class/api_deprecated_commande.class.php b/htdocs/commande/class/api_deprecated_commande.class.php index d41fd9cee1d..f494709e441 100644 --- a/htdocs/commande/class/api_deprecated_commande.class.php +++ b/htdocs/commande/class/api_deprecated_commande.class.php @@ -107,7 +107,7 @@ class CommandeApi extends DolibarrApi * @url GET /order/list * @return array Array of order objects */ - function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $mode=0, $societe = 0) { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $mode=0, $societe = 0) { global $db, $conf; $obj_ret = array(); @@ -316,7 +316,7 @@ class CommandeApi extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index 6ffca33a4ce..e31aaa4e060 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -52,9 +52,9 @@ class Orders extends DolibarrApi } /** - * Get properties of a commande object + * Get properties of an order object * - * Return an array with commande informations + * Return an array with order informations * * @param int $id ID of order * @return array|mixed data without useless information @@ -176,7 +176,7 @@ class Orders extends DolibarrApi * Create order object * * @param array $request_data Request data - * @return int ID of commande + * @return int ID of order */ function post($request_data = NULL) { @@ -196,6 +196,7 @@ class Orders extends DolibarrApi } $this->commande->lines = $lines; }*/ + if ($this->commande->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating order", array_merge(array($this->commande->error), $this->commande->errors)); } @@ -236,8 +237,8 @@ class Orders extends DolibarrApi /** * Add a line to given order * - * @param int $id Id of commande to update - * @param array $request_data Orderline data + * @param int $id Id of order to update + * @param array $request_data OrderLine data * * @url POST {id}/lines * @@ -281,12 +282,13 @@ class Orders extends DolibarrApi $request_data->label, $request_data->array_options, $request_data->fk_unit, - $this->element, - $request_data->id + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; @@ -295,9 +297,9 @@ class Orders extends DolibarrApi /** * Update a line to given order * - * @param int $id Id of commande to update + * @param int $id Id of order to update * @param int $lineid Id of line to update - * @param array $request_data Orderline data + * @param array $request_data OrderLine data * * @url PUT {id}/lines/{lineid} * @@ -310,7 +312,7 @@ class Orders extends DolibarrApi $result = $this->commande->fetch($id); if( ! $result ) { - throw new RestException(404, 'Commande not found'); + throw new RestException(404, 'Order not found'); } if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { @@ -338,7 +340,8 @@ class Orders extends DolibarrApi $request_data->label, $request_data->special_code, $request_data->array_options, - $request_data->fk_unit + $request_data->fk_unit, + $request_data->multicurrency_subprice ); if ($updateRes > 0) { @@ -387,7 +390,7 @@ class Orders extends DolibarrApi /** * Update order general fields (won't touch lines of order) * - * @param int $id Id of commande to update + * @param int $id Id of order to update * @param array $request_data Datas * * @return int @@ -399,7 +402,7 @@ class Orders extends DolibarrApi $result = $this->commande->fetch($id); if( ! $result ) { - throw new RestException(404, 'Commande not found'); + throw new RestException(404, 'Order not found'); } if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { @@ -498,6 +501,47 @@ class Orders extends DolibarrApi ); } + /** + * Close an order (Classify it as "Delivered") + * + * @param int $id Order ID + * @param int $notrigger Disabled triggers + * + * @url POST {id}/close + * + * @return array + */ + function close($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->commande->creer) { + throw new RestException(401); + } + $result = $this->commande->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Order not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->commande->cloture(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Order: '.$this->commande->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Order closed (Ref='.$this->commande->ref.')' + ) + ); + } + + /** * Clean sensible object datas * @@ -509,6 +553,10 @@ class Orders extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 1ad2d876478..36162e71384 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -46,7 +46,7 @@ class Commande extends CommonOrder public $table_element_line = 'commandedet'; public $class_element_line = 'OrderLine'; public $fk_element = 'fk_commande'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'order'; /** @@ -557,9 +557,10 @@ class Commande extends CommonOrder * Close order * * @param User $user Objet user that close + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @return int <0 if KO, >0 if OK */ - function cloture($user) + function cloture($user, $notrigger=0) { global $conf; @@ -580,10 +581,13 @@ class Commande extends CommonOrder if ($this->db->query($sql)) { - // Call trigger - $result=$this->call_trigger('ORDER_CLOSE',$user); - if ($result < 0) $error++; - // End call triggers + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ORDER_CLOSE',$user); + if ($result < 0) $error++; + // End call triggers + } if (! $error) { @@ -606,6 +610,7 @@ class Commande extends CommonOrder return -1; } } + return 0; } /** @@ -873,6 +878,11 @@ class Commande extends CommonOrder { $this->ref = $initialref; + 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)) { @@ -885,7 +895,7 @@ class Commande extends CommonOrder $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -896,7 +906,7 @@ class Commande extends CommonOrder $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -1077,11 +1087,12 @@ class Commande extends CommonOrder * Load an object from a proposal and create a new order into database * * @param Object $object Object source + * @param User $user User making creation * @return int <0 if KO, 0 if nothing done, 1 if OK */ - function createFromProposal($object) + function createFromProposal($object, User $user) { - global $conf,$user,$hookmanager; + global $conf, $hookmanager; dol_include_once('/core/class/extrafields.class.php'); @@ -1240,7 +1251,7 @@ class Commande extends CommonOrder { global $mysoc, $conf, $langs, $user; - dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit", LOG_DEBUG); + dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1429,10 +1440,10 @@ class Commande extends CommonOrder return -2; } } - else - { + else + { dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); - return -3; + return -3; } } @@ -1548,7 +1559,7 @@ class Commande extends CommonOrder $sql.= ', c.fk_shipping_method'; $sql.= ', c.fk_warehouse'; $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed'; - $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams'; + $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.last_main_doc, c.fk_delivery_address, c.extraparams'; $sql.= ', c.fk_incoterms, c.location_incoterms'; $sql.= ", c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva, c.multicurrency_total_ttc"; $sql.= ", i.libelle as libelle_incoterms"; @@ -1603,6 +1614,7 @@ class Commande extends CommonOrder $this->note_public = $obj->note_public; $this->fk_project = $obj->fk_projet; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement_libelle; @@ -1894,6 +1906,40 @@ class Commande extends CommonOrder return $nb; } + /** + * Count numbe rof shipments for this order + * + * @return int <0 if KO, Nb of shipment found if OK + */ + function getNbOfShipments() + { + $nb = 0; + + $sql = 'SELECT COUNT(DISTINCT ed.fk_expedition) as nb'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'expeditiondet as ed,'; + $sql.= ' '.MAIN_DB_PREFIX.'commandedet as cd'; + $sql.= ' WHERE'; + $sql.= ' ed.fk_origin_line = cd.rowid'; + $sql.= ' AND cd.fk_commande =' .$this->id; + //print $sql; + + dol_syslog(get_class($this)."::getNbOfShipments", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj) $nb = $obj->nb; + + $this->db->free($resql); + return $nb; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + /** * Load array this->expeditions of lines of shipments with nb of products sent for each order line * Note: For a dedicated shipment, the fetch_lines can be used to load the qty_asked and qty_shipped. This function is use to return qty_shipped cumulated for the order @@ -1920,18 +1966,18 @@ class Commande extends CommonOrder //print $sql; dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) + $resql = $this->db->query($sql); + if ($resql) { - $num = $this->db->num_rows($result); + $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { - $obj = $this->db->fetch_object($result); + $obj = $this->db->fetch_object($resql); $this->expeditions[$obj->rowid] = $obj->qty; $i++; } - $this->db->free(); + $this->db->free($resql); return $num; } else @@ -1939,7 +1985,6 @@ class Commande extends CommonOrder $this->error=$this->db->lasterror(); return -1; } - } /** @@ -1990,18 +2035,18 @@ class Commande extends CommonOrder $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps"; $sql.= " WHERE ps.fk_product IN (".join(',',$array_of_product).")"; $sql.= ' GROUP BY fk_product '; - $result = $this->db->query($sql); - if ($result) + $resql = $this->db->query($sql); + if ($resql) { - $num = $this->db->num_rows($result); + $num = $this->db->num_rows($resql); $i = 0; while ($i < $num) { - $obj = $this->db->fetch_object($result); + $obj = $this->db->fetch_object($resql); $this->stocks[$obj->fk_product] = $obj->total; $i++; } - $this->db->free(); + $this->db->free($resql); } } return 0; @@ -3048,48 +3093,6 @@ class Commande extends CommonOrder } } - /** - * Update value of extrafields on order - * - * @param User $user Object user that modify - * @return int <0 if ko, >0 if ok - */ - function update_extrafields($user) - { - global $hookmanager, $conf; - - $action='create'; - $error = 0; - - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('orderdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - } - else if ($reshook < 0) $error++; - - if (!$error) - { - return 1; - } - else - { - return -1; - } - - } - /** * Delete the customer order * @@ -3398,7 +3401,6 @@ class Commande extends CommonOrder if ($short) return $url; - $picto = 'order'; $label = ''; if ($user->rights->commande->lire) { @@ -3432,9 +3434,11 @@ class Commande extends CommonOrder $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$linkstart.$this->ref.$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; } diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 10c1459a087..e007953bfe3 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -142,7 +142,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -1397,7 +1397,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->commande->lire; - $delallowed=$user->rights->commande->supprimer; + $delallowed=$user->rights->commande->creer; print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 326e3ece569..5e79874ae8f 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -151,7 +151,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -1114,7 +1114,7 @@ if ($resql) $bankstatic->id=$banklinestatic->fk_account; $bankstatic->label=$banklinestatic->bank_account_ref; print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1); + print $bankstatic->getNomUrl(1,'transactions'); print ' '.$langs->trans("toward").' '; $bankstatic->id=$objp->bankid; $bankstatic->label=$objp->bankref; @@ -1131,7 +1131,7 @@ if ($resql) $banklinestatic->fetch($links[$key]['url_id']); $bankstatic->id=$banklinestatic->fk_account; $bankstatic->label=$banklinestatic->bank_account_ref; - print $bankstatic->getNomUrl(1); + print $bankstatic->getNomUrl(1,'transactions'); print ')'; } //var_dump($links); diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 8ad1ccd2ecf..6bc9ae16089 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -386,7 +386,7 @@ class Account extends CommonObject * Add an entry into table ".MAIN_DB_PREFIX."bank * * @param int $date Date operation - * @param string $oper 1,2,3,4... (deprecated) or TYP,VIR,PRE,LIQ,VAD,CB,CHQ... + * @param string $oper 1,2,3,4... (deprecated) or 'TYP','VIR','PRE','LIQ','VAD','CB','CHQ'... * @param string $label Descripton * @param float $amount Amount * @param string $num_chq Numero cheque ou virement @@ -1324,11 +1324,14 @@ class Account extends CommonObject if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; } - $link = 'picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : ''); + $result .= $linkend; - if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '').$linkend; return $result; } diff --git a/htdocs/compta/bank/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php index c6fd3f72def..fa540f43401 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -61,7 +61,7 @@ class BankAccounts extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') { $list = array(); diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 0ecfe01498f..23df6a44285 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -74,7 +74,7 @@ $hookmanager->initHooks(array($contextpage)); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels -$extralabels = $extrafields->fetch_name_optionals_label('bankaccount'); +$extralabels = $extrafields->fetch_name_optionals_label('bank_account'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); // List of fields to search into when doing a "search in all" @@ -103,7 +103,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -143,7 +143,7 @@ $title=$langs->trans('BankAccounts'); // Load array of financial accounts (opened by default) $accounts = array(); -$sql = "SELECT rowid, label, courant, rappro, account_number, fk_accountancy_journal, currency_code, datec as date_creation, tms as date_update"; +$sql = "SELECT b.rowid, b.label, b.courant, b.rappro, b.account_number, b.fk_accountancy_journal, b.currency_code, b.datec as date_creation, b.tms as date_update"; // Add fields from extrafields foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); // Add fields from hooks @@ -151,7 +151,7 @@ $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."bank_account as b"; -if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bankcacount_extrafields as ef on (c.rowid = ef.fk_object)"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account_extrafields as ef on (b.rowid = ef.fk_object)"; $sql.= " WHERE entity IN (".getEntity('bank_account').")"; if ($search_status == 'opened') $sql.= " AND clos = 0"; if ($search_status == 'closed') $sql.= " AND clos = 1"; diff --git a/htdocs/compta/deplacement/class/deplacement.class.php b/htdocs/compta/deplacement/class/deplacement.class.php index c0a4ef94613..c67fce127c2 100644 --- a/htdocs/compta/deplacement/class/deplacement.class.php +++ b/htdocs/compta/deplacement/class/deplacement.class.php @@ -35,7 +35,7 @@ class Deplacement extends CommonObject public $table_element='deplacement'; public $table_element_line = ''; public $fk_element = ''; - protected $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe var $datec; // Creation date var $dated; diff --git a/htdocs/compta/facture/admin/facture_cust_extrafields.php b/htdocs/compta/facture/admin/facture_cust_extrafields.php index c7a43c737de..2e985c8a009 100644 --- a/htdocs/compta/facture/admin/facture_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_cust_extrafields.php @@ -39,7 +39,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php index 1bc9272a32f..0cbea0c8d89 100644 --- a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php @@ -40,7 +40,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php index 3a5f8c3387f..b17e3c416d2 100644 --- a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php @@ -40,7 +40,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php index 8c2a0b3365a..0951dff721b 100644 --- a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php @@ -40,7 +40,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 55b128bcb6a..868856094df 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -307,11 +307,11 @@ if (empty($reshook)) $date = dol_mktime(12, 0, 0, $_POST['invoicedatemonth'], $_POST['invoicedateday'], $_POST['invoicedateyear']); if (empty($date)) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); - exit; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); + exit; } - $object->date=$date; + $object->date=$date; $new_date_lim_reglement = $object->calculate_date_lim_reglement(); if ($new_date_lim_reglement > $old_date_lim_reglement) $object->date_lim_reglement = $new_date_lim_reglement; if ($object->date_lim_reglement < $object->date) $object->date_lim_reglement = $object->date; @@ -323,7 +323,7 @@ if (empty($reshook)) { $object->fetch($id); $date_pointoftax = dol_mktime(12, 0, 0, $_POST['date_pointoftaxmonth'], $_POST['date_pointoftaxday'], $_POST['date_pointoftaxyear']); - $object->date_pointoftax=$date_pointoftax; + $object->date_pointoftax=$date_pointoftax; $result = $object->update($user); if ($result < 0) dol_print_error($db, $object->error); } @@ -369,14 +369,14 @@ if (empty($reshook)) // Set incoterm elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { - $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - } + { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + } // bank account else if ($action == 'setbankaccount' && $user->rights->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } else if ($action == 'setremisepercent' && $user->rights->facture->creer) @@ -451,8 +451,8 @@ if (empty($reshook)) // Classify to validated else if ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) ) { $idwarehouse = GETPOST('idwarehouse','int'); @@ -462,7 +462,7 @@ if (empty($reshook)) // Check parameters - // Check for mandatory fields defined into setup + // Check for mandatory fields defined into setup $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL'); foreach($array_to_check as $key) { @@ -540,7 +540,7 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } } else @@ -554,7 +554,7 @@ if (empty($reshook)) // Go back to draft status (unvalidate) else if ($action == 'confirm_modif' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) ) { $idwarehouse = GETPOST('idwarehouse'); @@ -831,7 +831,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = $_POST['cond_reglement_id']; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -883,7 +883,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = 0; $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); @@ -899,62 +899,62 @@ if (empty($reshook)) if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0) { - $facture_source = new Facture($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source)>0) - { - $fk_parent_line = 0; + $facture_source = new Facture($db); // fetch origin object + if ($facture_source->fetch($object->fk_facture_source)>0) + { + $fk_parent_line = 0; - foreach($facture_source->lines as $line) - { - // Reset fk_parent_line for no child products and special product - if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { - $fk_parent_line = 0; - } + foreach($facture_source->lines as $line) + { + // Reset fk_parent_line for no child products and special product + if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { + $fk_parent_line = 0; + } - $line->fk_facture = $object->id; - $line->fk_parent_line = $fk_parent_line; + $line->fk_facture = $object->id; + $line->fk_parent_line = $fk_parent_line; - $line->subprice = -$line->subprice; // invert price for object - $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here - $line->total_ht = -$line->total_ht; - $line->total_tva = -$line->total_tva; - $line->total_ttc = -$line->total_ttc; - $line->total_localtax1 = -$line->total_localtax1; - $line->total_localtax2 = -$line->total_localtax2; + $line->subprice = -$line->subprice; // invert price for object + $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here + $line->total_ht = -$line->total_ht; + $line->total_tva = -$line->total_tva; + $line->total_ttc = -$line->total_ttc; + $line->total_localtax1 = -$line->total_localtax1; + $line->total_localtax2 = -$line->total_localtax2; - $line->multicurrency_subprice = -$line->multicurrency_subprice; - $line->multicurrency_total_ht = -$line->multicurrency_total_ht; - $line->multicurrency_total_tva = -$line->multicurrency_total_tva; - $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc; + $line->multicurrency_subprice = -$line->multicurrency_subprice; + $line->multicurrency_total_ht = -$line->multicurrency_total_ht; + $line->multicurrency_total_tva = -$line->multicurrency_total_tva; + $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc; - $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked + $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked - $object->lines[] = $line; // insert new line in current object + $object->lines[] = $line; // insert new line in current object - // Defined the new fk_parent_line - if ($result > 0 && $line->product_type == 9) { - $fk_parent_line = $result; - } - } + // Defined the new fk_parent_line + if ($result > 0 && $line->product_type == 9) { + $fk_parent_line = $result; + } + } - $object->update_price(1); - } + $object->update_price(1); + } } - if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) - { - $facture_source = new Facture($db); // fetch origin object if not previously defined - if ($facture_source->fetch($object->fk_facture_source)>0) - { - $totalpaye = $facture_source->getSommePaiement(); - $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); - $totaldeposits = $facture_source->getSumDepositsUsed(); - $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits); + if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) + { + $facture_source = new Facture($db); // fetch origin object if not previously defined + if ($facture_source->fetch($object->fk_facture_source)>0) + { + $totalpaye = $facture_source->getSommePaiement(); + $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); + $totaldeposits = $facture_source->getSumDepositsUsed(); + $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits); - $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); - } - } + $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); + } + } } } @@ -985,7 +985,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; @@ -1035,7 +1035,7 @@ if (empty($reshook)) $object->fk_project = $_POST['projectid']; $object->cond_reglement_id = ($_POST['type'] == 3?1:$_POST['cond_reglement_id']); $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->fk_account = GETPOST('fk_account', 'int'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->amount = $_POST['amount']; $object->remise_absolue = $_POST['remise_absolue']; $object->remise_percent = $_POST['remise_percent']; @@ -1117,7 +1117,7 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines or deposit lines"); $result = $srcobject->fetch($object->origin_id); - // If deposit invoice + // If deposit invoice if ($_POST['type'] == Facture::TYPE_DEPOSIT) { $typeamount = GETPOST('typedeposit', 'alpha'); @@ -1167,8 +1167,8 @@ if (empty($reshook)) if ($totalamount != 0) { if ($numlines > 0) $numlines = $numlines-1; - $tva_tx = $lines[$numlines]->tva_tx; - if (! empty($lines[$numlines]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$numlines]->vat_src_code.')'; + $tva_tx = $lines[$numlines]->tva_tx; + if (! empty($lines[$numlines]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$numlines]->vat_src_code.')'; $amountdeposit[$tva_tx] = ($totalamount * $valuedeposit) / 100; } else { $amountdeposit[0] = 0; @@ -1205,7 +1205,7 @@ if (empty($reshook)) 0, // date_start 0, // date_end 0, - $lines[$i]->info_bits, // info_bits + $lines[$i]->info_bits, // info_bits 0, 'HT', 0, @@ -1367,8 +1367,8 @@ if (empty($reshook)) // modified by hook if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - $error++; + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + $error++; } } else { @@ -1540,16 +1540,16 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error ++; } - if (!$prod_entry_mode) - { - if (GETPOST('type') < 0 && ! GETPOST('search_idprod')) - { - setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); - $error ++; - } - } + if (!$prod_entry_mode) + { + if (GETPOST('type') < 0 && ! GETPOST('search_idprod')) + { + setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors'); + $error ++; + } + } if ($prod_entry_mode == 'free' && empty($idprod) && GETPOST('type') < 0) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error ++; } if ($prod_entry_mode == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '') && $price_ht_devise == '') // Unit price can be 0 but not '' @@ -1634,8 +1634,8 @@ if (empty($reshook)) $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; if (empty($tva_tx)) $tva_npr=0; } } @@ -1790,18 +1790,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); unset($_POST['situations']); unset($_POST['progress']); @@ -1966,18 +1966,18 @@ if (empty($reshook)) unset($_POST['idprod']); unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); unset($_POST['situations']); unset($_POST['progress']); @@ -2020,10 +2020,10 @@ if (empty($reshook)) $trackid='inv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Actions to build doc - $upload_dir = $conf->facture->dir_output; - $permissioncreate=$user->rights->facture->creer; - include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + // Actions to build doc + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; if ($action == 'update_extras') { @@ -2041,8 +2041,10 @@ if (empty($reshook)) // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { - $error ++; + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; } } else if ($reshook < 0) $error ++; @@ -2195,7 +2197,7 @@ if ($action == 'create') $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); @@ -2238,14 +2240,14 @@ if ($action == 'create') if ($origin == 'contrat') { - $langs->load("admin"); - $text=$langs->trans("ToCreateARecurringInvoice"); - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); - if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) - { - $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); - } - print info_admin($text, 0, 0, 0).'
'; + $langs->load("admin"); + $text=$langs->trans("ToCreateARecurringInvoice"); + $text.=' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates")); + if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) + { + $text.=' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name')); + } + print info_admin($text, 0, 0, 0).'
'; } print '
'; @@ -2303,7 +2305,7 @@ if ($action == 'create') }); '; } - print ' '.$langs->trans("AddThirdParty").''; + print ' '.$langs->trans("AddThirdParty").''; print ''; } print '' . "\n"; @@ -2313,16 +2315,16 @@ if ($action == 'create') // Overwrite value if creation of invoice is from a predefined invoice if (empty($origin) && empty($originid) && GETPOST('fac_rec','int') > 0) { - $invoice_predefined = new FactureRec($db); - $invoice_predefined->fetch(GETPOST('fac_rec','int')); + $invoice_predefined = new FactureRec($db); + $invoice_predefined->fetch(GETPOST('fac_rec','int')); - $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later - if (empty($projectid)) $projectid = $invoice_predefined->fk_project; - $cond_reglement_id = $invoice_predefined->cond_reglement_id; - $mode_reglement_id = $invoice_predefined->mode_reglement_id; - $fk_account = $invoice_predefined->fk_account; - $note_public = $invoice_predefined->note_public; - $note_private = $invoice_predefined->note_private; + $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later + if (empty($projectid)) $projectid = $invoice_predefined->fk_project; + $cond_reglement_id = $invoice_predefined->cond_reglement_id; + $mode_reglement_id = $invoice_predefined->mode_reglement_id; + $fk_account = $invoice_predefined->fk_account; + $note_public = $invoice_predefined->note_public; + $note_private = $invoice_predefined->note_private; $sql = 'SELECT r.rowid, r.titre, r.total_ttc'; $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as r'; @@ -2345,17 +2347,17 @@ if ($action == 'create') print ''; $i ++; } print ''; // Option to reload page to retrieve customer informations. Note, this clear other input - if (!empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE)) - { - print ''; - } + } print ''; } $db->free($resql); @@ -2433,9 +2435,9 @@ if ($action == 'create') // Deposit if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) { - print '
'; - $tmp=' '; - print ''; - $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3); - print ''; - if (($origin == 'propal') || ($origin == 'commande')) - { - print ''; - print '
'; - print $desc; - print ''; - $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); - print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1); - print '' . $langs->trans('Value') . ':'; - } - print '
'; + $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3); + print ''; + if (($origin == 'propal') || ($origin == 'commande')) + { + print ''; + print '
'; + print $desc; + print ''; + $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); + print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1); + print '' . $langs->trans('Value') . ':'; + } + print '
'; - print '
'; + print '
'; } } @@ -2490,33 +2492,33 @@ if ($action == 'create') // Replacement if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) { - print ''; - print '
'; - $tmp=' + print ''; + print '
'; + $tmp=' jQuery(document).ready(function() { jQuery("#fac_replacement").change(function() { jQuery("#radio_replacement").prop("checked", true); }); }); '; - $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' '; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); - print $desc; - print '
'; + $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' '; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
'; } } else @@ -2534,15 +2536,15 @@ if ($action == 'create') { if ($socid > 0) { - // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { - print '
'; - $tmp=' + // Credit note + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) + { + print '
'; + $tmp=' jQuery(document).ready(function() { if (! jQuery("#radio_creditnote").is(":checked")) { @@ -2556,29 +2558,29 @@ if ($action == 'create') }); }); '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; - // $text.=''; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + // $text.=''; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; - print '
'; - print '    0 ? 'checked':'').' /> "; - print '
    0 ? 'checked':'').' /> "; - print '
'; + print '
'; + print '    0 ? 'checked':'').' /> "; + print '
    0 ? 'checked':'').' /> "; + print '
'; - print '
'; - } + print '
'; + } } else { @@ -2652,14 +2654,14 @@ if ($action == 'create') $form->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id', 'CRDT'); print ''; - // Bank Account + // Bank Account if (isset($_POST['fk_account'])) { $fk_account = $_POST['fk_account']; } - print '' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print ''; + print '' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; // Project if (! empty($conf->projet->enabled) && $socid > 0) @@ -2676,22 +2678,22 @@ if ($action == 'create') { print ''; print ''; - print ''; - $incoterm_id = GETPOST('incoterm_id'); - $incoterm_location = GETPOST('location_incoterms'); - if (empty($incoterm_id)) - { - $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); - $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); - } - print $form->select_incoterms($incoterm_id, $incoterm_location); + print ''; + $incoterm_id = GETPOST('incoterm_id'); + $incoterm_location = GETPOST('location_incoterms'); + if (empty($incoterm_id)) + { + $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms); + $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms); + } + print $form->select_incoterms($incoterm_id, $incoterm_location); print ''; } // Other attributes $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="2"', 'cols'=>2); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } @@ -2709,8 +2711,8 @@ if ($action == 'create') { print ''; print ''.fieldLabel('Currency','multicurrency_code').''; - print ''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print ''; } @@ -2718,28 +2720,28 @@ if ($action == 'create') $htmltext=''; if (GETPOST('fac_rec','int') > 0) { - $dateexample=($datefacture ? $datefacture : $dateinvoice); - if (empty($dateexample)) $dateexample=dol_now(); - $substitutionarray=array( - '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')', - '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')', - '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')', - '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')', - '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')', - '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')', - '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')', - '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')', - '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')', - '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')', - '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')' - ); + $dateexample=($datefacture ? $datefacture : $dateinvoice); + if (empty($dateexample)) $dateexample=dol_now(); + $substitutionarray=array( + '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')', + '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')', + '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%m').')', + '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%m').')', + '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'),'%m').')', + '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'),'%B').')', + '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%B').')', + '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')', + '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'),'%Y').')', + '__INVOICE_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample,'%Y').')', + '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'),'%Y').')' + ); - $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; - foreach($substitutionarray as $key => $val) - { - $htmltext.=$key.' = '.$langs->trans($val).'
'; - } - $htmltext.='
'; + $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; + foreach($substitutionarray as $key => $val) + { + $htmltext.=$key.' = '.$langs->trans($val).'
'; + } + $htmltext.='
'; } // Public note @@ -2810,8 +2812,8 @@ if ($action == 'create') $cntinvoice=count($objectsrc->linkedObjects['facture']); if ($cntinvoice>=1) { - setEventMessages('WarningBillExist', null, 'warnings'); - echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; + setEventMessages('WarningBillExist', null, 'warnings'); + echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; } echo ''; print '' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . ''; @@ -3179,34 +3181,34 @@ else if ($id > 0 || ! empty($ref)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->facture->creer) - { - 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.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->facture->creer) + { + 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.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } $morehtmlref.='
'; @@ -3259,7 +3261,7 @@ else if ($id > 0 || ! empty($ref)) $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, $object->id); if ($result > 0){ - print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
'; + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
'; } } print ''; @@ -3501,16 +3503,16 @@ else if ($id > 0 || ! empty($ref)) print $langs->trans('BankAccount'); print ''; if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon)) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; print ''; print ''; if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); } print ""; print ''; @@ -3568,14 +3570,14 @@ else if ($id > 0 || ! empty($ref)) if (!empty($conf->incoterm->enabled)) { print ''; - print '
'; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->facture->creer) print ''.img_edit().''; - else print ' '; - print '
'; - print ''; - print ''; + print '
'; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->facture->creer) print ''.img_edit().''; + else print ' '; + print '
'; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -3584,7 +3586,7 @@ else if ($id > 0 || ! empty($ref)) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } // Other attributes @@ -3602,20 +3604,20 @@ else if ($id > 0 || ! empty($ref)) if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Amount @@ -3629,40 +3631,40 @@ else if ($id > 0 || ! empty($ref)) // Amount Local Taxes if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 { - print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . ''; - print '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . ''; + print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . ''; + print '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . ''; } if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 { - print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . ''; - print '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . ''; + print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . ''; + print '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . ''; } // Revenue stamp if ($selleruserevenustamp) // Test company use revenue stamp { - print ''; - print ''; - if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) - { - print ''; - } - print '
'; - print $langs->trans('RevenueStamp'); - print 'id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '
'; - print ''; - if ($action == 'editrevenuestamp') { - print '
'; - print ''; - print ''; - print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code); - // print ''; - print ' '; - print '
'; - } else { - print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); - } - print ''; + print ''; + print ''; + if ($action != 'editrevenuestamp' && ! empty($object->brouillon) && $user->rights->facture->creer) + { + print ''; + } + print '
'; + print $langs->trans('RevenueStamp'); + print 'id . '">' . img_edit($langs->trans('SetRevenuStamp'), 1) . '
'; + print ''; + if ($action == 'editrevenuestamp') { + print '
'; + print ''; + print ''; + print $formother->select_revenue_stamp(GETPOST('revenuestamp'), 'revenuestamp', $mysoc->country_code); + // print ''; + print ' '; + print '
'; + } else { + print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); + } + print ''; } // Total with tax @@ -3675,165 +3677,165 @@ else if ($id > 0 || ! empty($ref)) $sign = 1; if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1; - $nbrows = 8; - $nbcols = 3; - if (! empty($conf->projet->enabled)) - $nbrows ++; - if (! empty($conf->banque->enabled)) { - $nbrows ++; - $nbcols ++; - } - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) - $nbrows ++; - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) - $nbrows ++; - if ($selleruserevenustamp) - $nbrows ++; - if (! empty($conf->multicurrency->enabled)) - $nbrows += 5; - if (! empty($conf->incoterm->enabled)) - $nbrows += 1; + $nbrows = 8; + $nbcols = 3; + if (! empty($conf->projet->enabled)) + $nbrows ++; + if (! empty($conf->banque->enabled)) { + $nbrows ++; + $nbcols ++; + } + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) + $nbrows ++; + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) + $nbrows ++; + if ($selleruserevenustamp) + $nbrows ++; + if (! empty($conf->multicurrency->enabled)) + $nbrows += 5; + if (! empty($conf->incoterm->enabled)) + $nbrows += 1; - if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION)) - { - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print ''; + if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION)) + { + if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) + print '
'; - if (count($object->tab_previous_situation_invoice) > 0) { - // List of previous invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + if (count($object->tab_previous_situation_invoice) > 0) { + // List of previous invoices + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - $total_prev_ht = $total_prev_ttc = 0; - foreach ($object->tab_previous_situation_invoice as $prev_invoice) { - $totalpaye = $prev_invoice->getSommePaiement(); - $total_prev_ht += $prev_invoice->total_ht; - $total_prev_ttc += $prev_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + $total_prev_ht = $total_prev_ttc = 0; + foreach ($object->tab_previous_situation_invoice as $prev_invoice) { + $totalpaye = $prev_invoice->getSommePaiement(); + $total_prev_ht += $prev_invoice->total_ht; + $total_prev_ttc += $prev_invoice->total_ttc; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - } + } - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; + } - if (count($object->tab_next_situation_invoice) > 0) { - // List of next invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + if (count($object->tab_next_situation_invoice) > 0) { + // List of next invoices + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - $total_next_ht = $total_next_ttc = 0; + $total_next_ht = $total_next_ttc = 0; - foreach ($object->tab_next_situation_invoice as $next_invoice) { - $totalpaye = $next_invoice->getSommePaiement(); - $total_next_ht += $next_invoice->total_ht; - $total_next_ttc += $next_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + foreach ($object->tab_next_situation_invoice as $next_invoice) { + $totalpaye = $next_invoice->getSommePaiement(); + $total_next_ht += $next_invoice->total_ht; + $total_next_ttc += $next_invoice->total_ttc; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - } + } - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; + } - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print '
' . $langs->trans('ListOfPreviousSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $langs->trans('ListOfPreviousSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $prev_invoice->getNomUrl(1) . '' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
' . $prev_invoice->getNomUrl(1) . '' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
' . price($total_prev_ht) . '' . price($total_prev_ttc) . ' 
' . price($total_prev_ht) . '' . price($total_prev_ttc) . ' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $next_invoice->getNomUrl(1) . '' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
' . $next_invoice->getNomUrl(1) . '' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
'; - } + if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) + print ''; + } - // List of payments already done + // List of payments already done - print ''; + print '
'; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) { - print ''; - } - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) { + print ''; + } + print ''; + print ''; + print ''; - // Payments already done (from payment on this invoice) - $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; - $sql .= ' c.code as payment_code, c.libelle as payment_label,'; - $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'; - $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; - $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; - $sql .= ' AND c.entity IN (' . getEntity('c_paiement').')'; - $sql .= ' ORDER BY p.datep, p.tms'; + // Payments already done (from payment on this invoice) + $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,'; + $sql .= ' c.code as payment_code, c.libelle as payment_label,'; + $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'; + $sql .= ' FROM ' . MAIN_DB_PREFIX . 'c_paiement as c, ' . MAIN_DB_PREFIX . 'paiement_facture as pf, ' . MAIN_DB_PREFIX . 'paiement as p'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; + $sql .= ' WHERE pf.fk_facture = ' . $object->id . ' AND p.fk_paiement = c.id AND pf.fk_paiement = p.rowid'; + $sql .= ' AND c.entity IN (' . getEntity('c_paiement').')'; + $sql .= ' ORDER BY p.datep, p.tms'; - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; - // if ($object->type != 2) - // { - if ($num > 0) { - while ($i < $num) { - $objp = $db->fetch_object($result); + // if ($object->type != 2) + // { + if ($num > 0) { + while ($i < $num) { + $objp = $db->fetch_object($result); - $paymentstatic->id = $objp->rowid; - $paymentstatic->datepaye = $db->jdate($objp->dp); - $paymentstatic->ref = $objp->ref; - $paymentstatic->num_paiement = $objp->num_paiement; - $paymentstatic->payment_code = $objp->payment_code; + $paymentstatic->id = $objp->rowid; + $paymentstatic->datepaye = $db->jdate($objp->dp); + $paymentstatic->ref = $objp->ref; + $paymentstatic->num_paiement = $objp->num_paiement; + $paymentstatic->payment_code = $objp->payment_code; - print ''; - print ''; - $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label; - print ''; - if (! empty($conf->banque->enabled)) - { - $bankaccountstatic->id = $objp->baid; - $bankaccountstatic->ref = $objp->baref; - $bankaccountstatic->label = $objp->baref; + print ''; + print ''; + $label = ($langs->trans("PaymentType" . $objp->payment_code) != ("PaymentType" . $objp->payment_code)) ? $langs->trans("PaymentType" . $objp->payment_code) : $objp->payment_label; + print ''; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; $bankaccountstatic->number = $objp->banumber; if (! empty($conf->accounting->enabled)) { @@ -3845,155 +3847,155 @@ else if ($id > 0 || ! empty($ref)) } print ''; - } - print ''; - print ''; - print ''; - $i ++; - } - } - /*else { + if ($bankaccountstatic->id) + print $bankaccountstatic->getNomUrl(1, 'transactions'); + print ''; + } + print ''; + print ''; + print ''; + $i ++; + } + } + /*else { print ''; }*/ - // } - $db->free($result); - } else { - dol_print_error($db); - } + // } + $db->free($result); + } else { + dol_print_error($db); + } - if ($object->type != Facture::TYPE_CREDIT_NOTE) { - // Total already paid - print ''; + if ($object->type != Facture::TYPE_CREDIT_NOTE) { + // Total already paid + print ''; - $resteapayeraffiche = $resteapayer; - $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + $resteapayeraffiche = $resteapayer; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; - // Loop on each credit note or deposit amount applied - $creditnoteamount = 0; - $depositamount = 0; - $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; - $sql .= " re.description, re.fk_facture_source"; - $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; - $sql .= " WHERE fk_facture = " . $object->id; - $resql = $db->query($sql); - if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - $invoice = new Facture($db); - while ($i < $num) { - $obj = $db->fetch_object($resql); - $invoice->fetch($obj->fk_facture_source); - print ''; - print ''; - print ''; - $i ++; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) - $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == Facture::TYPE_DEPOSIT) - $depositamount += $obj->amount_ttc; - } - } else { - dol_print_error($db); - } + // Loop on each credit note or deposit amount applied + $creditnoteamount = 0; + $depositamount = 0; + $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,"; + $sql .= " re.description, re.fk_facture_source"; + $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except as re"; + $sql .= " WHERE fk_facture = " . $object->id; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + $invoice = new Facture($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_facture_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == Facture::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); + } - // Paye partiellement 'escompte' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'badcustomer' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') { - print ''; - // $resteapayeraffiche=0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'product_returned' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } - // Paye partiellement ou Abandon 'abandon' - if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { - print ''; - $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; - } + // Paye partiellement 'escompte' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'badcustomer' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') { + print ''; + // $resteapayeraffiche=0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'product_returned' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'abandon' + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } - // Billed - print ''; + // Billed + print ''; - // Remainder to pay - print ''; - print ''; - print ''; - } - else // Credit note - { - $cssforamountpaymentcomplete=''; + // Remainder to pay + print ''; + print ''; + print ''; + } + else // Credit note + { + $cssforamountpaymentcomplete=''; - // Total already paid back - print ''; + // Total already paid back + print ''; - // Billed - print ''; + // Billed + print ''; - // Remainder to pay back - print ''; - print ''; - print ''; + // Remainder to pay back + print ''; + print ''; + print ''; - // Sold credit note - // print ''; - // print ''; - } + // Sold credit note + // print ''; + // print ''; + } - print '
' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '' . $langs->trans('Date') . '' . $langs->trans('Type') . '' . $langs->trans('BankAccount') . '' . $langs->trans('Amount') . ' 
' . ($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '' . $langs->trans('Date') . '' . $langs->trans('Type') . '' . $langs->trans('BankAccount') . '' . $langs->trans('Amount') . ' 
'; - print $paymentstatic->getNomUrl(1); - print '' . dol_print_date($db->jdate($objp->dp), 'day') . '' . $label . ' ' . $objp->num_paiement . '
'; + print $paymentstatic->getNomUrl(1); + print '' . dol_print_date($db->jdate($objp->dp), 'day') . '' . $label . ' ' . $objp->num_paiement . ''; - if ($bankaccountstatic->id) - print $bankaccountstatic->getNomUrl(1, 'transactions'); - print '' . price($sign * $objp->amount) . ' 
' . price($sign * $objp->amount) . ' 
' . $langs->trans("None") . '
'; - if ($object->type != Facture::TYPE_DEPOSIT) - print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); - else - print $langs->trans('AlreadyPaid'); - print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
'; + if ($object->type != Facture::TYPE_DEPOSIT) + print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); + else + print $langs->trans('AlreadyPaid'); + print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
'; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) - print $langs->trans("CreditNote") . ' '; - if ($invoice->type == Facture::TYPE_DEPOSIT) - print $langs->trans("Deposit") . ' '; - print $invoice->getNomUrl(0); - print ' :' . price($obj->amount_ttc) . ''; - print 'rowid . '">' . img_delete() . ''; - print '
'; + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == Facture::TYPE_DEPOSIT) + print $langs->trans("Deposit") . ' '; + print $invoice->getNomUrl(0); + print ' :' . price($obj->amount_ttc) . ''; + print 'rowid . '">' . img_delete() . ''; + print '
'; - print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; - print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); - print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; - $text = $langs->trans("HelpAbandonOther"); - if ($object->close_note) - $text .= '

' . $langs->trans("Reason") . ':' . $object->close_note; - print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); - print '
' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); + print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; + $text = $langs->trans("HelpAbandonOther"); + if ($object->close_note) + $text .= '

' . $langs->trans("Reason") . ':' . $object->close_note; + print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); + print '
' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
'; - if ($resteapayeraffiche >= 0) - print $langs->trans('RemainderToPay'); - else - print $langs->trans('ExcessReceived'); - print ' :' . price($resteapayeraffiche) . ' 
'; + if ($resteapayeraffiche >= 0) + print $langs->trans('RemainderToPay'); + else + print $langs->trans('ExcessReceived'); + print ' :' . price($resteapayeraffiche) . ' 
'; - print $langs->trans('AlreadyPaidBack'); - print ' :' . price($sign * $totalpaye) . ' 
'; + print $langs->trans('AlreadyPaidBack'); + print ' :' . price($sign * $totalpaye) . ' 
' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
'; - if ($resteapayeraffiche <= 0) - print $langs->trans('RemainderToPayBack'); - else - print $langs->trans('ExcessPaydBack'); - print ' :' . price($sign * $resteapayeraffiche) . ' 
'; + if ($resteapayeraffiche <= 0) + print $langs->trans('RemainderToPayBack'); + else + print $langs->trans('ExcessPaydBack'); + print ' :' . price($sign * $resteapayeraffiche) . ' 
'.$langs->trans('TotalTTC').' :'.price($sign * - // $object->total_ttc).' 
'.$langs->trans('TotalTTC').' :'.price($sign * + // $object->total_ttc).' 
'; + print ''; // Margin Infos if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); } print '
'; @@ -4076,7 +4078,7 @@ else if ($id > 0 || ! empty($ref)) } } - print '
+ print ' @@ -4084,7 +4086,7 @@ else if ($id > 0 || ! empty($ref)) '; if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } print '
'; @@ -4110,7 +4112,7 @@ else if ($id > 0 || ! empty($ref)) } print "\n"; - print "
"; + print "
"; print "\n"; @@ -4138,8 +4140,8 @@ else if ($id > 0 || ! empty($ref)) { if (! $objectidnext && $object->is_last_in_cycle()) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) { print ''; } else { @@ -4166,7 +4168,7 @@ else if ($id > 0 || ! empty($ref)) || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id)) || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))) && ($object->statut == 2 || $object->statut == 3 || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data - && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->invoice_advance->reopen))) // A paid invoice (partially or completely) + && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->facture->invoice_advance->reopen))) // A paid invoice (partially or completely) { if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice { @@ -4179,7 +4181,7 @@ else if ($id > 0 || ! empty($ref)) // Validate if ($object->statut == Facture::STATUS_DRAFT && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (! empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) { print ''; } @@ -4200,22 +4202,22 @@ else if ($id > 0 || ! empty($ref)) // Request a direct debit order if ($object->statut > Facture::STATUS_DRAFT && $object->paye == 0 && $num == 0) { - if ($resteapayer > 0) - { - if ($user->rights->prelevement->bons->creer) - { - $langs->load("withdrawals"); - print ''.$langs->trans("MakeWithdrawRequest").''; - } - else - { - //print ''.$langs->trans("MakeWithdrawRequest").''; - } - } - else - { - //print ''.$langs->trans("MakeWithdrawRequest").''; - } + if ($resteapayer > 0) + { + if ($user->rights->prelevement->bons->creer) + { + $langs->load("withdrawals"); + print ''.$langs->trans("MakeWithdrawRequest").''; + } + else + { + //print ''.$langs->trans("MakeWithdrawRequest").''; + } + } + else + { + //print ''.$langs->trans("MakeWithdrawRequest").''; + } } // Create payment @@ -4364,8 +4366,8 @@ else if ($id > 0 || ! empty($ref)) $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref); $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id; - $genallowed = $user->rights->facture->creer; - $delallowed = $user->rights->facture->supprimer; + $genallowed = $user->rights->facture->lire; + $delallowed = $user->rights->facture->creer; print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); $somethingshown = $formfile->numoffiles; @@ -4378,7 +4380,7 @@ else if ($id > 0 || ! empty($ref)) // Show online payment link $useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)); - if ($object->statut != 0 && $useonlinepayment) + if ($object->statut != Facture::STATUS_DRAFT && $useonlinepayment) { print '
'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; diff --git a/htdocs/compta/facture/class/api_deprecated_invoice.class.php b/htdocs/compta/facture/class/api_deprecated_invoice.class.php index 360c065a5f2..ac2086fc87e 100644 --- a/htdocs/compta/facture/class/api_deprecated_invoice.class.php +++ b/htdocs/compta/facture/class/api_deprecated_invoice.class.php @@ -23,7 +23,7 @@ * API class for invoice object * * @smart-auto-routing false - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} * @deprecated Use Invoices instead (defined in api_invoices.class.php) */ @@ -31,7 +31,7 @@ class InvoiceApi extends DolibarrApi { /** * - * @var array $FIELDS Mandatory fields, checked when create and update object + * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( 'socid' @@ -46,7 +46,7 @@ class InvoiceApi extends DolibarrApi * Constructor Warning: Deprecated * * @url GET invoice/ - * + * */ function __construct() { @@ -59,7 +59,7 @@ class InvoiceApi extends DolibarrApi * Get properties of a invoice object Warning: Deprecated * * Return an array with invoice informations - * + * * @param int $id ID of invoice * @return array|mixed data without useless information * @@ -67,16 +67,16 @@ class InvoiceApi extends DolibarrApi * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } - + $result = $this->invoice->fetch($id); if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -86,9 +86,9 @@ class InvoiceApi extends DolibarrApi /** * List invoices Warning: Deprecated - * + * * Get a list of invoices - * + * * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list @@ -101,15 +101,15 @@ class InvoiceApi extends DolibarrApi * @url GET invoice/list * @url GET invoice/list/{mode} * @url GET thirdparty/{socid}/invoice/list - * @url GET thirdparty/{socid}/invoice/list/{mode} + * @url GET thirdparty/{socid}/invoice/list/{mode} */ - function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid=0, $mode='') { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $socid=0, $mode='') { global $db, $conf; - + $obj_ret = array(); - + $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $socid; - + // If the internal user must only see his customers, force searching by him $search_sale = 0; if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; @@ -117,27 +117,27 @@ class InvoiceApi extends DolibarrApi $sql = "SELECT s.rowid"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) $sql.= " FROM ".MAIN_DB_PREFIX."facture as s"; - + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale $sql.= ' WHERE s.entity IN ('.getEntity('facture').')'; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc"; if ($socid) $sql.= " AND s.fk_soc = ".$socid; if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - - + + // Example of use $mode if ($mode == 'draft') $sql.= " AND s.fk_statut IN (0)"; if ($mode == 'unpaid') $sql.= " AND s.fk_statut IN (1)"; if ($mode == 'paid') $sql.= " AND s.fk_statut IN (2)"; if ($mode == 'cancelled') $sql.= " AND s.fk_statut IN (3)"; - + // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - + $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { @@ -180,10 +180,10 @@ class InvoiceApi extends DolibarrApi } return $obj_ret; } - + /** * Create invoice object Warning: Deprecated - * + * * @param array $request_data Request datas * @return int ID of invoice * @@ -196,7 +196,7 @@ class InvoiceApi extends DolibarrApi } // Check mandatory fields $result = $this->_validate($request_data); - + foreach($request_data as $field => $value) { $this->invoice->$field = $value; } @@ -213,9 +213,9 @@ class InvoiceApi extends DolibarrApi * Update invoice Warning: Deprecated * * @param int $id Id of invoice to update - * @param array $request_data Datas - * @return int - * + * @param array $request_data Datas + * @return int + * * @url PUT invoice/{id} */ function put($id, $request_data = NULL) @@ -223,12 +223,12 @@ class InvoiceApi extends DolibarrApi if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } - + $result = $this->invoice->fetch($id); if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -237,20 +237,20 @@ class InvoiceApi extends DolibarrApi if ($field == 'id') continue; $this->invoice->$field = $value; } - + if($this->invoice->update($id, DolibarrApiAccess::$user)) return $this->get ($id); - + return false; } - + /** * Delete invoice Warning: Deprecated * * @param int $id Invoice ID * @return type - * - * @url DELETE invoice/{id} + * + * @url DELETE invoice/{id} */ function delete($id) { @@ -261,31 +261,31 @@ class InvoiceApi extends DolibarrApi if( ! $result ) { throw new RestException(404, 'Facture not found'); } - + if( ! DolibarrApi::_checkAccessToResource('facture',$this->facture->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - + if( !$this->invoice->delete(DolibarrApiAccess::$user)) { throw new RestException(500); } - + return array( 'success' => array( 'code' => 200, 'message' => 'Facture deleted' ) ); - + } - + /** * Validate fields before create or update object - * + * * @param array $data Datas to validate * @return array - * + * * @throws RestException */ function _validate($data) diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index d8a5a231593..222404411d7 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -15,9 +15,9 @@ * along with this program. If not, see . */ - use Luracast\Restler\RestException; +use Luracast\Restler\RestException; - require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; /** * API class for invoices @@ -71,10 +71,17 @@ class Invoices extends DolibarrApi throw new RestException(404, 'Invoice not found'); } + // Get payment details + $this->invoice->totalpaye = $this->invoice->getSommePaiement(); + $this->invoice->totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $this->invoice->totaldeposits = $this->invoice->getSumDepositsUsed(); + $this->invoice->resteapayer = price2num($this->invoice->total_ttc - $this->invoice->totalpaye - $this->invoice->totalcreditnotes - $this->invoice->totaldeposits, 'MT'); + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + $this->invoice->fetchObjectLinked(); return $this->_cleanObjectDatas($this->invoice); } @@ -94,7 +101,7 @@ class Invoices extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -210,6 +217,142 @@ class Invoices extends DolibarrApi return $this->invoice->id; } + /** + * Get lines of an invoice + * + * @param int $id Id of invoice + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->invoice->getLinesArray(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + + /** + * Update a line to a given invoice + * + * @param int $id Id of invoice to update + * @param int $lineid Id of line to update + * @param array $request_data InvoiceLine data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->invoice->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->date_start, + $request_data->date_end, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->situation_percent, + $request_data->fk_unit, + $request_data->multicurrency_subprice + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } + + /** + * Deletes a line of a given invoice + * + * @param int $id Id of invoice + * @param int $lineid Id of the line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return array + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function deleteLine($id, $lineid) { + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($lineid)) { + throw new RestException(400, 'Line ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + 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->deleteline($lineid); + if( $result < 0) { + throw new RestException(405, $this->invoice->error); + } + + $result = $this->invoice->fetch($id); + + $this->invoice->getLinesArray(); + $result = array(); + foreach ($this->invoice->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + /** * Update invoice * @@ -276,95 +419,15 @@ class Invoices extends DolibarrApi ); } - /** - * Get lines of a given invoice - * - * @param int $id Id of invoice - * - * @url GET {id}/lines - * - * @return array - */ - function getLines($id) { - if(! DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $result = $this->invoice->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Invoice not found'); - } - - if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->invoice->getLinesArray(); - $result = array(); - foreach ($this->invoice->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - - /** - * Deletes a line of a given invoice - * - * @param int $id Id of invoice - * @param int $lineid Id of the line to delete - * - * @url DELETE {id}/lines/{lineid} - * - * @return array - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 - */ - function deleteLine($id, $lineid) { - - if(! DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); - } - if(empty($lineid)) { - throw new RestException(400, 'Line ID is mandatory'); - } - - if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { - 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->deleteline($lineid); - if( $result < 0) { - throw new RestException(405, $this->invoice->error); - } - - $result = $this->invoice->fetch($id); - - $this->invoice->getLinesArray(); - $result = array(); - foreach ($this->invoice->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - - - - /** * Add a line to a given invoice * * Exemple of POST query : { "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null } * * @param int $id Id of invoice - * @param array $request_data Invoiceline data + * @param array $request_data InvoiceLine data * - * @url POST {id}/addline + * @url POST {id}/lines * * @return int */ @@ -421,7 +484,7 @@ class Invoices extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } throw new RestException(400, 'Unable to insert the new line. Check your inputs.'); @@ -482,7 +545,7 @@ class Invoices extends DolibarrApi /** * Validate an invoice * - * @param int $id Order ID + * @param int $id Invoice ID * @param int $idwarehouse Warehouse ID * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @@ -589,6 +652,247 @@ class Invoices extends DolibarrApi } + /** + * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount) + * + * @param int $id Id of invoice + * @param int $discountid Id of discount + * + * @url POST {id}/usediscount/{discountid} + * + * @return int + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function useDiscount($id, $discountid) { + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + if(empty($discountid)) { + throw new RestException(400, 'Discount ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + 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->insert_discount($discountid); + if( $result < 0) { + throw new RestException(405, $this->invoice->error); + } + + return $result; + } + + /** + * Add an available credit note discount to payments of an existing invoice (Consume the credit note) + * + * @param int $id Id of invoice + * @param int $discountid Id of a discount coming from a credit note + * + * @url POST {id}/usecreditnote/{discountid} + * + * @return int + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function useCreditNote($id, $discountid) { + + require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php'; + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + if(empty($discountid)) { + throw new RestException(400, 'Credit ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $discount = new DiscountAbsolute($this->db); + $result = $discount->fetch($discountid); + if( ! $result ) { + throw new RestException(404, 'Credit not found'); + } + + $result = $discount->link_to_invoice(0, $id); + if( $result < 0) { + throw new RestException(405, $discount->error); + } + + return $result; + } + + /** + * Get list of payments of a given invoice + * + * @param int $id Id of invoice + * + * @url GET {id}/payments + * + * @return array + * @throws 400 + * @throws 401 + * @throws 404 + * @throws 405 + */ + function getPayments($id) { + + if(! DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + 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 invoice + * + * The model schema is defined by the PaymentData class. + * + * @param int $id Id of invoice + * @param string $datepaye {@from body} Payment date {@type timestamp} + * @param int $paiementid {@from body} Payment mode Id {@min 1} + * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} + * @param int $accountid {@from body} Account Id {@min 1} + * @param string $num_paiement {@from body} Payment number (optional) + * @param string $comment {@from body} Note (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') + * @param string $chqbank {@from body} Issuer bank name (optional) + * + * @url POST {id}/payments + * + * @return int Payment ID + * @throws 400 + * @throws 401 + * @throws 404 + */ + function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement='', $comment='', $chqemetteur='', $chqbank='') { + global $conf; + + require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $payment_data; + + if (! empty($conf->banque->enabled)) { + if(empty($accountid)) { + throw new RestException(400, 'Account ID is mandatory'); + } + } + + if(empty($paiementid)) { + throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + } + + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement(); + $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $totaldeposits = $this->invoice->getSumDepositsUsed(); + $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + + $this->db->begin(); + // Clean parameters amount if payment is for a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = -$resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = -$newvalue; + } else { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = $resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = $newvalue; + } + + + // Creation of payment line + $paiement = new Paiement($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 = $paiementid; + $paiement->paiementcode = dol_getIdFromCode($this->db,$paiementid,'c_paiement','id','code',1); + $paiement->num_paiement = $num_paiement; + $paiement->note = $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); + } + + if (! empty($conf->banque->enabled)) { + $label='(CustomerInvoicePayment)'; + + if($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { + throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); + } + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)'; // Refund of a credit note + $result=$paiement->addPaymentToBank(DolibarrApiAccess::$user,'payment',$label,$accountid,$chqemetteur,$chqbank); + if ($result < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + } + } + $this->db->commit(); + return $paiement_id; + } + /** * Clean sensible object datas * @@ -600,6 +904,10 @@ class Invoices extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index dd42c8d3fb7..b46c249d1b0 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -201,19 +201,40 @@ class FactureRec extends CommonInvoice } } - // Add object linked - if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) - { - foreach($this->linked_objects as $origin => $origin_id) - { - $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) - { - $this->error=$this->db->lasterror(); - $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 + } + + // 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) + { + $this->error=$this->db->lasterror(); + $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) + { + $this->error=$this->db->lasterror(); + $error++; + } + } + } + } if ($error) { diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 6452c689215..6f36bd016b4 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -52,7 +52,7 @@ class Facture extends CommonInvoice public $table_element='facture'; public $table_element_line = 'facturedet'; public $fk_element = 'fk_facture'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='bill'; /** @@ -79,6 +79,8 @@ class Facture extends CommonInvoice public $remise_percent; public $total_ht=0; public $total_tva=0; + public $total_localtax1=0; + public $total_localtax2=0; public $total_ttc=0; public $revenuestamp; @@ -448,6 +450,11 @@ class Facture extends CommonInvoice $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 + } + // Add object linked if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects)) { @@ -460,7 +467,7 @@ class Facture extends CommonInvoice $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -471,7 +478,7 @@ class Facture extends CommonInvoice $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -747,7 +754,7 @@ class Facture extends CommonInvoice * @param int $invertdetail Reverse sign of amounts for lines * @return int <0 if KO, >0 if OK */ - function createFromCurrent($user,$invertdetail=0) + function createFromCurrent(User $user, $invertdetail=0) { global $conf; @@ -948,11 +955,12 @@ class Facture extends CommonInvoice * Load an object from an order and create a new invoice into database * * @param Object $object Object source + * @param User $user Object user * @return int <0 if KO, 0 if nothing done, 1 if OK */ - function createFromOrder($object) + function createFromOrder($object, User $user) { - global $user,$hookmanager; + global $hookmanager; $error=0; @@ -971,6 +979,8 @@ class Facture extends CommonInvoice $line->subprice = $object->lines[$i]->subprice; $line->total_ht = $object->lines[$i]->total_ht; $line->total_tva = $object->lines[$i]->total_tva; + $line->total_localtax1 = $object->lines[$i]->total_localtax1; + $line->total_localtax2 = $object->lines[$i]->total_localtax2; $line->total_ttc = $object->lines[$i]->total_ttc; $line->vat_src_code = $object->lines[$i]->vat_src_code; $line->tva_tx = $object->lines[$i]->tva_tx; @@ -1122,6 +1132,10 @@ class Facture extends CommonInvoice $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_tva)) + $label.= '
' . $langs->trans('LT1') . ': ' . price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
' . $langs->trans('LT2') . ': ' . price($this->total_localtax2, 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 ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref; @@ -1147,9 +1161,10 @@ class Facture extends CommonInvoice $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend; + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), $picto, ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= ($max?dol_trunc($this->ref,$max):$this->ref); + $result .= $linkend; if ($addlinktonotes) { @@ -1192,7 +1207,7 @@ class Facture extends CommonInvoice $sql.= ', f.datec as datec'; $sql.= ', f.date_valid as datev'; $sql.= ', f.tms as datem'; - $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf'; + $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf, f.last_main_doc'; $sql.= ', f.fk_facture_source'; $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams'; $sql.= ', f.situation_cycle_ref, f.situation_counter, f.situation_final'; @@ -1261,6 +1276,7 @@ class Facture extends CommonInvoice $this->user_author = $obj->fk_user_author; $this->user_valid = $obj->fk_user_valid; $this->modelpdf = $obj->model_pdf; + $this->last_main_doc = $obj->last_main_doc; $this->situation_cycle_ref = $obj->situation_cycle_ref; $this->situation_counter = $obj->situation_counter; $this->situation_final = $obj->situation_final; @@ -1575,7 +1591,7 @@ class Facture extends CommonInvoice /** - * Add a discount line into invoice using an existing absolute discount + * 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 @@ -1641,7 +1657,7 @@ class Facture extends CommonInvoice $result=$this->update_price(1); if ($result > 0) { - // Create linke between discount and invoice line + // Create link between discount and invoice line $result=$remise->link_to_invoice($lineid,0); if ($result < 0) { @@ -2686,6 +2702,11 @@ class Facture extends CommonInvoice return -2; } } + else + { + dol_syslog(get_class($this)."::addline status of order must be Draft to allow use of ->addline()", LOG_ERR); + return -3; + } } /** @@ -2698,7 +2719,7 @@ class Facture extends CommonInvoice * @param double $remise_percent Pourcentage de remise de la ligne * @param int $date_start Date de debut de validite du service * @param int $date_end Date de fin de validite du service - * @param double $txtva VAT Rate + * @param double $txtva VAT Rate (Can be '8.5', '8.5 (ABC)') * @param double $txlocaltax1 Local tax 1 rate * @param double $txlocaltax2 Local tax 2 rate * @param string $price_base_type HT or TTC @@ -3493,11 +3514,12 @@ class Facture extends CommonInvoice /** - * Renvoi liste des factures remplacables - * Statut validee ou abandonnee pour raison autre + non payee + aucun paiement + pas deja remplacee + * Return list of invoices qualified to be replaced by another invoice. + * Invoices matching the following rules are returned: + * (Status validated or abandonned for a reason 'other') + not payed + no payment at all + not already replaced * - * @param int $socid Id societe - * @return array Tableau des factures ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) + * @param int $socid Id thirdparty + * @return array Array of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1) */ function list_replacable_invoices($socid=0) { @@ -3540,12 +3562,12 @@ class Facture extends CommonInvoice /** - * Renvoi liste des factures qualifiables pour correction par avoir - * Les factures qui respectent les regles suivantes sont retournees: - * (validee + paiement en cours) ou classee (payee completement ou payee partiellement) + pas deja remplacee + pas deja avoir + * Return list of invoices qualified to be corrected by a credit note. + * Invoices matching the following rules are returned: + * (validated + payment on process) or classified (payed completely or payed partiely) + not already replaced + not already a credit note * - * @param int $socid Id societe - * @return array Tableau des factures ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) + * @param int $socid Id thirdparty + * @return array Array of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>) */ function list_qualified_avoir_invoices($socid=0) { diff --git a/htdocs/compta/facture/class/facturestats.class.php b/htdocs/compta/facture/class/facturestats.class.php index b2fd603a394..b6874862286 100644 --- a/htdocs/compta/facture/class/facturestats.class.php +++ b/htdocs/compta/facture/class/facturestats.class.php @@ -39,7 +39,7 @@ class FactureStats extends Stats var $from; var $field; var $where; - + /** * Constructor @@ -56,8 +56,8 @@ class FactureStats extends Stats $this->db = $db; $this->socid = ($socid > 0 ? $socid : 0); $this->userid = $userid; - $this->cachefilesuffix = $mode; - + $this->cachefilesuffix = $mode; + if ($mode == 'customer') { $object=new Facture($this->db); @@ -195,7 +195,7 @@ class FactureStats extends Stats return $this->_getAllByYear($sql); } - + /** * Return nb, amount of predefined product for year * @@ -218,7 +218,7 @@ class FactureStats extends Stats return $this->_getAllByProduct($sql); } - - + + } diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index deffb252d9c..622b1bc7731 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -34,8 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; if (! empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; - //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; } require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; @@ -129,526 +129,520 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (GETPOST('cancel','alpha')) $action=''; + if (GETPOST('cancel','alpha')) $action=''; - // Selection of new fields - include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Set note - include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + // Set note + 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 - // Do we click on purge search criteria ? - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers - { - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_montant_mode=''; - $search_montant_term=''; - $day=''; - $year=''; - $month=''; - $day_date_when=''; - $year_date_when=''; - $month_date_when=''; - $search_recurring=''; - $search_frequency=''; - $search_unit_frequency=''; - $search_array_options=array(); - } + // Do we click on purge search criteria ? + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers + { + $search_ref=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $search_montant_mode=''; + $search_montant_term=''; + $day=''; + $year=''; + $month=''; + $day_date_when=''; + $year_date_when=''; + $month_date_when=''; + $search_recurring=''; + $search_frequency=''; + $search_unit_frequency=''; + $search_array_options=array(); + } - // Mass actions - /*$objectclass='MyObject'; + // Mass actions + /*$objectclass='MyObject'; $objectlabel='MyObject'; $permtoread = $user->rights->mymodule->read; $permtodelete = $user->rights->mymodule->delete; $uploaddir = $conf->mymodule->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ - // Create predefined invoice - if ($action == 'add') - { - if (! GETPOST('titre')) - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors'); - $action = "create"; - $error++; - } + // Create predefined invoice + if ($action == 'add') + { + if (! GETPOST('titre')) + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors'); + $action = "create"; + $error++; + } - $frequency=GETPOST('frequency', 'int'); - $reyear=GETPOST('reyear'); - $remonth=GETPOST('remonth'); - $reday=GETPOST('reday'); - $rehour=GETPOST('rehour'); - $remin=GETPOST('remin'); - $nb_gen_max=GETPOST('nb_gen_max', 'int'); - //if (empty($nb_gen_max)) $nb_gen_max =0; + $frequency=GETPOST('frequency', 'int'); + $reyear=GETPOST('reyear'); + $remonth=GETPOST('remonth'); + $reday=GETPOST('reday'); + $rehour=GETPOST('rehour'); + $remin=GETPOST('remin'); + $nb_gen_max=GETPOST('nb_gen_max', 'int'); + //if (empty($nb_gen_max)) $nb_gen_max =0; - if (GETPOST('frequency')) - { - if (empty($reyear) || empty($remonth) || empty($reday)) - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors'); - $action = "create"; - $error++; - } - if ($nb_gen_max === '') - { - setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors'); - $action = "create"; - $error++; - } - } + if (GETPOST('frequency')) + { + if (empty($reyear) || empty($remonth) || empty($reday)) + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Date")), null, 'errors'); + $action = "create"; + $error++; + } + if ($nb_gen_max === '') + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("MaxPeriodNumber")), null, 'errors'); + $action = "create"; + $error++; + } + } - if (! $error) - { - $object->titre = GETPOST('titre', 'alpha'); - $object->note_private = GETPOST('note_private','none'); - $object->note_public = GETPOST('note_public','none'); - $object->usenewprice = GETPOST('usenewprice'); + if (! $error) + { + $object->titre = GETPOST('titre', 'alpha'); + $object->note_private = GETPOST('note_private','none'); + $object->note_public = GETPOST('note_public','none'); + $object->usenewprice = GETPOST('usenewprice'); - $object->frequency = $frequency; - $object->unit_frequency = GETPOST('unit_frequency', 'alpha'); - $object->nb_gen_max = $nb_gen_max; - $object->auto_validate = GETPOST('auto_validate', 'int'); + $object->frequency = $frequency; + $object->unit_frequency = GETPOST('unit_frequency', 'alpha'); + $object->nb_gen_max = $nb_gen_max; + $object->auto_validate = GETPOST('auto_validate', 'int'); - $object->fk_project = $projectid; + $object->fk_project = $projectid; - $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear); - $object->date_when = $date_next_execution; + $date_next_execution = dol_mktime($rehour, $remin, 0, $remonth, $reday, $reyear); + $object->date_when = $date_next_execution; - // Get first contract linked to invoice used to generate template - if ($id > 0) - { - $srcObject = new Facture($db); - $srcObject->fetch(GETPOST('facid','int')); + // Get first contract linked to invoice used to generate template + if ($id > 0) + { + $srcObject = new Facture($db); + $srcObject->fetch(GETPOST('facid','int')); - $srcObject->fetchObjectLinked(); + $srcObject->fetchObjectLinked(); - if (! empty($srcObject->linkedObjectsIds['contrat'])) - { - $contractidid = reset($srcObject->linkedObjectsIds['contrat']); + if (! empty($srcObject->linkedObjectsIds['contrat'])) + { + $contractidid = reset($srcObject->linkedObjectsIds['contrat']); - $object->origin = 'contrat'; - $object->origin_id = $contractidid; - $object->linked_objects[$object->origin] = $object->origin_id; - } - } + $object->origin = 'contrat'; + $object->origin_id = $contractidid; + $object->linked_objects[$object->origin] = $object->origin_id; + } + } - $db->begin(); + $db->begin(); - $oldinvoice = new Facture($db); - $oldinvoice->fetch($id); + $oldinvoice = new Facture($db); + $oldinvoice->fetch($id); - $result = $object->create($user, $oldinvoice->id); - if ($result > 0) - { - $result=$oldinvoice->delete($user, 1); - if ($result < 0) - { - $error++; - setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors'); - $action = "create"; - } - } - else - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } + $result = $object->create($user, $oldinvoice->id); + if ($result > 0) + { + $result=$oldinvoice->delete($user, 1); + if ($result < 0) + { + $error++; + setEventMessages($oldinvoice->error, $oldinvoice->errors, 'errors'); + $action = "create"; + } + } + else + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } - if (! $error) - { - $db->commit(); + if (! $error) + { + $db->commit(); - header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); - exit; - } - else - { - $db->rollback(); + header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); + exit; + } + else + { + $db->rollback(); - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } - } - } + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } + } + } - // Delete - if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) - { - $object->delete($user); - header("Location: " . $_SERVER['PHP_SELF'] ); - exit; - } + // Delete + if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) + { + $object->delete($user); + header("Location: " . $_SERVER['PHP_SELF'] ); + exit; + } - // Update field - // Set condition - if ($action == 'setconditions' && $user->rights->facture->creer) - { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + // Update field + // Set condition + if ($action == 'setconditions' && $user->rights->facture->creer) + { + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - } - // Set mode - elseif ($action == 'setmode' && $user->rights->facture->creer) - { - $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - } - // Set project - elseif ($action == 'classin' && $user->rights->facture->creer) - { - $object->setProject(GETPOST('projectid', 'int')); - } - // Set bank account - elseif ($action == 'setref' && $user->rights->facture->creer) - { - //var_dump(GETPOST('ref', 'alpha'));exit; - $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); - if ($result > 0) - { - $object->titre = GETPOST('ref', 'alpha'); - $object->ref = $object->titre; - } - else dol_print_error($db, $object->error, $object->errors); - } - // Set bank account - elseif ($action == 'setbankaccount' && $user->rights->facture->creer) - { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); - } - // Set frequency and unit frequency - elseif ($action == 'setfrequency' && $user->rights->facture->creer) - { - $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); - } - // Set next date of execution - elseif ($action == 'setdate_when' && $user->rights->facture->creer) - { - $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); - if (!empty($date)) $object->setNextDate($date); - } - // Set max period - elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) - { - $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); - } - // Set auto validate - elseif ($action == 'setauto_validate' && $user->rights->facture->creer) - { - $object->setAutoValidate(GETPOST('auto_validate', 'int')); - } + } + // Set mode + elseif ($action == 'setmode' && $user->rights->facture->creer) + { + $result=$object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + } + // Set project + elseif ($action == 'classin' && $user->rights->facture->creer) + { + $object->setProject(GETPOST('projectid', 'int')); + } + // Set bank account + elseif ($action == 'setref' && $user->rights->facture->creer) + { + //var_dump(GETPOST('ref', 'alpha'));exit; + $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); + if ($result > 0) + { + $object->titre = GETPOST('ref', 'alpha'); + $object->ref = $object->titre; + } + else dol_print_error($db, $object->error, $object->errors); + } + // Set bank account + elseif ($action == 'setbankaccount' && $user->rights->facture->creer) + { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + } + // Set frequency and unit frequency + elseif ($action == 'setfrequency' && $user->rights->facture->creer) + { + $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); + } + // Set next date of execution + elseif ($action == 'setdate_when' && $user->rights->facture->creer) + { + $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); + if (!empty($date)) $object->setNextDate($date); + } + // Set max period + elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) + { + $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); + } + // Set auto validate + elseif ($action == 'setauto_validate' && $user->rights->facture->creer) + { + $object->setAutoValidate(GETPOST('auto_validate', 'int')); + } - // Delete line - if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) - { - $object->fetch($id); - $object->fetch_thirdparty(); + // Delete line + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id); + $object->fetch_thirdparty(); - $db->begin(); + $db->begin(); - $line=new FactureLigneRec($db); + $line=new FactureLigneRec($db); - // For triggers - $line->id = $lineid; + // For triggers + $line->id = $lineid; - if ($line->delete($user) > 0) - { - $result=$object->update_price(1); + if ($line->delete($user) > 0) + { + $result=$object->update_price(1); - if ($result > 0) - { - $db->commit(); - $object->fetch($object->id); // Reload lines - } - else - { - $db->rollback(); - setEventMessages($db->lasterror(), null, 'errors'); - } - } - else - { - $db->rollback(); - setEventMessages($line->error, $line->errors, 'errors'); - } - } - else if ($action == 'update_extras') - { - // Fill array 'array_options' with data from update form - $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($result > 0) + { + $db->commit(); + $object->fetch($object->id); // Reload lines + } + else + { + $db->rollback(); + setEventMessages($db->lasterror(), null, 'errors'); + } + } + else + { + $db->rollback(); + setEventMessages($line->error, $line->errors, 'errors'); + } + } + else if ($action == 'update_extras') + { + // Fill array 'array_options' with data from update form + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + if ($ret < 0) $error++; - if (! $error) { + if (! $error) { + $result = $object->insertExtraFields(); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + } - $result = $object->insertExtraFields(); - if ($result < 0) { - $error ++; - } - } else if ($reshook < 0) - $error ++; + // Add a new line + if ($action == 'addline' && $user->rights->facture->creer) + { + $langs->load('errors'); + $error = 0; - if ($error) { - $action = 'edit_extras'; - setEventMessages($object->error, $object->errors, 'errors'); - } - } + // Set if we used free entry or predefined product + $predef=''; + $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $price_ht = GETPOST('price_ht'); + if (GETPOST('prod_entry_mode') == 'free') + { + $idprod=0; + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + } + else + { + $idprod=GETPOST('idprod', 'int'); + $tva_tx = ''; + } - // Add a new line - if ($action == 'addline' && $user->rights->facture->creer) - { - $langs->load('errors'); - $error = 0; + $qty = GETPOST('qty' . $predef); + $remise_percent = GETPOST('remise_percent' . $predef); - // Set if we used free entry or predefined product - $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - $price_ht = GETPOST('price_ht'); - if (GETPOST('prod_entry_mode') == 'free') - { - $idprod=0; - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - } - else - { - $idprod=GETPOST('idprod', 'int'); - $tva_tx = ''; - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) + { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key . $predef]); + } + } - $qty = GETPOST('qty' . $predef); - $remise_percent = GETPOST('remise_percent' . $predef); + if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) { + setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); + $error ++; + } + if ($qty == '') { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error ++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); + $error ++; + } + if ($qty < 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); + $error ++; + } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) - { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key . $predef]); - } - } + if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) + { + $ret = $object->fetch($id); + if ($ret < 0) { + dol_print_error($db, $object->error); + exit(); + } + $ret = $object->fetch_thirdparty(); - if (empty($idprod) && ($price_ht < 0) && ($qty < 0)) { - setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && GETPOST('type') < 0) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && (! ($price_ht >= 0) || $price_ht == '')) // Unit price can be 0 but not '' - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); - $error ++; - } - if ($qty == '') { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error ++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); - $error ++; - } - if ($qty < 0) { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; - } + // Clean parameters + $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); + $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); + $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) - { - $ret = $object->fetch($id); - if ($ret < 0) { - dol_print_error($db, $object->error); - exit(); - } - $ret = $object->fetch_thirdparty(); + // Define special_code for special lines + $special_code = 0; + // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices - // Clean parameters - $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); - $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); - $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT'); + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $tva_tx par celui du produit + // Ecrase $base_price_type par celui du produit + // Replaces $fk_unit with the product's + if (! empty($idprod)) + { + $prod = new Product($db); + $prod->fetch($idprod); - // Define special_code for special lines - $special_code = 0; - // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices + $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $tva_tx par celui du produit - // Ecrase $base_price_type par celui du produit - // Replaces $fk_unit with the product's - if (! empty($idprod)) - { - $prod = new Product($db); - $prod->fetch($idprod); + // Update if prices fields are defined + $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); + $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); + if (empty($tva_tx)) $tva_npr=0; - $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; - // Update if prices fields are defined - $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); - $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr=0; + // We define price for product + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + { + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; + if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility + { + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (empty($tva_tx)) $tva_npr=0; + } + } + elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + { + require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + $prodcustprice = new Productcustomerprice($db); - // We define price for product - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) - { - $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; - $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; - $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; - $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - if (! empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; - if (empty($tva_tx)) $tva_npr=0; - } - } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); - $prodcustprice = new Productcustomerprice($db); - - $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); - - $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - if ($result) - { - if (count($prodcustprice->lines) > 0) - { - $pu_ht = price($prodcustprice->lines[0]->price); - $pu_ttc = price($prodcustprice->lines[0]->price_ttc); - $price_base_type = $prodcustprice->lines[0]->price_base_type; - $tva_tx = $prodcustprice->lines[0]->tva_tx; - } - } - } + $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); + if ($result) + { + if (count($prodcustprice->lines) > 0) + { + $pu_ht = price($prodcustprice->lines[0]->price); + $pu_ttc = price($prodcustprice->lines[0]->price_ttc); + $price_base_type = $prodcustprice->lines[0]->price_base_type; + $tva_tx = $prodcustprice->lines[0]->tva_tx; + } + } + } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx)); $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); - // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? - if (! empty($price_ht)) - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } - // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - elseif ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { - $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); - } - else - { - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } - } + // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ? + if (! empty($price_ht)) + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); + } + // On reevalue prix selon taux tva car taux tva transaction peut etre different + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). + elseif ($tmpvat != $tmpprodvat) + { + if ($price_base_type != 'HT') + { + $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); + } + else + { + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); + } + } - $desc = ''; + $desc = ''; - // Define output language - if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { - $outputlangs = $langs; - $newlang = ''; - if (empty($newlang) && GETPOST('lang_id','aZ09')) - $newlang = GETPOST('lang_id','aZ09'); - if (empty($newlang)) - $newlang = $object->thirdparty->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } + // Define output language + if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) + { + $outputlangs = $langs; + $newlang = ''; + if (empty($newlang) && GETPOST('lang_id','aZ09')) + $newlang = GETPOST('lang_id','aZ09'); + if (empty($newlang)) + $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) + { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } - $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; - } - else - { - $desc = $prod->description; - } + $desc = (! empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; + } + else + { + $desc = $prod->description; + } - $desc = dol_concatdesc($desc, $product_desc); + $desc = dol_concatdesc($desc, $product_desc); - // Add custom code and origin country into description - if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) - { - $tmptxt = '('; - if (! empty($prod->customcode)) - $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; - if (! empty($prod->customcode) && ! empty($prod->country_code)) - $tmptxt .= ' - '; - if (! empty($prod->country_code)) - $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); - $tmptxt .= ')'; - $desc = dol_concatdesc($desc, $tmptxt); + // Add custom code and origin country into description + if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (! empty($prod->customcode) || ! empty($prod->country_code))) + { + $tmptxt = '('; + if (! empty($prod->customcode)) + $tmptxt .= $langs->transnoentitiesnoconv("CustomCode") . ': ' . $prod->customcode; + if (! empty($prod->customcode) && ! empty($prod->country_code)) + $tmptxt .= ' - '; + if (! empty($prod->country_code)) + $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, 0, $db, $langs, 0); + $tmptxt .= ')'; + $desc = dol_concatdesc($desc, $tmptxt); - } + } - $type = $prod->type; - $fk_unit = $prod->fk_unit; + $type = $prod->type; + $fk_unit = $prod->fk_unit; - } - else - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); - $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); - $tva_tx = str_replace('*', '', $tva_tx); - if (empty($tva_tx)) $tva_npr=0; - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - $desc = $product_desc; - $type = GETPOST('type'); - $fk_unit= GETPOST('units', 'alpha'); - } + } + else + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); + $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); + $tva_tx = str_replace('*', '', $tva_tx); + if (empty($tva_tx)) $tva_npr=0; + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + $desc = $product_desc; + $type = GETPOST('type'); + $fk_unit= GETPOST('units', 'alpha'); + } - // Margin - $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value + // Margin + $fournprice = price2num(GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); + $buyingprice = price2num(GETPOST('buying_price' . $predef) != '' ? GETPOST('buying_price' . $predef) : ''); // If buying_price is '0', we must keep this value - // Local Taxes - $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); - $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); + // Local Taxes + $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr); + $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr); - $info_bits = 0; - if ($tva_npr) - $info_bits |= 0x01; + $info_bits = 0; + if ($tva_npr) + $info_bits |= 0x01; - if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) - { - $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); - setEventMessages($mesg, null, 'errors'); - } - else - { - // Insert line - $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); + if (! empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))) + { + $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); + setEventMessages($mesg, null, 'errors'); + } + else + { + // Insert line + $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); - if ($result > 0) - { - /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + if ($result > 0) + { + /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; @@ -665,114 +659,114 @@ if (empty($reshook)) $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines - unset($_POST['prod_entry_mode']); + unset($_POST['prod_entry_mode']); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['price_ht']); - unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['product_ref']); - unset($_POST['product_label']); - unset($_POST['product_desc']); - unset($_POST['fournprice']); - unset($_POST['buying_price']); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprod']); - unset($_POST['units']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['multicurrency_price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); - unset($_POST['situations']); - unset($_POST['progress']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + unset($_POST['situations']); + unset($_POST['progress']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } - $action = ''; - } - } - } + $action = ''; + } + } + } - elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel','alpha')) - { - if (! $object->fetch($id) > 0) dol_print_error($db); - $object->fetch_thirdparty(); + elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel','alpha')) + { + if (! $object->fetch($id) > 0) dol_print_error($db); + $object->fetch_thirdparty(); - // Clean parameters - $date_start = ''; - $date_end = ''; - //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - $description = dol_htmlcleanlastbr(GETPOST('product_desc','none') ? GETPOST('product_desc','none') : GETPOST('desc','none')); - $pu_ht = GETPOST('price_ht'); - $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - $qty = GETPOST('qty'); + // Clean parameters + $date_start = ''; + $date_end = ''; + //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $description = dol_htmlcleanlastbr(GETPOST('product_desc','none') ? GETPOST('product_desc','none') : GETPOST('desc','none')); + $pu_ht = GETPOST('price_ht'); + $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $qty = GETPOST('qty'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); - $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); + // Define vat_rate + $vat_rate = str_replace('*', '', $vat_rate); + $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); + $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); - // Add buying price - $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); - $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value + // Add buying price + $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); + $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); - $objectline = new FactureLigneRec($db); - if ($objectline->fetch(GETPOST('lineid'))) - { - $objectline->array_options=$array_options; - $result=$objectline->insertExtraFields(); - if ($result < 0) - { - setEventMessages($langs->trans('Error').$result, null, 'errors'); - } - } + $objectline = new FactureLigneRec($db); + if ($objectline->fetch(GETPOST('lineid'))) + { + $objectline->array_options=$array_options; + $result=$objectline->insertExtraFields(); + if ($result < 0) + { + setEventMessages($langs->trans('Error').$result, null, 'errors'); + } + } - // Unset extrafield - if (is_array($extralabelsline)) - { - // Get extra fields - foreach ($extralabelsline as $key => $value) - { - unset($_POST["options_" . $key]); - } - } + // Unset extrafield + if (is_array($extralabelsline)) + { + // Get extra fields + foreach ($extralabelsline as $key => $value) + { + unset($_POST["options_" . $key]); + } + } - // Define special_code for special lines - $special_code=GETPOST('special_code'); - if (! GETPOST('qty')) $special_code=3; + // Define special_code for special lines + $special_code=GETPOST('special_code'); + if (! GETPOST('qty')) $special_code=3; - /*$line = new FactureLigne($db); + /*$line = new FactureLigne($db); $line->fetch(GETPOST('lineid')); $percent = $line->get_prev_progress($object->id); @@ -784,69 +778,69 @@ if (empty($reshook)) $result = -1; }*/ - // Check minimum price - $productid = GETPOST('productid', 'int'); - if (! empty($productid)) - { - $product = new Product($db); - $product->fetch($productid); + // Check minimum price + $productid = GETPOST('productid', 'int'); + if (! empty($productid)) + { + $product = new Product($db); + $product->fetch($productid); - $type = $product->type; + $type = $product->type; - $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) - $price_min = $product->multiprices_min [$object->thirdparty->price_level]; + $price_min = $product->price_min; + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + $price_min = $product->multiprices_min [$object->thirdparty->price_level]; - $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); + $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); - // Check price is not lower than minimum (check is done only for standard or replacement invoices) - if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) { - setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); - $error ++; - } - } else { - $type = GETPOST('type'); - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + // Check price is not lower than minimum (check is done only for standard or replacement invoices) + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - price2num(GETPOST('remise_percent')) / 100) < price2num($price_min))) { + setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors'); + $error ++; + } + } else { + $type = GETPOST('type'); + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - // Check parameters - if (GETPOST('type') < 0) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error ++; - } - } - if ($qty < 0) { - $langs->load("errors"); - setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); - $error ++; - } + // Check parameters + if (GETPOST('type') < 0) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error ++; + } + } + if ($qty < 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors'); + $error ++; + } - // Update line - if (! $error) - { - $result = $object->updateline( - GETPOST('lineid'), - $description, - $pu_ht, - $qty, - $vat_rate, - $localtax1_rate, - $localtax1_rate, - GETPOST('productid'), - GETPOST('remise_percent'), - 'HT', - $info_bits, - 0, - 0, - $type, - 0, - $special_code, - $label, - GETPOST('units') - ); + // Update line + if (! $error) + { + $result = $object->updateline( + GETPOST('lineid'), + $description, + $pu_ht, + $qty, + $vat_rate, + $localtax1_rate, + $localtax1_rate, + GETPOST('productid'), + GETPOST('remise_percent'), + 'HT', + $info_bits, + 0, + 0, + $type, + 0, + $special_code, + $label, + GETPOST('units') + ); - if ($result >= 0) - { - /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + if ($result >= 0) + { + /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $outputlangs = $langs; $newlang = ''; @@ -863,50 +857,50 @@ if (empty($reshook)) $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); }*/ - $object->fetch($object->id); // Reload lines + $object->fetch($object->id); // Reload lines - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['productid']); - unset($_POST['remise_percent']); - unset($_POST['price_ht']); - unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['product_ref']); - unset($_POST['product_label']); - unset($_POST['product_desc']); - unset($_POST['fournprice']); - unset($_POST['buying_price']); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['productid']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['multicurrency_price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprod']); - unset($_POST['units']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); - unset($_POST['situations']); - unset($_POST['progress']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } + unset($_POST['situations']); + unset($_POST['progress']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } } @@ -987,7 +981,7 @@ if ($action == 'create') $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext.=$key.' = '.$langs->trans($val).'
'; } $htmltext.='
'; @@ -998,20 +992,20 @@ if ($action == 'create') print ''; print ''; $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); + print $doleditor->Create(1); // Private note if (empty($user->societe_id)) { - print ''; - print ''; - print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); - print ''; - print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - // print ' - print ''; + print ''; + print ''; + print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext, 1, 'help', '', 0, 2, 'noteprivate'); + print ''; + print ''; + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + // print ' + print ''; } // Author @@ -1083,7 +1077,7 @@ if ($action == 'create') print ""; - dol_fiche_end(); + dol_fiche_end(); $title = $langs->trans("ProductsAndServices"); @@ -1102,10 +1096,10 @@ if ($action == 'create') // Show object lines if (! empty($object->lines)) { - $disableedit=1; - $disablemove=1; - $disableremove=1; - $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + $disableedit=1; + $disablemove=1; + $disableremove=1; + $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } print "\n"; @@ -1125,9 +1119,9 @@ if ($action == 'create') print "\n"; print '
'; - print '     '; - print ''; - print '
'; + print '     '; + print ''; + print '
'; print "\n"; } else @@ -1171,53 +1165,53 @@ else if ($action != 'editref') $morehtmlref.=$form->editfieldkey($object->ref, 'ref', $object->ref, $object, $user->rights->facture->creer, '', '', 0, 2); else $morehtmlref.= $form->editfieldval('', 'ref', $object->ref, $object, $user->rights->facture->creer, 'string'); - $morehtmlref.='
'; - // Ref customer - //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); - //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->facture->creer) - { - 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.='
'; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } - } - $morehtmlref.='
'; + $morehtmlref.='
'; + // Ref customer + //$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', 0, 1); + //$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->facture->creer, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.=$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->facture->creer) + { + 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.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
'; - dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); + dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; print '"; @@ -1309,7 +1303,7 @@ else $htmltext = ''.$langs->trans("FollowingConstantsWillBeSubstituted").':
'; foreach($substitutionarray as $key => $val) { - $htmltext.=$key.' = '.$langs->trans($val).'
'; + $htmltext.=$key.' = '.$langs->trans($val).'
'; } $htmltext.='
'; @@ -1337,16 +1331,16 @@ else print $langs->trans('RIB'); print ''; + print ''; print '
'.$langs->trans("Author").''.$author->getFullName($langs)."
'; if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon)) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; print ''; if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); } print ""; print ''; @@ -1356,12 +1350,12 @@ else $cols = 2; include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print ''; + print ''; - print '
'; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; + print '
'; /* @@ -1397,13 +1391,13 @@ else } else { - if ($object->frequency > 0) - { + if ($object->frequency > 0) + { print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); - } - else - { - print $langs->trans("NotARecurringInvoiceTemplate"); + } + else + { + print $langs->trans("NotARecurringInvoiceTemplate"); } } print ''; @@ -1412,16 +1406,16 @@ else print ''; if ($action == 'date_when' || $object->frequency > 0) { - print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); + print $form->editfieldkey($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day'); } else { - print $langs->trans("NextDateToExecution"); + print $langs->trans("NextDateToExecution"); } print ''; if ($action == 'date_when' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached'); + print $form->editfieldval($langs->trans("NextDateToExecution"), 'date_when', $object->date_when, $object, $user->rights->facture->creer, 'day', $object->date_when, null, '', '', 0, 'strikeIfMaxNbGenReached'); } print ''; print ''; @@ -1430,20 +1424,20 @@ else print ''; if ($action == 'nb_gen_max' || $object->frequency > 0) { - print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); + print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); } else { - print $langs->trans("MaxPeriodNumber"); + print $langs->trans("MaxPeriodNumber"); } print ''; if ($action == 'nb_gen_max' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer); + print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max?$object->nb_gen_max:'', $object, $user->rights->facture->creer); } else { - print ''; + print ''; } print ''; print ''; @@ -1451,51 +1445,51 @@ else // Status of generated invoices print ''; if ($action == 'auto_validate' || $object->frequency > 0) - print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); + print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); else - print $langs->trans("StatusOfGeneratedInvoices"); + print $langs->trans("StatusOfGeneratedInvoices"); print ''; - $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); + $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); if ($action == 'auto_validate' || $object->frequency > 0) { - print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select); + print $form->editfieldval($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer, $select); } print ''; print ''; print ''; - // Frequencry/Recurring section - if ($object->frequency > 0) - { - print '
'; + // Frequencry/Recurring section + if ($object->frequency > 0) + { + print '
'; - if (empty($conf->cron->enabled)) - { - print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); - } + if (empty($conf->cron->enabled)) + { + print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); + } - print '
'; - print ''; + print '
'; + print '
'; - // Nb of generation already done - print ''; - print ''; - print ''; + // Nb of generation already done + print ''; + print ''; + print ''; - // Date last - print ''; - print ''; + // Date last + print ''; + print ''; - print '
'.$langs->trans("NbOfGenerationDone").''; - print $object->nb_gen_done?$object->nb_gen_done:'0'; - print '
'.$langs->trans("NbOfGenerationDone").''; + print $object->nb_gen_done?$object->nb_gen_done:'0'; + print '
'; - print $langs->trans("DateLastGeneration"); - print ''; - print dol_print_date($object->date_last_gen, 'dayhour'); - print '
'; + print $langs->trans("DateLastGeneration"); + print ''; + print dol_print_date($object->date_last_gen, 'dayhour'); + print '
'; + print ''; - print '
'; + print '
'; } print '
'; @@ -1514,7 +1508,7 @@ else '; if (! empty($conf->use_javascript_ajax) && $object->statut == 0) { - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } print '
'; @@ -1522,22 +1516,22 @@ else // Show object lines if (! empty($object->lines)) { - //$disableedit=1; - //$disablemove=1; - $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + //$disableedit=1; + //$disablemove=1; + $ret = $object->printObjectLines($action, $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } // Form to add new line if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline') { - if ($action != 'editline') - { - // Add free products/services - $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice + if ($action != 'editline') + { + // Add free products/services + $object->formAddObjectLine(0, $mysoc, $object->thirdparty); // No date selector for template invoice - $parameters = array(); - $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - } + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + } } print "\n"; @@ -1570,13 +1564,13 @@ else else { print ''; - } - } + } + } } else { print ''; - } + } //} //if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer) @@ -1594,12 +1588,12 @@ else // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); + $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; + print '
'; } } diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index c7c13b1628a..b1b95b99f7b 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -138,7 +138,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 9241726aaec..1f45a7cec3e 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -174,7 +174,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -1247,7 +1247,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->creer; print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index 3d2daf5a53d..d85255fbf4e 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -84,7 +84,7 @@ dol_mkdir($dir); $stats = new FactureStats($db, $socid, $mode, ($userid>0?$userid:0)); if ($mode == 'customer') { - if ($object_status != '' && $object_status >= -1) $stats->where .= ' AND f.fk_statut IN ('.$db->escape($object_status).')'; + if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->escape($object_status).')'; } if ($mode == 'supplier') { @@ -227,12 +227,13 @@ complete_head_from_modules($conf,$langs,null,$head,$h,$type); dol_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1); -$tmp_companies = $form->select_thirdparty_list($socid,'socid',$filter,1, 0, 0, array(), '', 1); +// We use select_thirdparty_list instead of select_company so we can use $filter and share same code for customer and supplier. +$tmp_companies = $form->select_thirdparty_list($socid, 'socid', $filter, 1, 0, 0, array(), '', 1); //Array passed as an argument to Form::selectarray to build a proper select input $companies = array(); foreach ($tmp_companies as $value) { - $companies[$value['value']] = $value['label']; + $companies[$value['key']] = $value['label']; } print '
'; diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index 103ec747e37..d00c54cc9e2 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -136,7 +136,7 @@ if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is usele if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { $sql = "SELECT f.facnumber"; - $sql.= ", f.rowid, f.total as total_ht, f.tva as total_tva, f.total_ttc"; + $sql.= ", f.rowid, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.ref_client"; $sql.= ", f.type"; $sql.= ", s.nom as name"; $sql.= ", s.rowid as socid"; @@ -178,6 +178,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $facturestatic->total_ht=$obj->total_ht; $facturestatic->total_tva=$obj->total_tva; $facturestatic->total_ttc=$obj->total_ttc; + $facturestatic->ref_client=$obj->ref_client; $facturestatic->type=$obj->type; print $facturestatic->getNomUrl(1,''); print ''; @@ -218,7 +219,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) */ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) { - $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type"; + $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type, f.ref_supplier"; $sql.= ", s.nom as name"; $sql.= ", s.rowid as socid"; $sql.= ", s.code_fournisseur"; @@ -253,6 +254,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $facturesupplierstatic->total_ht=$obj->total_ht; $facturesupplierstatic->total_tva=$obj->total_tva; $facturesupplierstatic->total_ttc=$obj->total_ttc; + $facturesupplierstatic->ref_supplier=$obj->ref_supplier; $facturesupplierstatic->type=$obj->type; print $facturesupplierstatic->getNomUrl(1,'',16); print ''; diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index 398f70ad36a..e966eba4a47 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -169,6 +169,20 @@ if ($action == 'create') $charge->paiementtype=$charge->mode_reglement_id?$charge->mode_reglement_id:$charge->paiementtype; $total = $charge->amount; + if (! empty($conf->use_javascript_ajax)) + { + print "\n".''."\n"; + } print load_fiche_titre($langs->trans("DoPayment")); print "
\n"; @@ -188,14 +202,12 @@ if ($action == 'create') print ''; - print ""; - - print ''; + print ''; print '\n"; print '\n"; print '\n"; - print '\n"; - print ''; + /*print '\n"; + print '';*/ $sql = "SELECT sum(p.amount) as total"; $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; @@ -207,12 +219,8 @@ if ($action == 'create') $sumpaid = $obj->total; $db->free(); } - print ''; - print ''; - - print ''; - print "'; - print ''; + /*print ''; + print '';*/ print ''; + $html_class = ''; + if (!empty($data['fk_facture'])) $html_class = 'facid-'.$data['fk_facture']; + elseif (!empty($data['fk_paiement'])) $html_class = 'payid-'.$data['fk_paiement']; + + print ''; print "\n"; print '\n"; diff --git a/htdocs/compta/salaries/card.php b/htdocs/compta/salaries/card.php index 47d4c027185..a456777f631 100644 --- a/htdocs/compta/salaries/card.php +++ b/htdocs/compta/salaries/card.php @@ -73,6 +73,8 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $dateep=dol_mktime(12,0,0, $_POST["dateepmonth"], $_POST["dateepday"], $_POST["dateepyear"]); if (empty($datev)) $datev=$datep; + $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement'); + $object->accountid=GETPOST("accountid") > 0 ? GETPOST("accountid","int") : 0; $object->fk_user=GETPOST("fk_user") > 0 ? GETPOST("fk_user","int") : 0; $object->datev=$datev; @@ -82,7 +84,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $object->datesp=$datesp; $object->dateep=$dateep; $object->note=GETPOST("note"); - $object->type_payment=GETPOST("paymenttype") > 0 ? GETPOST("paymenttype", "int") : 0; + $object->type_payment=($type_payment > 0 ? $type_payment : 0); $object->num_payment=GETPOST("num_payment"); $object->fk_user_author=$user->id; @@ -101,7 +103,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Employee")), null, 'errors'); $error++; } - if (empty($object->type_payment) || $object->type_payment < 0) + if (empty($type_payment) || $type_payment < 0) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentMode")), null, 'errors'); $error++; @@ -292,7 +294,7 @@ if ($action == 'create') // Type payment print ''; // Number diff --git a/htdocs/compta/salaries/class/paymentsalary.class.php b/htdocs/compta/salaries/class/paymentsalary.class.php index 7fbbaf43d48..57d2d94f1a3 100644 --- a/htdocs/compta/salaries/class/paymentsalary.class.php +++ b/htdocs/compta/salaries/class/paymentsalary.class.php @@ -349,7 +349,7 @@ class PaymentSalary extends CommonObject $sql.= ", '".$this->db->idate($this->datev)."'"; $sql.= ", ".$this->amount; $sql.= ", ".($this->salary > 0 ? $this->salary : "null"); - $sql.= ", '".$this->db->escape($this->type_payment)."'"; + $sql.= ", ".$this->db->escape($this->type_payment); $sql.= ", '".$this->db->escape($this->num_payment)."'"; if ($this->note) $sql.= ", '".$this->db->escape($this->note)."'"; $sql.= ", '".$this->db->escape($this->label)."'"; diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php index 6928d3e38f6..2da142aff15 100644 --- a/htdocs/compta/salaries/index.php +++ b/htdocs/compta/salaries/index.php @@ -114,7 +114,7 @@ $sql.= " AND s.entity = ".$conf->entity; // Search criteria if ($search_ref) $sql.=" AND s.rowid=".$search_ref; -if ($search_user) $sql.=natural_search(array('u.login', 'u.lastname', 'u.firstname', 'u.email', 'u.note'), $search_user); +if ($search_user) $sql.=natural_search(array('u.login', 'u.lastname', 'u.firstname', 'u.email'), $search_user); if ($search_label) $sql.=natural_search(array('s.label'), $search_label); if ($search_amount) $sql.=natural_search("s.amount", $search_amount, 1); if ($search_account > 0) $sql .=" AND b.fk_account=".$search_account; diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 13a2d29aff9..6149a2a92b1 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -654,7 +654,9 @@ if ($id > 0) else { - print ''; + print ''; + print ''; + print ''; } print '\n"; diff --git a/htdocs/compta/sociales/document.php b/htdocs/compta/sociales/document.php index ce2f853c935..048d35d73f1 100644 --- a/htdocs/compta/sociales/document.php +++ b/htdocs/compta/sociales/document.php @@ -88,6 +88,7 @@ if ($action == 'setlib' && $user->rights->tax->charges->creer) setEventMessages($object->error, $object->errors, 'errors'); } + /* * View */ @@ -125,7 +126,7 @@ if ($object->id) } else { $morehtmlref.=''; } - } + } $morehtmlref.=''; $linkback = '' . $langs->trans("BackToList") . ''; @@ -153,9 +154,9 @@ if ($object->id) print '
".$langs->trans("SocialContribution")."
'.$langs->trans("Ref").''.$chid.'
'.$langs->trans("Ref").''.$chid.'
'.$langs->trans("Type")."".$charge->type_libelle."
'.$langs->trans("Period")."".dol_print_date($charge->periode,'day')."
'.$langs->trans("Label").''.$charge->lib."
'.$langs->trans("DateDue")."".dol_print_date($charge->date_ech,'day')."
'.$langs->trans("Amount")."".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("DateDue")."".dol_print_date($charge->date_ech,'day')."
'.$langs->trans("Amount")."".price($charge->amount,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("AlreadyPaid").''.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("RemainderToPay").''.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
".$langs->trans("Payment").'
'.$langs->trans("AlreadyPaid").''.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("RemainderToPay").''.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("Date").''; $datepaye = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); @@ -294,7 +302,12 @@ if ($action == 'create') if ($sumpaid < $objp->amount) { $namef = "amount_".$objp->id; - print ''; + $nameRemain = "remain_".$objp->id; + if (!empty($conf->use_javascript_ajax)) + print img_picto("Auto fill",'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->amount - $sumpaid)."'"); + $remaintopay=$objp->amount - $sumpaid; + print ''; + print ''; } else { diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php index c3231ecccdd..4b5351324a3 100644 --- a/htdocs/compta/recap-compta.php +++ b/htdocs/compta/recap-compta.php @@ -1,6 +1,7 @@ * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2017 Pierre-Henry Favre * * 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 @@ -39,6 +40,9 @@ $result = restrictedArea($user, 'societe', $id, '&societe'); $object = new Societe($db); if ($id > 0) $object->fetch($id); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('recapcomptacard','globalcard')); + // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST('sortfield','alpha'); @@ -60,6 +64,9 @@ $arrayfields=array( /* * Actions */ +$parameters = array('socid' => $id); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object); // Note that $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // None @@ -139,13 +146,20 @@ if ($id > 0) $userstatic->id=$objf->userid; $userstatic->login=$objf->login; - $TData[] = array( + $values = array( + 'fk_facture' => $objf->facid, 'date' => $fac->date, 'link' => $fac->getNomUrl(1), 'status' => $fac->getLibStatut(2,$totalpaye), 'amount' => $fac->total_ttc, 'author' => $userstatic->getLoginUrl(1) ); + + $parameters = array('socid' => $id, 'values' => &$values, 'fac' => $fac, 'userstatic' => $userstatic); + $reshook = $hookmanager->executeHooks('facdao', $parameters, $object); // Note that $parameters['values'] and $object may have been modified by some hooks + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + $TData[] = $values; $TDataSort[] = $fac->date; // Paiements @@ -175,13 +189,20 @@ if ($id > 0) $userstatic->id=$objp->userid; $userstatic->login=$objp->login; - $TData[] = array( + $values = array( + 'fk_paiement' => $objp->rowid, 'date' => $db->jdate($objp->dp), 'link' => $langs->trans("Payment") .' '. $paymentstatic->getNomUrl(1), 'status' => '', 'amount' => -$objp->amount, 'author' => $userstatic->getLoginUrl(1) ); + + $parameters = array('socid' => $id, 'values' => &$values, 'fac' => $fac, 'userstatic' => $userstatic, 'paymentstatic' => $paymentstatic); + $reshook = $hookmanager->executeHooks('paydao', $parameters, $object); // Note that $parameters['values'] and $object may have been modified by some hooks + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + $TData[] = $values; $TDataSort[] = $db->jdate($objp->dp); $j++; @@ -224,7 +245,11 @@ if ($id > 0) // Display array foreach($TData as $data) { - print '
".dol_print_date($data['date'],'day')."'.$data['link']."
'; print fieldLabel('PaymentMode','selectpaymenttype',1).''; - $form->select_types_paiements(GETPOST("paymenttype"), "paymenttype"); + $form->select_types_paiements(GETPOST("paymenttype"), "paymenttype", '', 2); print '
'.$langs->trans("None").'
'.$langs->trans("None").'
'.$langs->trans("AlreadyPaid")." :".price($totalpaye)."
'; print '
'; - + print '
'; - + dol_fiche_end(); $modulepart = 'tax'; diff --git a/htdocs/compta/sociales/info.php b/htdocs/compta/sociales/info.php index b67c844a7b9..dfa6439a3f4 100644 --- a/htdocs/compta/sociales/info.php +++ b/htdocs/compta/sociales/info.php @@ -42,6 +42,8 @@ $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', $id, 'chargesociales','charges'); +$object = new ChargeSociales($db); + /* * Actions @@ -68,7 +70,6 @@ $title = $langs->trans("SocialContribution") . ' - ' . $langs->trans("Info"); $help_url = 'EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:Módulo Impuestos y cargas sociales (IVA, impuestos)'; llxHeader("",$title,$help_url); -$object = new ChargeSociales($db); $object->fetch($id); $object->info($id); diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 7e9437f5442..494533fce75 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -39,7 +39,8 @@ class Contact extends CommonObject { public $element='contact'; public $table_element='socpeople'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $picto = 'contact'; public $civility_id; // In fact we store civility_code public $civility_code; @@ -1053,8 +1054,12 @@ class Contact extends CommonObject $linkend=''; } - if ($withpicto) $result.=($linkstart.img_object($label, 'contact', 'class="classfortooltip"').$linkend.' '); - $result.=$linkstart.($maxlen?dol_trunc($this->getFullName($langs),$maxlen):$this->getFullName($langs)).$linkend; + + $result.=$linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.=($maxlen?dol_trunc($this->getFullName($langs),$maxlen):$this->getFullName($langs)); + $result.=$linkend; + return $result; } diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 4b0356c8e52..a97e6687126 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -160,7 +160,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } diff --git a/htdocs/contrat/admin/contract_extrafields.php b/htdocs/contrat/admin/contract_extrafields.php index 509c5307ef8..abfc2b2b65d 100644 --- a/htdocs/contrat/admin/contract_extrafields.php +++ b/htdocs/contrat/admin/contract_extrafields.php @@ -41,7 +41,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/contrat/admin/contractdet_extrafields.php b/htdocs/contrat/admin/contractdet_extrafields.php index 39c691e7ddc..e2eb2bacc6c 100644 --- a/htdocs/contrat/admin/contractdet_extrafields.php +++ b/htdocs/contrat/admin/contractdet_extrafields.php @@ -41,7 +41,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 8c8a3c2fc11..b761eb1864b 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -109,16 +109,16 @@ if (empty($reshook)) if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) { - $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); + $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - setEventMessages($object->error, $object->errors, 'errors'); - } + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) @@ -130,47 +130,47 @@ if (empty($reshook)) } if (! $error) { - $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } } // Si ajout champ produit predefini if (GETPOST('mode')=='predefined') { - $date_start=''; - $date_end=''; - if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) - { - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - } - if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) - { - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - } + $date_start=''; + $date_end=''; + if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) + { + $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + } + if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) + { + $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + } } // Si ajout champ produit libre if (GETPOST('mode')=='libre') { - $date_start_sl=''; - $date_end_sl=''; - if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear')) - { - $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear')); - } - if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear')) - { - $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear')); - } + $date_start_sl=''; + $date_end_sl=''; + if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear')) + { + $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear')); + } + if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear')) + { + $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear')); + } } // Param dates @@ -181,23 +181,23 @@ if (empty($reshook)) $date_end_real_update=''; if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) { - $date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); + $date_start_update=dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); } if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) { - $date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); + $date_end_update=dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); } if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) { - $date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); + $date_start_real_update=dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); } if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) { - $date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); + $date_end_real_update=dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); } if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) { - $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); } // Add contract @@ -228,74 +228,74 @@ if (empty($reshook)) if (! $error) { $object->socid = $socid; - $object->date_contrat = $datecontrat; + $object->date_contrat = $datecontrat; - $object->commercial_suivi_id = GETPOST('commercial_suivi_id','int'); - $object->commercial_signature_id = GETPOST('commercial_signature_id','int'); + $object->commercial_suivi_id = GETPOST('commercial_suivi_id','int'); + $object->commercial_signature_id = GETPOST('commercial_signature_id','int'); - $object->note_private = GETPOST('note_private','alpha'); - $object->note_public = GETPOST('note_public','alpha'); - $object->fk_project = GETPOST('projectid','int'); - $object->remise_percent = GETPOST('remise_percent','alpha'); - $object->ref = GETPOST('ref','alpha'); - $object->ref_customer = GETPOST('ref_customer','alpha'); - $object->ref_supplier = GETPOST('ref_supplier','alpha'); + $object->note_private = GETPOST('note_private','alpha'); + $object->note_public = GETPOST('note_public','alpha'); + $object->fk_project = GETPOST('projectid','int'); + $object->remise_percent = GETPOST('remise_percent','alpha'); + $object->ref = GETPOST('ref','alpha'); + $object->ref_customer = GETPOST('ref_customer','alpha'); + $object->ref_supplier = GETPOST('ref_supplier','alpha'); - // If creation from another object of another module (Example: origin=propal, originid=1) - if (! empty($origin) && ! empty($originid)) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = $origin; - if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs)) - { - $element = $regs[1]; - $subelement = $regs[2]; - } + // If creation from another object of another module (Example: origin=propal, originid=1) + if (! empty($origin) && ! empty($originid)) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $origin; + if (preg_match('/^([^_]+)_([^_]+)/i',$origin,$regs)) + { + $element = $regs[1]; + $subelement = $regs[2]; + } - // For compatibility - if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + // For compatibility + if ($element == 'order') { $element = $subelement = 'commande'; } + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } - $object->origin = $origin; - $object->origin_id = $originid; + $object->origin = $origin; + $object->origin_id = $originid; - // Possibility to add external linked objects with hooks - $object->linked_objects[$object->origin] = $object->origin_id; - if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects'])) - { - $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); - } + // Possibility to add external linked objects with hooks + $object->linked_objects[$object->origin] = $object->origin_id; + if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects'])) + { + $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); + } - $id = $object->create($user); - if ($id < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $id = $object->create($user); + if ($id < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - if ($id > 0) - { - dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); + if ($id > 0) + { + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); - $classname = ucfirst($subelement); - $srcobject = new $classname($db); + $classname = ucfirst($subelement); + $srcobject = new $classname($db); - dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); - $result=$srcobject->fetch($object->origin_id); - if ($result > 0) - { - $srcobject->fetch_thirdparty(); + dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); + $result=$srcobject->fetch($object->origin_id); + if ($result > 0) + { + $srcobject->fetch_thirdparty(); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject,'fetch_lines')) - { - $srcobject->fetch_lines(); - $lines = $srcobject->lines; - } + if (empty($lines) && method_exists($srcobject,'fetch_lines')) + { + $srcobject->fetch_lines(); + $lines = $srcobject->lines; + } - $fk_parent_line=0; - $num=count($lines); + $fk_parent_line=0; + $num=count($lines); - for ($i=0;$i<$num;$i++) - { - $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + for ($i=0;$i<$num;$i++) + { + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); if ($product_type == 1 || (! empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0,1)))) { // TODO Exclude also deee // service prédéfini @@ -326,12 +326,20 @@ if (empty($reshook)) { $label = $lines[$i]->product_label; } - $desc = ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):''; } else { - $desc = dol_htmlentitiesbr($lines[$i]->desc); - } + $desc = dol_htmlentitiesbr($lines[$i]->desc); + } + + // Extrafields + $array_options = array(); + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if + // trigger used + { + $lines[$i]->fetch_optionals($lines[$i]->rowid); + $array_options = $lines[$i]->array_options; + } $txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx . ' (' . $lines[$i]->vat_src_code . ')' : $lines[$i]->tva_tx; @@ -339,72 +347,72 @@ if (empty($reshook)) $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty); $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty); - $result = $object->addline( - $desc, - $lines[$i]->subprice, - $lines[$i]->qty, - $txtva, - $localtax1_tx, - $localtax2_tx, - $lines[$i]->fk_product, - $lines[$i]->remise_percent, - $lines[$i]->date_start, - $lines[$i]->date_end, - 'HT', - 0, - $lines[$i]->info_bits, - $lines[$i]->fk_fournprice, - $lines[$i]->pa_ht, - array(), - $lines[$i]->fk_unit - ); + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $txtva, + $localtax1_tx, + $localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $lines[$i]->date_start, + $lines[$i]->date_end, + 'HT', + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $array_options, + $lines[$i]->fk_unit + ); - if ($result < 0) - { - $error++; - break; - } + if ($result < 0) + { + $error++; + break; + } } - } - } - else - { - setEventMessages($srcobject->error, $srcobject->errors, 'errors'); - $error++; - } + } + } + else + { + setEventMessages($srcobject->error, $srcobject->errors, 'errors'); + $error++; + } - // Hooks - $parameters = array('objFrom' => $srcobject); - $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook - if ($reshook < 0) - $error++; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } - else - { - $result = $object->create($user); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else { - setEventMessages($object->error, $object->errors, 'errors'); - } - $action='create'; + // Hooks + $parameters = array('objFrom' => $srcobject); + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been + // modified by hook + if ($reshook < 0) + $error++; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } - } + else + { + $result = $object->create($user); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + } + $action='create'; + } + } } else if ($action == 'classin' && $user->rights->contrat->creer) { - $object->setProject(GETPOST('projectid')); + $object->setProject(GETPOST('projectid')); } // Add a new line @@ -429,72 +437,72 @@ if (empty($reshook)) $qty = GETPOST('qty'.$predef); $remise_percent = GETPOST('remise_percent'.$predef); - if ($qty == '') - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); - $error++; - } - if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); - $error++; - } + if ($qty == '') + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); + $error++; + } + if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); + $error++; + } - $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); - $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); - if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) - { - setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); - $error++; - } + $date_start = dol_mktime(GETPOST('date_start' . $predef . 'hour'), GETPOST('date_start' . $predef . 'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start' . $predef . 'month'), GETPOST('date_start' . $predef . 'day'), GETPOST('date_start' . $predef . 'year')); + $date_end = dol_mktime(GETPOST('date_end' . $predef . 'hour'), GETPOST('date_end' . $predef . 'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); + if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $error++; + } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } - if (! $error) - { + if (! $error) + { // Clean parameters $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); $price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT'); - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $tva_tx par celui du produit - // Ecrase $base_price_type par celui du produit - if ($idprod > 0) - { - $prod = new Product($db); - $prod->fetch($idprod); + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $tva_tx par celui du produit + // Ecrase $base_price_type par celui du produit + if ($idprod > 0) + { + $prod = new Product($db); + $prod->fetch($idprod); - // Update if prices fields are defined - $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id); - $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id); - if (empty($tva_tx)) $tva_npr=0; + // Update if prices fields are defined + $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id); + $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id); + if (empty($tva_tx)) $tva_npr=0; - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; - // On defini prix unitaire - if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) - { - $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; - $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; - $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; - $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) + // On defini prix unitaire + if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) + { + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; + } + elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; @@ -517,35 +525,35 @@ if (empty($reshook)) $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx)); // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - if ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { - $pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU'); - } - else - { - $pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU'); - } - } + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). + if ($tmpvat != $tmpprodvat) + { + if ($price_base_type != 'HT') + { + $pu_ht = price2num($pu_ttc / (1 + ($tmpvat/100)), 'MU'); + } + else + { + $pu_ttc = price2num($pu_ht * (1 + ($tmpvat/100)), 'MU'); + } + } - $desc=$prod->description; - $desc=dol_concatdesc($desc,$product_desc); - $fk_unit = $prod->fk_unit; - } - else + $desc=$prod->description; + $desc=dol_concatdesc($desc,$product_desc); + $fk_unit = $prod->fk_unit; + } + else { - $pu_ht=GETPOST('price_ht'); - $price_base_type = 'HT'; - $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0; // tva_tx field may be disabled, so we use vat rate 0 - $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0; - $desc=$product_desc; + $pu_ht=GETPOST('price_ht'); + $price_base_type = 'HT'; + $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0; // tva_tx field may be disabled, so we use vat rate 0 + $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0; + $desc=$product_desc; $fk_unit= GETPOST('units', 'alpha'); - } + } - $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr); - $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr); + $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty,$mysoc,$tva_npr); + $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty,$mysoc,$tva_npr); // ajout prix achat $fk_fournprice = $_POST['fournprice']; @@ -554,41 +562,41 @@ if (empty($reshook)) else $pa_ht = null; - $info_bits=0; - if ($tva_npr) $info_bits |= 0x01; + $info_bits=0; + if ($tva_npr) $info_bits |= 0x01; - if($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))) - { - $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency)); - $result = -1 ; - } - else + if($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min))) { - // Insert line - $result = $object->addline( - $desc, - $pu_ht, - $qty, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $idprod, - $remise_percent, - $date_start, - $date_end, - $price_base_type, - $pu_ttc, - $info_bits, - $fk_fournprice, - $pa_ht, - $array_options, - $fk_unit - ); - } + $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency)); + $result = -1 ; + } + else + { + // Insert line + $result = $object->addline( + $desc, + $pu_ht, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $idprod, + $remise_percent, + $date_start, + $date_end, + $price_base_type, + $pu_ttc, + $info_bits, + $fk_fournprice, + $pa_ht, + $array_options, + $fk_unit + ); + } - if ($result > 0) - { - // Define output language + if ($result > 0) + { + // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && ! empty($conf->global->CONTRACT_ADDON_PDF)) // No generation if default type not defined { $outputlangs = $langs; @@ -624,159 +632,159 @@ if (empty($reshook)) unset($_POST['dp_desc']); unset($_POST['idprod']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha')) { - if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) - { - setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); - $action = 'editline'; - $_GET['rowid'] = GETPOST('elrowid'); - $error++; - } + if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $action = 'editline'; + $_GET['rowid'] = GETPOST('elrowid'); + $error++; + } - if (!$error) { - $objectline = new ContratLigne($db); - if ($objectline->fetch(GETPOST('elrowid'))) - { - $db->begin(); + if (!$error) { + $objectline = new ContratLigne($db); + if ($objectline->fetch(GETPOST('elrowid'))) + { + $db->begin(); - if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; - if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; + if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; + if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; - $vat_rate = GETPOST('eltva_tx'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; + $vat_rate = GETPOST('eltva_tx'); + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); - $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); + // Define vat_rate + $vat_rate = str_replace('*', '', $vat_rate); + $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); + $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); - $txtva = $vat_rate; + $txtva = $vat_rate; - // Clean vat code - $vat_src_code=''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { - $vat_src_code = $reg[1]; - $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + // Clean vat code + $vat_src_code=''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { + $vat_src_code = $reg[1]; + $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. + } - // ajout prix d'achat - $fk_fournprice = $_POST['fournprice']; - if ( ! empty($_POST['buying_price']) ) - $pa_ht = $_POST['buying_price']; - else - $pa_ht = null; + // ajout prix d'achat + $fk_fournprice = $_POST['fournprice']; + if ( ! empty($_POST['buying_price']) ) + $pa_ht = $_POST['buying_price']; + else + $pa_ht = null; - $fk_unit = GETPOST('unit', 'alpha'); + $fk_unit = GETPOST('unit', 'alpha'); - $objectline->description=GETPOST('product_desc','none'); - $objectline->price_ht=GETPOST('elprice'); - $objectline->subprice=GETPOST('elprice'); - $objectline->qty=GETPOST('elqty'); - $objectline->remise_percent=GETPOST('elremise_percent'); - $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 - $objectline->vat_src_code=$vat_src_code; - $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; - $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; - $objectline->date_ouverture_prevue=$date_start_update; - $objectline->date_ouverture=$date_start_real_update; - $objectline->date_fin_validite=$date_end_update; - $objectline->date_cloture=$date_end_real_update; - $objectline->fk_user_cloture=$user->id; - $objectline->fk_fournprice=$fk_fournprice; - $objectline->pa_ht=$pa_ht; + $objectline->description=GETPOST('product_desc','none'); + $objectline->price_ht=GETPOST('elprice'); + $objectline->subprice=GETPOST('elprice'); + $objectline->qty=GETPOST('elqty'); + $objectline->remise_percent=GETPOST('elremise_percent'); + $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 + $objectline->vat_src_code=$vat_src_code; + $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; + $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; + $objectline->date_ouverture_prevue=$date_start_update; + $objectline->date_ouverture=$date_start_real_update; + $objectline->date_fin_validite=$date_end_update; + $objectline->date_cloture=$date_end_real_update; + $objectline->fk_user_cloture=$user->id; + $objectline->fk_fournprice=$fk_fournprice; + $objectline->pa_ht=$pa_ht; - if ($fk_unit > 0) { - $objectline->fk_unit = GETPOST('unit'); - } else { - $objectline->fk_unit = null; - } + if ($fk_unit > 0) { + $objectline->fk_unit = GETPOST('unit'); + } else { + $objectline->fk_unit = null; + } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - $objectline->array_options=$array_options; + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + $objectline->array_options=$array_options; - // TODO verifier price_min si fk_product et multiprix + // TODO verifier price_min si fk_product et multiprix - $result=$objectline->update($user); - if ($result > 0) - { - $db->commit(); - } - else - { - setEventMessages($objectline->error, $objectline->errors, 'errors'); - $db->rollback(); - } - } - else - { - setEventMessages($objectline->error, $objectline->errors, 'errors'); - } - } + $result=$objectline->update($user); + if ($result > 0) + { + $db->commit(); + } + else + { + setEventMessages($objectline->error, $objectline->errors, 'errors'); + $db->rollback(); + } + } + else + { + setEventMessages($objectline->error, $objectline->errors, 'errors'); + } + } } else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) { - $result = $object->deleteline(GETPOST('lineid'),$user); + $result = $object->deleteline(GETPOST('lineid'),$user); - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + if ($result >= 0) + { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) { - $result = $object->validate($user); + $result = $object->validate($user); } else if ($action == 'reopen' && $user->rights->contrat->creer) { - $result = $object->reopen($user); + $result = $object->reopen($user); } // Close all lines else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->closeAll($user); + $object->closeAll($user); } // Close all lines else if ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->activateAll($user); + $object->activateAll($user); } else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) @@ -821,21 +829,19 @@ if (empty($reshook)) // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); - if ($ret < 0) - $error ++; + if ($ret < 0) $error++; if (! $error) { - - $result = $object->insertExtraFields(); - if ($result < 0) { - $error ++; - } - } else if ($reshook < 0) - $error ++; + $result = $object->insertExtraFields(); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } if ($error) { $action = 'edit_extras'; - setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action=='setref_supplier') @@ -848,7 +854,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editref_supplier'; @@ -857,10 +863,10 @@ if (empty($reshook)) exit; } } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setref_customer') { @@ -873,8 +879,8 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { + $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editref_customer'; } else { @@ -882,58 +888,58 @@ if (empty($reshook)) exit; } } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setref') { - $cancelbutton = GETPOST('cancel','alpha'); + $cancelbutton = GETPOST('cancel','alpha'); - if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + if (!$cancelbutton) { + $result = $object->fetch($id); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } - $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'editref'; - } else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); - exit; - } - } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editref'; + } else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + exit; + } + } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } elseif ($action=='setdate_contrat') { - $cancelbutton = GETPOST('cancel','alpha'); + $cancelbutton = GETPOST('cancel','alpha'); - if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + if (!$cancelbutton) { + $result = $object->fetch($id); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $datacontrat=dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear')); - $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY'); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'editdate_contrat'; - } else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); - exit; - } - } - else { - header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); - exit; - } + $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'editdate_contrat'; + } else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id); + exit; + } + } + else { + header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id); + exit; + } } @@ -1051,74 +1057,74 @@ if ($action == 'create') { print load_fiche_titre($langs->trans('AddContract'),'','title_commercial.png'); - $soc = new Societe($db); - if ($socid>0) $soc->fetch($socid); + $soc = new Societe($db); + if ($socid>0) $soc->fetch($socid); - if (GETPOST('origin') && GETPOST('originid')) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = GETPOST('origin'); - if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs)) - { - $element = $regs[1]; - $subelement = $regs[2]; - } + if (GETPOST('origin') && GETPOST('originid')) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = GETPOST('origin'); + if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs)) + { + $element = $regs[1]; + $subelement = $regs[2]; + } - if ($element == 'project') - { - $projectid=GETPOST('originid'); - } - else - { - // For compatibility - if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + if ($element == 'project') + { + $projectid=GETPOST('originid'); + } + else + { + // For compatibility + if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } + if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } - dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); + dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); - $classname = ucfirst($subelement); - $objectsrc = new $classname($db); - $objectsrc->fetch(GETPOST('originid')); - if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines')) $objectsrc->fetch_lines(); - $objectsrc->fetch_thirdparty(); + $classname = ucfirst($subelement); + $objectsrc = new $classname($db); + $objectsrc->fetch(GETPOST('originid')); + if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines')) $objectsrc->fetch_lines(); + $objectsrc->fetch_thirdparty(); - $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); + $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); - $soc = $objectsrc->thirdparty; + $soc = $objectsrc->thirdparty; - $note_private = (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''); - $note_public = (! empty($objectsrc->note_public) ? $objectsrc->note_public : ''); + $note_private = (! empty($objectsrc->note_private) ? $objectsrc->note_private : ''); + $note_public = (! empty($objectsrc->note_public) ? $objectsrc->note_public : ''); - // Object source contacts list - $srccontactslist = $objectsrc->liste_contact(-1,'external',1); - } - } - else { + // Object source contacts list + $srccontactslist = $objectsrc->liste_contact(-1,'external',1); + } + } + else { $projectid = GETPOST('projectid','int'); $note_private = GETPOST("note_private"); $note_public = GETPOST("note_public"); } - $object->date_contrat = dol_now(); + $object->date_contrat = dol_now(); - print '
'; - print ''; + print ''; + print ''; - print ''; - print ''."\n"; - print ''; + print ''; + print ''."\n"; + print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - // Ref + // Ref print ''; @@ -1130,7 +1136,7 @@ if ($action == 'create') print ''; print ''; - // Thirdparty + // Thirdparty print ''; print ''; if ($socid>0) @@ -1144,7 +1150,7 @@ if ($action == 'create') { print ''; } print ''."\n"; @@ -1163,75 +1169,75 @@ if ($action == 'create') print ''; } - // Commercial suivi - print ''; + // Commercial suivi + print ''; - // Commercial signature - print ''; + // Commercial signature + print ''; - print '"; + print '"; - // Project - if (! empty($conf->projet->enabled)) - { - $formproject=new FormProjets($db); + // Project + if (! empty($conf->projet->enabled)) + { + $formproject=new FormProjets($db); - print '"; - } - - print ''; - - if (empty($user->societe_id)) - { - print ''; - } - - // Other attributes - $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - // Other attributes - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - print $object->showOptionals($extrafields, 'edit'); - } - - print "
'.$langs->trans('Ref').''; - if (! empty($modCodeContract->code_auto)) { - $tmpcode=$langs->trans("Draft"); - } else { - $tmpcode=''; - } + if (! empty($modCodeContract->code_auto)) { + $tmpcode=$langs->trans("Draft"); + } else { + $tmpcode=''; + } print $tmpcode; print '
'.$langs->trans('RefSupplier').'
'.$langs->trans('ThirdParty').''; print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300'); - print ' '.$langs->trans("AddThirdParty").''; + print ' '.$langs->trans("AddThirdParty").''; print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").''; - print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,''); - print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").''; + print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,''); + print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").''; - print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,''); - print '
'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").''; + print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,''); + print '
'.$langs->trans("Date").''; - $form->select_date($datecontrat,'',0,0,'',"contrat"); - print "
'.$langs->trans("Date").''; + $form->select_date($datecontrat,'',0,0,'',"contrat"); + print "
'.$langs->trans("Project").''; - $formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1); - print "
'.$langs->trans("NotePublic").''; - $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
'.$langs->trans("NotePrivate").''; - $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
\n"; - - dol_fiche_end(); - - print '
'; - print ''; - print '     '; - print ''; - print '
'; - - if (is_object($objectsrc)) - { - print ''; - print ''; - - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) - { - print '
'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); - } + print ''.$langs->trans("Project").''; + $formproject->select_projects(($soc->id>0?$soc->id:-1),$projectid,"projectid",0,0,1,1); + print ""; } - print "
\n"; + print ''.$langs->trans("NotePublic").''; + $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print ''; + + if (empty($user->societe_id)) + { + print ''.$langs->trans("NotePrivate").''; + $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print ''; + } + + // Other attributes + $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"', 'cols'=>3); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + // Other attributes + if (empty($reshook) && ! empty($extrafields->attribute_label)) { + print $object->showOptionals($extrafields, 'edit'); + } + + print "\n"; + + dol_fiche_end(); + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + + if (is_object($objectsrc)) + { + print ''; + print ''; + + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) + { + print '
'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); + } + } + + print "\n"; } else /* *************************************************************************** */ @@ -1240,105 +1246,105 @@ else /* */ /* *************************************************************************** */ { - $now=dol_now(); + $now=dol_now(); - if ($object->id > 0) - { - $object->fetch_thirdparty(); + if ($object->id > 0) + { + $object->fetch_thirdparty(); - $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed - if ($result < 0) dol_print_error($db,$object->error); + $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed + if ($result < 0) dol_print_error($db,$object->error); - $nbofservices=count($object->lines); + $nbofservices=count($object->lines); - $author = new User($db); - $author->fetch($object->user_author_id); + $author = new User($db); + $author->fetch($object->user_author_id); - $commercial_signature = new User($db); - $commercial_signature->fetch($object->commercial_signature_id); + $commercial_signature = new User($db); + $commercial_signature->fetch($object->commercial_signature_id); - $commercial_suivi = new User($db); - $commercial_suivi->fetch($object->commercial_suivi_id); + $commercial_suivi = new User($db); + $commercial_suivi->fetch($object->commercial_suivi_id); - $head = contract_prepare_head($object); + $head = contract_prepare_head($object); - $hselected = 0; + $hselected = 0; - dol_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract'); + dol_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract'); - /* + /* * Confirmation de la suppression du contrat */ - if ($action == 'delete') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1); + if ($action == 'delete') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1); - } + } - /* + /* * Confirmation de la validation */ - if ($action == 'valid') - { - $ref = substr($object->ref, 1, 4); - if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) - { - $numref = $object->getNextNumRef($object->thirdparty); - } - else - { - $numref = $object->ref; - } + if ($action == 'valid') + { + $ref = substr($object->ref, 1, 4); + if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) + { + $numref = $object->getNextNumRef($object->thirdparty); + } + else + { + $numref = $object->ref; + } - $text=$langs->trans('ConfirmValidateContract',$numref); + $text=$langs->trans('ConfirmValidateContract',$numref); - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1); + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1); - } + } - /* + /* * Confirmation de la fermeture */ - if ($action == 'close') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1); + if ($action == 'close') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1); - } - if ($action == 'activate') - { - print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ActivateAllOnContract"),$langs->trans("ConfirmActivateAllOnContract"),"confirm_activate",'',0,1); + } + if ($action == 'activate') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ActivateAllOnContract"),$langs->trans("ConfirmActivateAllOnContract"),"confirm_activate",'',0,1); - } + } - /* + /* * Contrat */ - if (! empty($object->brouillon) && $user->rights->contrat->creer) - { - print '
'; - print ''; - print ''; - } + if (! empty($object->brouillon) && $user->rights->contrat->creer) + { + print ''; + print ''; + print ''; + } - // Clone confirmation - if ($action == 'clone') { - $formquestion = array(array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); - print $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); - } + // Clone confirmation + if ($action == 'clone') { + $formquestion = array(array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))); + print $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneContract'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + } // Contract card - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref=''; - if (! empty($modCodeContract->code_auto)) { - $morehtmlref.=$object->ref; - } else { - $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3); - $morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2); - } + $morehtmlref=''; + if (! empty($modCodeContract->code_auto)) { + $morehtmlref.=$object->ref; + } else { + $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,3); + $morehtmlref.=$form->editfieldval("",'ref',$object->ref,$object,$user->rights->contrat->creer,'string','',0,2); + } $morehtmlref.='
'; // Ref customer @@ -1349,64 +1355,64 @@ else $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1); $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->contrat->creer) - { - 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.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.=''; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $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.='
'; + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->contrat->creer) + { + 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.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
'; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref); - print '
'; - print '
'; + print '
'; + print '
'; - print ''; + print '
'; - // Ligne info remises tiers - print ''; + // Ligne info remises tiers + print ''; - // Date - print ''; + // Date + print ''; print ''; print ''; - // Other attributes - $cols = 3; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print "
'.$langs->trans('Discount').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - $absolute_discount=$object->thirdparty->getAvailableDiscounts(); - print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; - print '
'.$langs->trans('Discount').''; + if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); + else print $langs->trans("CompanyHasNoRelativeDiscount"); + $absolute_discount=$object->thirdparty->getAvailableDiscounts(); + print '. '; + if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency)); + else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print '.'; + print '
'; print $form->editfieldkey("Date",'date_contrat',$object->date_contrat,$object,$user->rights->contrat->creer); print ''; @@ -1414,577 +1420,577 @@ else print '
"; + print ""; - print '
'; + print '
'; - if (! empty($object->brouillon) && $user->rights->contrat->creer) - { - print ''; - } + if (! empty($object->brouillon) && $user->rights->contrat->creer) + { + print ''; + } - echo '
'; + echo '
'; - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { - $blocname = 'contacts'; - $title = $langs->trans('ContactsAddresses'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) + { + $blocname = 'contacts'; + $title = $langs->trans('ContactsAddresses'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $blocname = 'notes'; - $title = $langs->trans('Notes'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $blocname = 'notes'; + $title = $langs->trans('Notes'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - $colorb='666666'; + $colorb='666666'; - $arrayothercontracts=$object->getListOfContracts('others'); + $arrayothercontracts=$object->getListOfContracts('others'); - /* + /* * Lines of contracts */ $productstatic=new Product($db); - $usemargins=0; + $usemargins=0; if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1; - $var=false; + $var=false; // Title line for service - $cursorline=1; - while ($cursorline <= $nbofservices) - { - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; + $cursorline=1; + while ($cursorline <= $nbofservices) + { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; - // Area with common detail of line - print ''; + // Area with common detail of line + print '
'; - $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,"; - $sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,"; - $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,"; - $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,"; - $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,"; - $sql.= " cd.fk_unit,"; - $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; - $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id; + $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,"; + $sql.= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,"; + $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,"; + $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,"; + $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,"; + $sql.= " cd.fk_unit,"; + $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; + $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; + $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id; - $result = $db->query($sql); - if ($result) - { - $total = 0; + $result = $db->query($sql); + if ($result) + { + $total = 0; - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - print ''; - if ($conf->global->PRODUCT_USE_UNITS) print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + if (!empty($conf->multicurrency->enabled)) { + print ''; + } + print ''; + if ($conf->global->PRODUCT_USE_UNITS) print ''; + print ''; if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; - print ''; - print "\n"; + print ''; + print "\n"; - $objp = $db->fetch_object($result); + $objp = $db->fetch_object($result); - // + // - if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) - { - print ''; - // Label - if ($objp->fk_product > 0) - { - print ''; + // Label + if ($objp->fk_product > 0) + { + print ''; - } - else + print ''; + } + else { - print '\n"; - } - // TVA - print ''; - // Price - print '\n"; - // Price multicurrency - if (!empty($conf->multicurrency->enabled)) { - print ''; - } - // Quantite - print ''; - // Unit - if($conf->global->PRODUCT_USE_UNITS) print ''; - // Remise - if ($objp->remise_percent > 0) - { - print '\n"; - } - else - { - print ''; - } + print '\n"; + } + // TVA + print ''; + // Price + print '\n"; + // Price multicurrency + if (!empty($conf->multicurrency->enabled)) { + print ''; + } + // Quantite + print ''; + // Unit + if($conf->global->PRODUCT_USE_UNITS) print ''; + // Remise + if ($objp->remise_percent > 0) + { + print '\n"; + } + else + { + print ''; + } // Margin if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; - // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) - print ''; + // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) + print ''; - print "\n"; + print "\n"; - // Dates of service planed and real - if ($objp->subprice >= 0) - { - $colspan = 6; + // Dates of service planed and real + if ($objp->subprice >= 0) + { + $colspan = 6; - if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { - $colspan = 8; - } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) { - $colspan = 7; - } + if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { + $colspan = 8; + } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) { + $colspan = 7; + } - print ''; - print ''; + print ''; - print ''; - } + print ''; + print ''; + } - // Display lines extrafields - if (is_array($extralabelslines) && count($extralabelslines)>0) { - print ''; - $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); - print ''; - } - } - // Ligne en mode update - else - { - // Ligne carac - print ""; - print ''; + $line = new ContratLigne($db); + $line->fetch_optionals($objp->rowid,$extralabelslines); + print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); + print ''; + } + } + // Ligne en mode update + else + { + // Ligne carac + print ""; + print ''; - print ''; - print ''; - print ''; - if ($conf->global->PRODUCT_USE_UNITS) - { - print ''; - } - print ''; + print ''; + print ''; + print ''; + print ''; + if ($conf->global->PRODUCT_USE_UNITS) + { + print ''; + } + print ''; if (! empty($usemargins)) { - print ''; } - print ''; + print ''; - $colspan=6; - if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; - if($conf->global->PRODUCT_USE_UNITS) $colspan++; + $colspan=6; + if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; + if($conf->global->PRODUCT_USE_UNITS) $colspan++; - // Ligne dates prevues - print ""; - print ''; + // Ligne dates prevues + print ""; + print ''; - if (is_array($extralabelslines) && count($extralabelslines)>0) { - print ''; - $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); - print ''; - } + if (is_array($extralabelslines) && count($extralabelslines)>0) { + print ''; + $line = new ContratLigne($db); + $line->fetch_optionals($objp->rowid,$extralabelslines); + print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$colspan)); + print ''; + } - print ''; - } + print ''; + } - $db->free($result); - } - else + $db->free($result); + } + else { - dol_print_error($db); - } + dol_print_error($db); + } - if ($object->statut > 0) - { - print ''; - print ''; - print "\n"; - } + if ($object->statut > 0) + { + print ''; + print ''; + print "\n"; + } - print "
'.$langs->trans("ServiceNb",$cursorline).''.$langs->trans("VAT").''.$langs->trans("PriceUHT").''.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").'
'.$langs->trans("ServiceNb",$cursorline).''.$langs->trans("VAT").''.$langs->trans("PriceUHT").''.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").''.$langs->trans("BuyingPrice").' 
 
'; - $productstatic->id=$objp->fk_product; - $productstatic->type=$objp->ptype; - $productstatic->ref=$objp->pref; + if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) + { + print '
'; + $productstatic->id=$objp->fk_product; + $productstatic->type=$objp->ptype; + $productstatic->ref=$objp->pref; $productstatic->entity=$objp->pentity; $productstatic->label=$objp->plabel; $text = $productstatic->getNomUrl(1,'',20); - if ($objp->plabel) - { - $text .= ' - '; - //$productstatic->ref=$objp->label; - //$text .= $productstatic->getNomUrl(0,'',16); - $text .= $objp->plabel; - } - $description = $objp->description; + if ($objp->plabel) + { + $text .= ' - '; + //$productstatic->ref=$objp->label; + //$text .= $productstatic->getNomUrl(0,'',16); + $text .= $objp->plabel; + } + $description = $objp->description; - // Add description in form + // Add description in form if (! empty($conf->global->PRODUIT_DESC_IN_FORM)) { $text .= (! empty($objp->description) && $objp->description!=$objp->plabel)?'
'.dol_htmlentitiesbr($objp->description):''; $description = ''; // Already added into main visible desc } - echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):'')); + echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):'')); - print '
'.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."'; - print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits); - print ''.($objp->subprice != '' ? price($objp->subprice) : '')."'.price($objp->multicurrency_subprice).''.$objp->qty.''.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).''.$objp->remise_percent."% '.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."'; + print vatrate($objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), '%', $objp->info_bits); + print ''.($objp->subprice != '' ? price($objp->subprice) : '')."'.price($objp->multicurrency_subprice).''.$objp->qty.''.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).''.$objp->remise_percent."% '.price($objp->pa_ht).''; - if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) - { - print ''; - print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); - print ''; - } - if ($user->rights->contrat->creer && ($object->statut >= 0)) - { - print ''; - print img_edit(); - print ''; - } - if ( $user->rights->contrat->creer && ($object->statut >= 0)) - { - print ''; - print img_delete(); - print ''; - } - print ''; + if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) + { + print ''; + print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); + print ''; + } + if ($user->rights->contrat->creer && ($object->statut >= 0)) + { + print ''; + print img_edit(); + print ''; + } + if ( $user->rights->contrat->creer && ($object->statut >= 0)) + { + print ''; + print img_delete(); + print ''; + } + print '
'; + print '
'; - // Date planned - print $langs->trans("DateStartPlanned").': '; - if ($objp->date_debut) - { - print dol_print_date($db->jdate($objp->date_debut), 'day'); - // Warning si date prevu passee et pas en service - if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { - $warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print " ".img_warning($textlate); - } - } - else print $langs->trans("Unknown"); - print '  -  '; - print $langs->trans("DateEndPlanned").': '; - if ($objp->date_fin) - { - print dol_print_date($db->jdate($objp->date_fin), 'day'); - if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { - $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; - $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); - print " ".img_warning($textlate); - } - } - else print $langs->trans("Unknown"); + // Date planned + print $langs->trans("DateStartPlanned").': '; + if ($objp->date_debut) + { + print dol_print_date($db->jdate($objp->date_debut), 'day'); + // Warning si date prevu passee et pas en service + if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { + $warning_delay=$conf->contrat->services->inactifs->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print " ".img_warning($textlate); + } + } + else print $langs->trans("Unknown"); + print '  -  '; + print $langs->trans("DateEndPlanned").': '; + if ($objp->date_fin) + { + print dol_print_date($db->jdate($objp->date_fin), 'day'); + if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { + $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; + $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); + print " ".img_warning($textlate); + } + } + else print $langs->trans("Unknown"); - print '
'; - if ($objp->fk_product) - { - $productstatic->id=$objp->fk_product; - $productstatic->type=$objp->ptype; - $productstatic->ref=$objp->pref; + // Display lines extrafields + if (is_array($extralabelslines) && count($extralabelslines)>0) { + print '
'; + if ($objp->fk_product) + { + $productstatic->id=$objp->fk_product; + $productstatic->type=$objp->ptype; + $productstatic->ref=$objp->pref; $productstatic->entity=$objp->pentity; - print $productstatic->getNomUrl(1,'',20); - print $objp->label?' - '.dol_trunc($objp->label,16):''; - print '
'; - } - else - { - print $objp->label?$objp->label.'
':''; - } + print $productstatic->getNomUrl(1,'',20); + print $objp->label?' - '.dol_trunc($objp->label,16):''; + print '
'; + } + else + { + print $objp->label?$objp->label.'
':''; + } - // editeur wysiwyg - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $nbrows=ROWS_2; - if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; - $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0); - $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%'); - $doleditor->Create(); + // editeur wysiwyg + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $nbrows=ROWS_2; + if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT; + $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0); + $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,'90%'); + $doleditor->Create(); - print '
'; - print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1); - print ''; - print $form->selectUnits($objp->fk_unit, "unit"); - print '%'; + print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code?(' ('.$objp->vat_src_code.')'):''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1); + print ''; + print $form->selectUnits($objp->fk_unit, "unit"); + print '%'; - if ($objp->fk_product) print ''; + print ''; + if ($objp->fk_product) print ''; print ''; - print ''; - print '
'; - print '
'; + print ''; + print '
'; + print '
'; - print $langs->trans("DateStartPlanned").' '; - $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update"); - print '   '.$langs->trans("DateEndPlanned").' '; - $form->select_date($db->jdate($objp->date_fin),"date_end_update",$usehm,$usehm,($db->jdate($objp->date_fin)>0?0:1),"update"); - print '
'; + print $langs->trans("DateStartPlanned").' '; + $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update"); + print '   '.$langs->trans("DateEndPlanned").' '; + $form->select_date($db->jdate($objp->date_fin),"date_end_update",$usehm,$usehm,($db->jdate($objp->date_fin)>0?0:1),"update"); + print '


"; + print ""; - print "
\n"; + print "\n"; - /* + /* * Confirmation to delete service line of contract */ - if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1); - if ($ret == 'html') print '
'; - } + if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1); + if ($ret == 'html') print '
'; + } - /* + /* * Confirmation to move service toward another contract */ - if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) - { - $arraycontractid=array(); - foreach($arrayothercontracts as $contractcursor) - { - $arraycontractid[$contractcursor->id]=$contractcursor->ref; - } - //var_dump($arraycontractid); - // Cree un tableau formulaire - $formquestion=array( + if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid')) + { + $arraycontractid=array(); + foreach($arrayothercontracts as $contractcursor) + { + $arraycontractid[$contractcursor->id]=$contractcursor->ref; + } + //var_dump($arraycontractid); + // Cree un tableau formulaire + $formquestion=array( 'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"), - array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid)); + array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid)); - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion); - print '
'; - } + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion); + print '
'; + } - /* + /* * Confirmation de la validation activation */ - if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - $comment = GETPOST('comment','alpha'); - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1); - print '
'; - } + if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + $comment = GETPOST('comment','alpha'); + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1); + print '
'; + } - /* + /* * Confirmation de la validation fermeture */ - if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - $comment = GETPOST('comment','alpha'); + if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + $comment = GETPOST('comment','alpha'); - if (empty($dateactend)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); - } - else - { - $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1); - } - print '
'; - } + if (empty($dateactend)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); + } + else + { + $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne','int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService",dol_print_date($dateactend,"%A %d %B %Y")), "confirm_closeline", '', 0, 1); + } + print '
'; + } - // Area with status and activation info of line - if ($object->statut > 0) - { - print ''; + // Area with status and activation info of line + if ($object->statut > 0) + { + print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; - print "\n"; + } + } + print ''; + print "\n"; - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; - print ''; - print '
'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).''; - if ($user->societe_id == 0) - { - if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') - { - $tmpaction='activateline'; - $tmpactionpicto='play'; - $tmpactiontext=$langs->trans("Activate"); - if ($objp->statut == 4) - { - $tmpaction='unactivateline'; - $tmpactionpicto='playstop'; - $tmpactiontext=$langs->trans("Unactivate"); - } + print '
'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).''; + if ($user->societe_id == 0) + { + if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') + { + $tmpaction='activateline'; + $tmpactionpicto='play'; + $tmpactiontext=$langs->trans("Activate"); + if ($objp->statut == 4) + { + $tmpaction='unactivateline'; + $tmpactionpicto='playstop'; + $tmpactiontext=$langs->trans("Unactivate"); + } if (($tmpaction=='activateline' && $user->rights->contrat->activer) || ($tmpaction=='unactivateline' && $user->rights->contrat->desactiver)) { print ''; print img_picto($tmpactiontext, $tmpactionpicto); print ''; } - } - } - print '
'; - // Si pas encore active - if (! $objp->date_debut_reelle) { - print $langs->trans("DateStartReal").': '; - if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day'); - else print $langs->trans("ContractStatusNotRunning"); - } - // Si active et en cours - if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) { - print $langs->trans("DateStartReal").': '; - print dol_print_date($objp->date_debut_reelle, 'day'); - } - // Si desactive - if ($objp->date_debut_reelle && $objp->date_fin_reelle) { - print $langs->trans("DateStartReal").': '; - print dol_print_date($objp->date_debut_reelle, 'day'); - print '  -  '; - print $langs->trans("DateEndReal").': '; - print dol_print_date($objp->date_fin_reelle, 'day'); - } - if (! empty($objp->comment)) print "
".$objp->comment; - print '
'; + // Si pas encore active + if (! $objp->date_debut_reelle) { + print $langs->trans("DateStartReal").': '; + if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle, 'day'); + else print $langs->trans("ContractStatusNotRunning"); + } + // Si active et en cours + if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) { + print $langs->trans("DateStartReal").': '; + print dol_print_date($objp->date_debut_reelle, 'day'); + } + // Si desactive + if ($objp->date_debut_reelle && $objp->date_fin_reelle) { + print $langs->trans("DateStartReal").': '; + print dol_print_date($objp->date_debut_reelle, 'day'); + print '  -  '; + print $langs->trans("DateEndReal").': '; + print dol_print_date($objp->date_fin_reelle, 'day'); + } + if (! empty($objp->comment)) print "
".$objp->comment; + print '
  
'; - } + print ''; + print ''; + } - // Form to activate line - if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - print '
'; - print ''; + // Form to activate line + if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + print ''; + print ''; - print ''; + print '
'; - // Definie date debut et fin par defaut - $dateactstart = $objp->date_debut; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (! $dateactstart) $dateactstart = time(); + // Definie date debut et fin par defaut + $dateactstart = $objp->date_debut; + if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + elseif (! $dateactstart) $dateactstart = time(); - $dateactend = $objp->date_fin; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (! $dateactend) - { - if ($objp->fk_product > 0) - { - $product=new Product($db); - $product->fetch($objp->fk_product); - $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); - } - } + $dateactend = $objp->date_fin; + if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + elseif (! $dateactend) + { + if ($objp->fk_product > 0) + { + $product=new Product($db); + $product->fetch($objp->fk_product); + $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); + } + } - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
'.$langs->trans("DateServiceActivate").''; - print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active",1,0,1); - print ''.$langs->trans("DateEndPlanned").''; - print $form->select_date($dateactend,"end",$usehm,$usehm,'',"active",1,0,1); - print ''; - print '
'.$langs->trans("DateServiceActivate").''; + print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active",1,0,1); + print ''.$langs->trans("DateEndPlanned").''; + print $form->select_date($dateactend,"end",$usehm,$usehm,'',"active",1,0,1); + print ''; + print '
'.$langs->trans("Comment").''; - print '   '; - print ''; - print '
'.$langs->trans("Comment").''; + print '   '; + print ''; + print '
'; + print ''; - print '
'; - } + print ''; + } - if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) - { - /** - * Disable a contract line - */ - print ''."\n"; - print '
'; + if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne')) + { + /** + * Disable a contract line + */ + print ''."\n"; + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + print '
'; - // Definie date debut et fin par defaut - $dateactstart = $objp->date_debut_reelle; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (! $dateactstart) $dateactstart = time(); + // Definie date debut et fin par defaut + $dateactstart = $objp->date_debut_reelle; + if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + elseif (! $dateactstart) $dateactstart = time(); - $dateactend = $objp->date_fin_reelle; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (! $dateactend) - { - if ($objp->fk_product > 0) - { - $product=new Product($db); - $product->fetch($objp->fk_product); - $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); - } - } - $now=dol_now(); - if ($dateactend > $now) $dateactend=$now; + $dateactend = $objp->date_fin_reelle; + if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + elseif (! $dateactend) + { + if ($objp->fk_product > 0) + { + $product=new Product($db); + $product->fetch($objp->fk_product); + $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); + } + } + $now=dol_now(); + if ($dateactend > $now) $dateactend=$now; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
'; - if ($objp->statut >= 4) - { - if ($objp->statut == 4) - { - print $langs->trans("DateEndReal").' '; - print $form->select_date($dateactend,"end",$usehm,$usehm,($objp->date_fin_reelle>0?0:1),"closeline",1,1,1); - } - } - print ''; - print '
'; + if ($objp->statut >= 4) + { + if ($objp->statut == 4) + { + print $langs->trans("DateEndReal").' '; + print $form->select_date($dateactend,"end",$usehm,$usehm,($objp->date_fin_reelle>0?0:1),"closeline",1,1,1); + } + } + print ''; + print '
'.$langs->trans("Comment").''; - print '   '; - print ''; - print '
'.$langs->trans("Comment").''; + print '   '; + print ''; + print '
'; + print ''; - print '
'; - } + print ''; + } - $cursorline++; - } + $cursorline++; + } // Form to add new line - if ($user->rights->contrat->creer && ($object->statut == 0)) - { - $dateSelector=1; + if ($user->rights->contrat->creer && ($object->statut == 0)) + { + $dateSelector=1; print "\n"; print '
@@ -1994,15 +2000,15 @@ else '; - print '
'; + print '
'; print ''; // Array with (n*2)+1 lines - // Trick to not show product entries - $savproductenabled=$conf->product->enabled; - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $conf->product->enabled = 0; + // Trick to not show product entries + $savproductenabled=$conf->product->enabled; + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $conf->product->enabled = 0; - // Form to add new line - if ($action != 'editline') + // Form to add new line + if ($action != 'editline') { $var = true; @@ -2015,129 +2021,129 @@ else $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } - // Restore correct setup - $conf->product->enabled = $savproductenabled; + // Restore correct setup + $conf->product->enabled = $savproductenabled; - print '
'; - print '
'; - print ''; - } + print ''; + print '
'; + print ''; + } dol_fiche_end(); - /* + /* * Buttons */ - if ($user->societe_id == 0) - { - print '
'; + if ($user->societe_id == 0) + { + print '
'; - $parameters=array(); - $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { - // Send - if ($object->statut == 1) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { - print ''; - } else - print ''; - } + if (empty($reshook)) + { + // Send + if ($object->statut == 1) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { + print ''; + } else + print ''; + } - if ($object->statut == 0 && $nbofservices) - { - if ($user->rights->contrat->creer) print ''; - else print ''; - } - if ($object->statut == 1) - { - if ($user->rights->contrat->creer) print ''; - else print ''; - } + if ($object->statut == 0 && $nbofservices) + { + if ($user->rights->contrat->creer) print ''; + else print ''; + } + if ($object->statut == 1) + { + if ($user->rights->contrat->creer) print ''; + else print ''; + } - if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { - $langs->load("bills"); - if ($user->rights->facture->creer) print ''; - else print ''; - } + if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) + { + $langs->load("bills"); + if ($user->rights->facture->creer) print ''; + else print ''; + } - if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { - $langs->load("orders"); - if ($user->rights->commande->creer) print ''; - else print ''; - } + if (! empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) + { + $langs->load("orders"); + if ($user->rights->commande->creer) print ''; + else print ''; + } - // Clone - if ($user->rights->contrat->creer) { - print ''; - } + // Clone + if ($user->rights->contrat->creer) { + print ''; + } - if ($object->nbofservicesclosed > 0) - { - print ''; - } - if ($object->nbofservicesclosed < $nbofservices) - { - //if (! $numactive) - //{ - print ''; - //} - //else - //{ - // print ''; - //} - } + if ($object->nbofservicesclosed > 0) + { + print ''; + } + if ($object->nbofservicesclosed < $nbofservices) + { + //if (! $numactive) + //{ + print ''; + //} + //else + //{ + // print ''; + //} + } - // On peut supprimer entite si - // - Droit de creer + mode brouillon (erreur creation) - // - Droit de supprimer - if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer) - { - print ''; - } - else - { - print ''; - } - } + // On peut supprimer entite si + // - Droit de creer + mode brouillon (erreur creation) + // - Droit de supprimer + if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer) + { + print ''; + } + else + { + print ''; + } + } - print "
"; - } + print "
"; + } - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } - if ($action != 'presend') - { - print '
'; + if ($action != 'presend') + { + print '
'; - /* + /* * Documents generes */ - $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->contrat->creer; - $delallowed = $user->rights->contrat->supprimer; + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->contrat->lire; + $delallowed = $user->rights->contrat->creer; - $var = true; + $var = true; - print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; + print '
'; // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; @@ -2145,8 +2151,8 @@ else $somethingshown = $formactions->showactions($object, 'contract', $socid, 1); - print '
'; - } + print '
'; + } // Presend form $modelmail='contract'; @@ -2155,7 +2161,7 @@ else $trackid = 'con'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - } + } } diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php new file mode 100644 index 00000000000..0bc02458869 --- /dev/null +++ b/htdocs/contrat/class/api_contracts.class.php @@ -0,0 +1,587 @@ + + * Copyright (C) 2016 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + use Luracast\Restler\RestException; + + require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + +/** + * API class for contracts + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Contracts extends DolibarrApi +{ + + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid', + 'date_contrat', + 'commercial_signature_id', + 'commercial_suivi_id' + ); + + /** + * @var Contrat $contract {@type Contrat} + */ + public $contract; + + /** + * Constructor + */ + function __construct() + { + global $db, $conf; + $this->db = $db; + $this->contract = new Contrat($this->db); + } + + /** + * Get properties of a contrat object + * + * Return an array with contrat informations + * + * @param int $id ID of contract + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { + if(! DolibarrApiAccess::$user->rights->contrat->lire) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $this->contract->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->contract); + } + + + + /** + * List contracts + * + * Get a list of contracts + * + * @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 contracts of. {@example '1' or '1,2,3'} {@pattern /^[0-9,]*$/i} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of contract objects + * + * @throws RestException + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $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 && !$socids) $search_sale = DolibarrApiAccess::$user->id; + + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql.= " FROM ".MAIN_DB_PREFIX."contrat as t"; + + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + + $sql.= ' WHERE t.entity IN ('.getEntity('contrat').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $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 + // 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); + } + + dol_syslog("API Rest request"); + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + $i=0; + while ($i < $min) + { + $obj = $db->fetch_object($result); + $contrat_static = new Contrat($db); + if($contrat_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($contrat_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve contrat list : '.$db->lasterror()); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No contract found'); + } + return $obj_ret; + } + + /** + * Create contract object + * + * @param array $request_data Request data + * @return int ID of contrat + */ + function post($request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach($request_data as $field => $value) { + $this->contract->$field = $value; + } + /*if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->contract->lines = $lines; + }*/ + if ($this->contract->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors)); + } + + return $this->contract->id; + } + + /** + * Get lines of a contract + * + * @param int $id Id of contract + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->contrat->lire) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->contract->getLinesArray(); + $result = array(); + foreach ($this->contract->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + + /** + * Add a line to given contract + * + * @param int $id Id of contrat to update + * @param array $request_data Contractline data + * + * @url POST {id}/lines + * + * @return int + */ + function postLine($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->contract->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->date_start, // date_start = date planned start, date ouverture = date_start_real + $request_data->date_end, // date_end = date planned end, date_cloture = date_end_real + $request_data->HT, + $request_data->subprice_excl_tax, + $request_data->info_bits, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->array_options, + $request_data->fk_unit, + $request_data->rang + ); + + if ($updateRes > 0) { + return $updateRes; + + } + return false; + } + + /** + * Update a line to given contract + * + * @param int $id Id of contrat to update + * @param int $lineid Id of line to update + * @param array $request_data Contractline data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + + $updateRes = $this->contract->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->date_ouveture_prevue, + $request_data->date_fin_validite, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->date_ouverture, + $request_data->date_cloture, + 'HT', + $request_data->info_bits, + $request_data->fk_fourn_price, + $request_data->pa_ht, + $request_data->array_options, + $request_data->fk_unit + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + + return false; + } + + /** + * Delete a line to given contract + * + * + * @param int $id Id of contract to update + * @param int $lineid Id of line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return int + * @throws 401 + * @throws 404 + */ + function deleteLine($id, $lineid) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $request_data = (object) $request_data; + $updateRes = $this->contract->deleteline($lineid, DolibarrApiAccess::$user); + if ($updateRes > 0) { + return $this->get($id); + } + return false; + } + + /** + * Update contract general fields (won't touch lines of contract) + * + * @param int $id Id of contrat to update + * @param array $request_data Datas + * + * @return int + */ + function put($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contrat not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + foreach($request_data as $field => $value) { + if ($field == 'id') continue; + $this->contract->$field = $value; + } + + if($this->contract->update(DolibarrApiAccess::$user, 0)) + return $this->get($id); + + return false; + } + + /** + * Delete contract + * + * @param int $id Contract ID + * + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->contrat->supprimer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if( ! $this->contract->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete contract : '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract deleted' + ) + ); + + } + + /** + * Validate an contract + * + * @param int $id Contract ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "notrigger": 0 + * } + */ + function validate($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->contract->validate(DolibarrApiAccess::$user, '', $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Contract: '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract validated (Ref='.$this->contract->ref.')' + ) + ); + } + + /** + * Close all services of a contract + * + * @param int $id Contract ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/close + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "notrigger": 0 + * } + */ + function close($id, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->contrat->creer) { + throw new RestException(401); + } + $result = $this->contract->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Contract not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('contrat',$this->contract->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->contract->closeAll(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(500, 'Error nothing done. May be object is already close'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Contract: '.$this->contract->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Contract closed (Ref='.$this->contract->ref.'). All services were closed.' + ) + ); + } + + + + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + function _cleanObjectDatas($object) { + + $object = parent::_cleanObjectDatas($object); + + unset($object->address); + + unset($object->date_ouverture_prevue); + unset($object->date_ouverture); + unset($object->date_fin_validite); + unset($object->date_cloture); + unset($object->date_debut_prevue); + unset($object->date_debut_reel); + unset($object->date_fin_prevue); + unset($object->date_fin_reel); + unset($object->civility_id); + + return $object; + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate($data) + { + $contrat = array(); + foreach (Contracts::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $contrat[$field] = $data[$field]; + + } + return $contrat; + } +} diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 071ae75e5b7..47a40c1b0a3 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -44,7 +44,7 @@ class Contrat extends CommonObject public $table_element='contrat'; public $table_element_line='contratdet'; public $fk_element='fk_contrat'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='contract'; /** @@ -298,12 +298,13 @@ class Contrat extends CommonObject } /** - * Close all lines of a contract + * Close all lines of a contract * - * @param User $user Object User making action - * @return int <0 if KO, >0 if OK + * @param User $user Object User making action + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <0 if KO, >0 if OK */ - function closeAll($user) + function closeAll(User $user, $notrigger=0) { $this->db->begin(); @@ -330,7 +331,7 @@ class Contrat extends CommonObject if ($this->statut == 0) { - $result=$this->validate($user); + $result=$this->validate($user, '', $notrigger); if ($result < 0) $ok=false; } @@ -355,7 +356,7 @@ class Contrat extends CommonObject * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ - function validate($user, $force_number='', $notrigger=0) + function validate(User $user, $force_number='', $notrigger=0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; global $langs, $conf; @@ -691,8 +692,8 @@ class Contrat extends CommonObject $sql.= " d.fk_user_ouverture,"; $sql.= " d.fk_user_cloture,"; $sql.= " d.fk_unit"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d, ".MAIN_DB_PREFIX."product as p"; - $sql.= " WHERE d.fk_contrat = ".$this->id ." AND d.fk_product = p.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid"; + $sql.= " WHERE d.fk_contrat = ".$this->id; $sql.= " ORDER by d.rowid ASC"; dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); @@ -728,7 +729,7 @@ class Contrat extends CommonObject $line->total_localtax1 = $objp->total_localtax1; $line->total_localtax2 = $objp->total_localtax2; $line->total_ttc = $objp->total_ttc; - $line->fk_product = $objp->fk_product; + $line->fk_product = (($objp->fk_product > 0)?$objp->fk_product:0); $line->info_bits = $objp->info_bits; $line->fk_fournprice = $objp->fk_fournprice; @@ -740,26 +741,38 @@ class Contrat extends CommonObject $line->fk_user_cloture = $objp->fk_user_cloture; $line->fk_unit = $objp->fk_unit; - $line->ref = $objp->product_ref; // deprecated - $line->label = $objp->product_label; // deprecated - $line->libelle = $objp->product_label; // deprecated + $line->ref = $objp->product_ref; // deprecated + if (empty($objp->fk_product)) + { + $line->label = ''; // deprecated + $line->libelle = $objp->description; // deprecated + } + else + { + $line->label = $objp->product_label; // deprecated + $line->libelle = $objp->product_label; // deprecated + } $line->product_ref = $objp->product_ref; // Ref product $line->product_desc = $objp->product_desc; // Description product $line->product_label = $objp->product_label; // Label product $line->description = $objp->description; + $line->date_start = $this->db->jdate($objp->date_ouverture_prevue); + $line->date_start_real = $this->db->jdate($objp->date_ouverture); + $line->date_end = $this->db->jdate($objp->date_fin_validite); + $line->date_end_real = $this->db->jdate($objp->date_cloture); + // For backward compatibility $line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue); $line->date_ouverture = $this->db->jdate($objp->date_ouverture); $line->date_fin_validite = $this->db->jdate($objp->date_fin_validite); $line->date_cloture = $this->db->jdate($objp->date_cloture); - // For backward compatibility $line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue); $line->date_debut_reel = $this->db->jdate($objp->date_ouverture); $line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite); $line->date_fin_reel = $this->db->jdate($objp->date_cloture); - // Retreive all extrafield for propal + // Retreive all extrafield for contract // fetch optionals attributes and labels $line->fetch_optionals($line->id,$extralabelsline); @@ -789,108 +802,6 @@ class Contrat extends CommonObject return -3; } - // Selectionne les lignes contrat liees a aucun produit - $sql = "SELECT d.rowid, d.fk_contrat, d.statut, d.qty, d.description, d.price_ht, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.rowid, d.remise_percent, d.subprice,"; - $sql.= " d.total_ht,"; - $sql.= " d.total_tva,"; - $sql.= " d.total_localtax1,"; - $sql.= " d.total_localtax2,"; - $sql.= " d.total_ttc,"; - $sql.= " d.info_bits, d.fk_product,"; - $sql.= " d.date_ouverture_prevue, d.date_ouverture,"; - $sql.= " d.date_fin_validite, d.date_cloture,"; - $sql.= " d.fk_user_author,"; - $sql.= " d.fk_user_ouverture,"; - $sql.= " d.fk_user_cloture,"; - $sql.= " d.fk_unit"; - $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as d"; - $sql.= " WHERE d.fk_contrat = ".$this->id; - $sql.= " AND (d.fk_product IS NULL OR d.fk_product = 0)"; // fk_product = 0 gardee pour compatibilitee - - $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 ContratLigne($this->db); - $line->id = $objp->rowid; - $line->fk_contrat = $objp->fk_contrat; - $line->libelle = $objp->description; - $line->desc = $objp->description; - $line->qty = $objp->qty; - $line->statut = $objp->statut; - $line->ref = ''; - $line->tva_tx = $objp->tva_tx; - $line->localtax1_tx = $objp->localtax1_tx; - $line->localtax2_tx = $objp->localtax2_tx; - $line->localtax1_type = $objp->localtax1_type; - $line->localtax2_type = $objp->localtax2_type; - $line->subprice = $objp->subprice; - $line->remise_percent = $objp->remise_percent; - $line->price_ht = $objp->price_ht; - $line->price = (isset($objp->price)?$objp->price:null); // For backward compatibility - $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_product = 0; - $line->info_bits = $objp->info_bits; - - $line->fk_user_author = $objp->fk_user_author; - $line->fk_user_ouverture= $objp->fk_user_ouverture; - $line->fk_user_cloture = $objp->fk_user_cloture; - - $line->description = $objp->description; - - $line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue); - $line->date_ouverture = $this->db->jdate($objp->date_ouverture); - $line->date_fin_validite = $this->db->jdate($objp->date_fin_validite); - $line->date_cloture = $this->db->jdate($objp->date_cloture); - // For backward compatibility - $line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue); - $line->date_debut_reel = $this->db->jdate($objp->date_ouverture); - $line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite); - $line->date_fin_reel = $this->db->jdate($objp->date_cloture); - $line->fk_unit = $objp->fk_unit; - - if ($line->statut == 0) $this->nbofserviceswait++; - if ($line->statut == 4 && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++; - if ($line->statut == 4 && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++; - if ($line->statut == 5) $this->nbofservicesclosed++; - - - // Retreive all extrafield for propal - // fetch optionals attributes and labels - - $line->fetch_optionals($line->id,$extralabelsline); - - - $this->lines[$pos] = $line; - $this->lines_id_index_mapper[$line->id] = $pos; - - $total_ttc+=$objp->total_ttc; - $total_vat+=$objp->total_tva; - $total_ht+=$objp->total_ht; - - $i++; - $pos++; - } - - $this->db->free($result); - } - else - { - dol_syslog(get_class($this)."::Fetch Erreur lecture des lignes de contrat non liees aux produits"); - $this->error=$this->db->error(); - return -2; - } - $this->nbofservices=count($this->lines); $this->total_ttc = price2num($total_ttc); // TODO For the moment value is false as value is not stored in database for line linked to products $this->total_vat = price2num($total_vat); // TODO For the moment value is false as value is not stored in database for line linked to products @@ -1008,7 +919,12 @@ class Contrat extends CommonObject if (! $error) { - // Add object linked + 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) @@ -1020,7 +936,7 @@ class Contrat extends CommonObject $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -1031,7 +947,7 @@ class Contrat extends CommonObject $ret = $this->add_object_linked($origin, $origin_id); if (! $ret) { - dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } } @@ -1400,13 +1316,14 @@ class Contrat extends CommonObject * @param int $pa_ht Buying price HT * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one - * @return int <0 si erreur, >0 si ok + * @param string $rang Position + * @return int <0 if KO, >0 if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0) { global $user, $langs, $conf, $mysoc; - dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits"); + dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); if ($this->statut >= 0) { @@ -1616,7 +1533,7 @@ class Contrat extends CommonObject { global $user, $conf, $langs, $mysoc; - // Nettoyage parametres + // Clean parameters $qty=trim($qty); $desc=trim($desc); $desc=trim($desc); @@ -1625,6 +1542,7 @@ class Contrat extends CommonObject $localtax1tx = price2num($localtax1tx); $localtax2tx = price2num($localtax2tx); $pa_ht=price2num($pa_ht); + if (empty($fk_fournprice)) $fk_fournprice=0; $subprice = $price; $remise = 0; @@ -1701,7 +1619,7 @@ class Contrat extends CommonObject $sql.= ", total_localtax1='".price2num($total_localtax1)."'"; $sql.= ", total_localtax2='".price2num($total_localtax2)."'"; $sql.= ", total_ttc='". price2num($total_ttc)."'"; - $sql.= ", fk_product_fournisseur_price='".$fk_fournprice."'"; + $sql.= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null"); $sql.= ", buy_price_ht='".price2num($pa_ht)."'"; if ($date_start > 0) { $sql.= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; } else { $sql.=",date_ouverture_prevue=null"; } @@ -1772,7 +1690,7 @@ class Contrat extends CommonObject * @param User $user User that delete * @return int >0 if OK, <0 if KO */ - function deleteline($idline,$user) + function deleteline($idline, User $user) { global $conf, $langs; @@ -1960,7 +1878,6 @@ class Contrat extends CommonObject if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; //} - $picto = 'contract'; $label = ''; if ($user->rights->contrat->lire) { @@ -1995,9 +1912,11 @@ class Contrat extends CommonObject $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$linkstart.$this->ref.$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; } @@ -2171,10 +2090,10 @@ class Contrat extends CommonObject if ($mode == 'inactives') { $warning_delay = $conf->contrat->services->inactifs->warning_delay; $label = $langs->trans("BoardNotActivatedServices"); - $url = DOL_URL_ROOT.'/contrat/services.php?mainmenu=commercial&leftmenu=contracts&mode=0'; + $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=0'; } else { $warning_delay = $conf->contrat->services->expires->warning_delay; - $url = DOL_URL_ROOT.'/contrat/services.php?mainmenu=commercial&leftmenu=contracts&mode=4&filter=expired'; + $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=4&filter=expired'; $label = $langs->trans("BoardRunningServices"); } @@ -2329,10 +2248,10 @@ class Contrat extends CommonObject $line->total_ht=90; $line->total_ttc=107.64; // 90 * 1.196 $line->total_tva=17.64; - $line->date_ouverture = dol_now() - 200000; - $line->date_ouverture_prevue = dol_now() - 500000; - $line->date_fin_validite = dol_now() + 500000; - $line->date_cloture = dol_now() - 100000; + $line->date_start = dol_now() - 500000; + $line->date_start_real = dol_now() - 200000; + $line->date_end = dol_now() + 500000; + $line->date_end_real = dol_now() - 100000; if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); @@ -2343,6 +2262,17 @@ class Contrat extends CommonObject } } + /** + * Create an array of order lines + * + * @return int >0 if OK, <0 if KO + */ + function getLinesArray() + { + return $this->fetch_lines(); + } + + /** * Create a document onto disk according to template module. * @@ -2535,6 +2465,12 @@ class ContratLigne extends CommonObjectLine var $product_label; var $date_commande; + + var $date_start; // date start planned + var $date_start_real; // date start real + var $date_end; // date end planned + var $date_end_real; // date end real + // For backward compatibility var $date_ouverture_prevue; // date start planned var $date_ouverture; // date start real var $date_fin_validite; // date end planned @@ -2770,10 +2706,17 @@ class ContratLigne extends CommonObjectLine $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line $this->description = $obj->description; $this->date_commande = $this->db->jdate($obj->date_commande); + + $this->date_start = $this->db->jdate($obj->date_ouverture_prevue); + $this->date_start_real = $this->db->jdate($obj->date_ouverture); + $this->date_end = $this->db->jdate($obj->date_fin_validite); + $this->date_end_real = $this->db->jdate($obj->date_cloture); + // For backward compatibility $this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue); $this->date_ouverture = $this->db->jdate($obj->date_ouverture); $this->date_fin_validite = $this->db->jdate($obj->date_fin_validite); $this->date_cloture = $this->db->jdate($obj->date_cloture); + $this->tva_tx = $obj->tva_tx; $this->vat_src_code = $obj->vat_src_code; $this->localtax1_tx = $obj->localtax1_tx; @@ -2861,6 +2804,12 @@ class ContratLigne extends CommonObjectLine if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; if (empty($this->remise_percent)) $this->remise_percent = 0; + // For backward compatibility + if (empty($this->date_start)) $this->date_start=$this->date_ouverture_prevue; + if (empty($this->date_start_real)) $this->date_start=$this->date_ouverture; + if (empty($this->date_end)) $this->date_start=$this->date_fin_validite; + if (empty($this->date_end_real)) $this->date_start=$this->date_cloture; + // Check parameters // Put here code to add control on parameters values @@ -3033,7 +2982,7 @@ class ContratLigne extends CommonObjectLine $sql.= " info_bits,"; $sql.= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht"; if ($this->date_ouverture_prevue > 0) { $sql.= ",date_ouverture_prevue"; } - if ($this->date_fin_validite > 0) { $sql.= ",date_fin_validite"; } + if ($this->date_fin_validite > 0) { $sql.= ",date_fin_validite"; } $sql.= ") VALUES ($this->fk_contrat, '', '" . $this->db->escape($this->description) . "',"; $sql.= ($this->fk_product>0 ? $this->fk_product : "null").","; $sql.= " '".$this->db->escape($this->qty)."',"; @@ -3051,8 +3000,8 @@ class ContratLigne extends CommonObjectLine else $sql.= ' null,'; if ($this->pa_ht > 0) $sql.= ' '.price2num($this->pa_ht); else $sql.= ' null'; - if ($this->date_ouverture_prevue > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture_prevue)."'"; } - if ($this->date_fin_validite > 0) { $sql.= ",'".$this->db->idate($this->date_fin_validite)."'"; } + if ($this->date_ouverture > 0) { $sql.= ",'".$this->db->idate($this->date_ouverture)."'"; } + if ($this->date_cloture > 0) { $sql.= ",'".$this->db->idate($this->date_cloture)."'"; } $sql.= ")"; dol_syslog(get_class($this)."::insert", LOG_DEBUG); diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 2d818f8001d..e0874d41595 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -190,7 +190,7 @@ foreach($listofstatus as $status) print ''; print ''.$staticcontratligne->LibStatut($status,0,($bool?1:0)).''; - print ''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).''; + print ''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).''; print "\n"; } if ($status==4 && ! $bool) $bool=true; @@ -210,7 +210,7 @@ foreach($listofstatus as $status) { print ''; print ''.$staticcontratligne->LibStatut($status,0,($bool?1:0)).''; - print ''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).''; + print ''.($nb[$status.$bool]?$nb[$status.$bool]:0).' '.$staticcontratligne->LibStatut($status,3,($bool?1:0)).''; if ($status==4 && ! $bool) $bool=true; else $bool=false; print "\n"; @@ -468,7 +468,7 @@ if ($resql) print ''; - print ''; + print ''; print "\n"; while ($i < $num) @@ -548,7 +548,7 @@ if ($resql) print '
'.$langs->trans("NotActivatedServices").' '.$num.'
'.$langs->trans("NotActivatedServices").' '.$num.'
'; - print ''; + print ''; print "\n"; while ($i < $num) diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 611eae49e4c..38bfef6ebe2 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -137,7 +137,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } diff --git a/htdocs/contrat/services.php b/htdocs/contrat/services_list.php similarity index 99% rename from htdocs/contrat/services.php rename to htdocs/contrat/services_list.php index 84a7fd17cc2..c25311b84da 100644 --- a/htdocs/contrat/services.php +++ b/htdocs/contrat/services_list.php @@ -19,7 +19,7 @@ */ /** - * \file htdocs/contrat/services.php + * \file htdocs/contrat/services_list.php * \ingroup contrat * \brief Page to list services in contracts */ @@ -134,7 +134,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -272,7 +272,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); //print $sql; -dol_syslog("contrat/services.php", LOG_DEBUG); +dol_syslog("contrat/services_list.php", LOG_DEBUG); $resql=$db->query($sql); if (! $resql) { diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php new file mode 100644 index 00000000000..b2ec79af5a7 --- /dev/null +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -0,0 +1,142 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +/** + * \file htdocs/core/actions_addupdatedelete.inc.php + * \brief Code for common actions cancel / add / update / delete + */ + + +// $action or $cancel must be defined +// $object must be defined +// $permissiontoadd must be defined +// $permissiontodelete must be defined +// $backurlforlist must be defined +// $backtopage may be defined + +if ($cancel) +{ + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + $action=''; +} + +// Action to add record +if ($action == 'add' && ! empty($permissiontoadd)) +{ + foreach ($object->fields as $key => $val) + { + if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; // Ignore special fields + + $value = GETPOST($key,'alpha'); + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value=''; // This is an implicit foreign key field + if (! empty($object->fields[$key]['foreignkey']) && $value == '-1') $value=''; // This is an explicit foreign key field + + $object->$key=$value; + if ($val['notnull'] > 0 && $object->$key == '') + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); + } + } + + if (! $error) + { + $result=$object->createCommon($user); + if ($result > 0) + { + // Creation OK + $urltogo=$backtopage?$backtopage:$backurlforlist; + header("Location: ".$urltogo); + exit; + } + else + { + // Creation KO + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + $action='create'; + } + } + else + { + $action='create'; + } +} + +// Action to update record +if ($action == 'update' && ! empty($permissiontoadd)) +{ + foreach ($object->fields as $key => $val) + { + if (! GETPOSTISSET($key)) continue; // The field was not submited to be edited + if (in_array($key, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'fk_user_modif', 'import_key'))) continue; // Ignore special fields + + $value = GETPOST($key,'alpha'); + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value=''; // This is an implicit foreign key field + if (! empty($object->fields[$key]['foreignkey']) && $value == '-1') $value=''; // This is an explicit foreign key field + + $object->$key=$value; + if ($val['notnull'] > 0 && $object->$key == '') + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv($val['label'])), null, 'errors'); + } + } + + if (! $error) + { + $result=$object->updateCommon($user); + if ($result > 0) + { + $action='view'; + } + else + { + // Creation KO + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + $action='edit'; + } + } + else + { + $action='edit'; + } +} + +// Action to delete +if ($action == 'confirm_delete' && ! empty($permissiontodelete)) +{ + $result=$object->deleteCommon($user); + if ($result > 0) + { + // Delete OK + setEventMessages("RecordDeleted", null, 'mesgs'); + header("Location: ".$backurlforlist); + exit; + } + else + { + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + } +} diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index bd86c5cb80c..dd996f83f57 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -91,11 +91,13 @@ if ($action == 'builddoc' && $permissioncreate) } else { - if (empty($donotredirect)) // This is se when include is done by bulk action "Bill Orders" + if (empty($donotredirect)) // This is use when include is done by bulk action "Bill Orders" { setEventMessages($langs->trans("FileGenerated"), null); - header('Location: '.$_SERVER['REQUEST_URI'].'#builddoc'); + $redirecturl = $_SERVER['REQUEST_URI']; + $redirecturl = preg_replace('/&?action=builddoc/', '', $redirecturl); // Remove action=builddoc parameter to avoid infinite loop + header('Location: '.$redirecturl.'#builddoc'); exit; } } diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index b6e70059da3..6b6d40acd9c 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -160,6 +160,10 @@ if ($action == 'add') } } + // Visibility: -1=not visible by default in list, 1=visible, 0=hidden + $visibility = GETPOST('list', 'alpha'); + if ($type == 'separate') $visibility=3; + $result=$extrafields->addExtraField( GETPOST('attrname', 'alpha'), GETPOST('label', 'alpha'), @@ -173,8 +177,8 @@ if ($action == 'add') $params, (GETPOST('alwayseditable', 'alpha')?1:0), (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), - GETPOST('list', 'alpha'), // Same as visible -1=not visible by default in list, 1=visible, 0=not visible in list - (GETPOST('ishidden', 'alpha')?1:0), + $visibility, + 0, GETPOST('computed_value','alpha'), (GETPOST('entitycurrentorall', 'alpha')?0:''), GETPOST('langfile', 'alpha') @@ -323,6 +327,10 @@ if ($action == 'update') } } + // Visibility: -1=not visible by default in list, 1=visible, 0=hidden + $visibility = GETPOST('list', 'alpha'); + if ($type == 'separate') $visibility=3; + $result=$extrafields->update( GETPOST('attrname', 'alpha'), GETPOST('label', 'alpha'), @@ -335,8 +343,8 @@ if ($action == 'update') $params, (GETPOST('alwayseditable', 'alpha')?1:0), (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), - GETPOST('list', 'alpha'), // Same as visible -1=not visible by default in list, 1=visible, 0=not visible in list - (GETPOST('ishidden', 'alpha')?1:0), + $visibility, + 0, GETPOST('default_value','alpha'), GETPOST('computed_value','alpha'), (GETPOST('entitycurrentorall', 'alpha')?0:''), diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 4aec6179365..e6e9bbea604 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -322,14 +322,14 @@ if (! $error && $massaction == 'confirm_presend') $replyto = $from; $subject = GETPOST('subject','none'); $message = GETPOST('message','none'); - $sendtocc = GETPOST('sentocc'); - $sendtobcc = ''; - if ($objectclass == 'Propale') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO); - if ($objectclass == 'Commande') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO); - if ($objectclass == 'Facture') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO); - if ($objectclass == 'Supplier_Proposal') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO); - if ($objectclass == 'CommandeFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO); - if ($objectclass == 'FactureFournisseur') $sendtocc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO); + + $sendtobcc = GETPOST('sendtoccc'); + if ($objectclass == 'Propale') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); + if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); + if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); + if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); + if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); + if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); // $listofqualifiedid is array with key = object id of qualified objects for the current thirdparty $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0); @@ -567,7 +567,7 @@ if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_se $input_files.=' '.escapeshellarg($f); } - $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file); + $cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file); exec($cmd); if (! empty($conf->global->MAIN_UMASK)) diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index 203bd71e645..2607002dff3 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -89,9 +89,7 @@ else // For no ajax call if (empty($url)) $url=DOL_URL_ROOT.'/ecm/index.php'; // Load traductions files -$langs->load("ecm"); -$langs->load("companies"); -$langs->load("other"); +$langs->loadLangs(array("ecm","companies","other")); // Security check if ($user->societe_id > 0) $socid = $user->societe_id; diff --git a/htdocs/core/ajax/ajaxdirtree.php b/htdocs/core/ajax/ajaxdirtree.php index c376bee9da3..ea4bf830e21 100644 --- a/htdocs/core/ajax/ajaxdirtree.php +++ b/htdocs/core/ajax/ajaxdirtree.php @@ -211,15 +211,26 @@ if (file_exists($fullpathselecteddir)) } // Enable jquery handlers on new generated HTML objects - print ''; + }); + }); + '; echo "\n"; diff --git a/htdocs/core/ajax/selectobject.php b/htdocs/core/ajax/selectobject.php new file mode 100644 index 00000000000..0c52c490512 --- /dev/null +++ b/htdocs/core/ajax/selectobject.php @@ -0,0 +1,86 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/ajax/selectobject.php + * \brief File to return Ajax response on a selection list request + */ + +if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal +if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); +if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); +if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); +if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); + +require '../../main.inc.php'; + +$objectdesc=GETPOST('objectdesc', 'alpha'); +$htmlname=GETPOST('htmlname', 'aZ09'); +$sqlfilter=GETPOST('sqlfilter', 'alpha'); +$outjson=(GETPOST('outjson', 'int') ? GETPOST('outjson', 'int') : 0); +$action=GETPOST('action', 'alpha'); +$id=GETPOST('id', 'int'); + + +/* + * View + */ + +//print ''."\n"; + +dol_syslog(join(',', $_GET)); +//print_r($_GET); + + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; +$form = new Form($db); + +//$langs->load("companies"); + +top_httphead(); + +if (empty($htmlname)) return; + + +$InfoFieldList = explode(":", $objectdesc); +$classname=$InfoFieldList[0]; +$classpath=$InfoFieldList[1]; +if (! empty($classpath)) +{ + dol_include_once($classpath); + if ($classname && class_exists($classname)) + { + $objecttmp = new $classname($db); + } +} +if (! is_object($objecttmp)) +{ + dol_syslog('Error bad param objectdesc', LOG_WARNING); + print 'Error bad param objectdesc'; +} + +// When used from jQuery, the search term is added as GET param "term". +$searchkey=(($id && GETPOST($id, 'alpha'))?GETPOST($id, 'alpha'):(($htmlname && GETPOST($htmlname, 'alpha'))?GETPOST($htmlname, 'alpha'):'')); + +// TODO Add a security test to avoid to get content of all tables + +$arrayresult=$form->selectForFormsList($objecttmp, $htmlname, '', 0, $searchkey, '', '', '', 0, 1); + +$db->close(); + +if ($outjson) print json_encode($arrayresult); diff --git a/htdocs/core/ajax/selectsearchbox.php b/htdocs/core/ajax/selectsearchbox.php index f04e2e95b18..0861ef160b6 100644 --- a/htdocs/core/ajax/selectsearchbox.php +++ b/htdocs/core/ajax/selectsearchbox.php @@ -49,35 +49,35 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; //global $hookmanager; $hookmanager->initHooks(array('searchform')); -$search_boxvalue=GETPOST('q'); +$search_boxvalue=GETPOST('q', 'none'); $arrayresult=array(); // Define $searchform if ((( ! empty($conf->societe->enabled) && (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) || empty($conf->global->SOCIETE_DISABLE_CUSTOMERS))) || ! empty($conf->fournisseur->enabled)) && empty($conf->global->MAIN_SEARCHFORM_SOCIETE_DISABLED) && $user->rights->societe->lire) { - $arrayresult['searchintothirdparty']=array('position'=>10, 'img'=>'object_company', 'label'=>$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'text'=>img_picto('','object_company').' '.$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/societe/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintothirdparty']=array('position'=>10, 'shortcut'=>'T', 'img'=>'object_company', 'label'=>$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'text'=>img_picto('','object_company').' '.$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/societe/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->societe->enabled) && empty($conf->global->MAIN_SEARCHFORM_CONTACT_DISABLED) && $user->rights->societe->lire) { - $arrayresult['searchintocontact']=array('position'=>15, 'img'=>'object_contact', 'label'=>$langs->trans("SearchIntoContacts", $search_boxvalue), 'text'=>img_picto('','object_contact').' '.$langs->trans("SearchIntoContacts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contact/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintocontact']=array('position'=>15, 'shortcut'=>'A', 'img'=>'object_contact', 'label'=>$langs->trans("SearchIntoContacts", $search_boxvalue), 'text'=>img_picto('','object_contact').' '.$langs->trans("SearchIntoContacts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contact/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->adherent->enabled) && empty($conf->global->MAIN_SEARCHFORM_ADHERENT_DISABLED) && $user->rights->adherent->lire) { - $arrayresult['searchintomember']=array('position'=>20, 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoMembers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoMembers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/adherents/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintomember']=array('position'=>20, 'shortcut'=>'M', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoMembers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoMembers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/adherents/list.php?sall='.urlencode($search_boxvalue)); } if (((! empty($conf->product->enabled) && $user->rights->produit->lire) || (! empty($conf->service->enabled) && $user->rights->service->lire)) && empty($conf->global->MAIN_SEARCHFORM_PRODUITSERVICE_DISABLED)) { - $arrayresult['searchintoproduct']=array('position'=>30, 'img'=>'object_product', 'label'=>$langs->trans("SearchIntoProductsOrServices", $search_boxvalue),'text'=>img_picto('','object_product').' '.$langs->trans("SearchIntoProductsOrServices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/product/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoproduct']=array('position'=>30, 'shortcut'=>'P', 'img'=>'object_product', 'label'=>$langs->trans("SearchIntoProductsOrServices", $search_boxvalue),'text'=>img_picto('','object_product').' '.$langs->trans("SearchIntoProductsOrServices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/product/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->projet->enabled) && empty($conf->global->MAIN_SEARCHFORM_PROJECT_DISABLED) && $user->rights->projet->lire) { - $arrayresult['searchintoprojects']=array('position'=>40, 'img'=>'object_projectpub', 'label'=>$langs->trans("SearchIntoProjects", $search_boxvalue), 'text'=>img_picto('','object_projectpub').' '.$langs->trans("SearchIntoProjects", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/list.php?search_all='.urlencode($search_boxvalue)); + $arrayresult['searchintoprojects']=array('position'=>40, 'shortcut'=>'Q', 'img'=>'object_projectpub', 'label'=>$langs->trans("SearchIntoProjects", $search_boxvalue), 'text'=>img_picto('','object_projectpub').' '.$langs->trans("SearchIntoProjects", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->projet->enabled) && empty($conf->global->MAIN_SEARCHFORM_TASK_DISABLED) && $user->rights->projet->lire) { @@ -126,7 +126,7 @@ if (! empty($conf->ficheinter->enabled) && empty($conf->global->MAIN_SEARCHFORM_ // HR if (! empty($conf->user->enabled) && empty($conf->global->MAIN_SEARCHFORM_USER_DISABLED) && $user->rights->user->user->lire) { - $arrayresult['searchintouser']=array('position'=>200, 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintouser']=array('position'=>200, 'shortcut'=>'U', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->expensereport->enabled) && empty($conf->global->MAIN_SEARCHFORM_EXPENSEREPORT_DISABLED) && $user->rights->expensereport->lire) { diff --git a/htdocs/core/boxes/box_ficheinter.php b/htdocs/core/boxes/box_ficheinter.php index f62745437a6..c96fb37afe7 100644 --- a/htdocs/core/boxes/box_ficheinter.php +++ b/htdocs/core/boxes/box_ficheinter.php @@ -1,7 +1,7 @@ - * Copyright (C) 2013 Juanjo Menent - * Copyright (C) 2015 Frederic France +/* Copyright (C) 2013 Florian Henry + * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2015 Frederic France * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -75,7 +75,7 @@ class box_ficheinter extends ModeleBoxes $this->info_box_head = array('text' => $langs->trans("BoxTitleLastFicheInter",$max)); - if ($user->rights->ficheinter->lire) + if (! empty($user->rights->ficheinter->lire)) { $sql = "SELECT f.rowid, f.ref, f.fk_soc, f.fk_statut,"; $sql.= " f.datec,"; diff --git a/htdocs/core/boxes/box_graph_invoices_permonth.php b/htdocs/core/boxes/box_graph_invoices_permonth.php index 639db28637d..677fcc17ad2 100644 --- a/htdocs/core/boxes/box_graph_invoices_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_permonth.php @@ -111,7 +111,7 @@ class box_graph_invoices_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php index ca26f1392a8..d1a6d2d5436 100644 --- a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php @@ -110,7 +110,7 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_orders_permonth.php b/htdocs/core/boxes/box_graph_orders_permonth.php index d192805782e..179501e9bf0 100644 --- a/htdocs/core/boxes/box_graph_orders_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_permonth.php @@ -113,7 +113,7 @@ class box_graph_orders_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php index 18b85b2ae80..4979ea6f993 100644 --- a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php @@ -112,7 +112,7 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/box_graph_propales_permonth.php b/htdocs/core/boxes/box_graph_propales_permonth.php index a0a15cae59a..868ddf60268 100644 --- a/htdocs/core/boxes/box_graph_propales_permonth.php +++ b/htdocs/core/boxes/box_graph_propales_permonth.php @@ -111,7 +111,7 @@ class box_graph_propales_permonth extends ModeleBoxes $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; } - if (empty($shownb) && empty($showtot)) $showtot=1; + if (empty($shownb) && empty($showtot)) { $shownb=1; $showtot=1; } $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index 93b8fa3d9d2..fe919b1fcba 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -269,7 +269,8 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" $out.= img_picto($langs->trans("MoveBox",$this->box_id),'grip_title','class="boxhandle hideonsmartphone cursormove"'); $out.= img_picto($langs->trans("CloseBox",$this->box_id),'close_title','class="boxclose cursorpointer" rel="x:y" id="imgclose'.$this->box_id.'"'); $label=$head['text']; - if (! empty($head['graph'])) $label.=' ('.$langs->trans("Graph").')'; + //if (! empty($head['graph'])) $label.=' ('.$langs->trans("Graph").')'; + if (! empty($head['graph'])) $label.=' '; $out.= ''; $out.= '
'.$langs->trans("ListOfExpiredServices").' '.$num.'
'.$langs->trans("ListOfExpiredServices").' '.$num.'
'; } diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index e382f5c8198..39487cf6fea 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -275,7 +275,8 @@ class CMailFile // comme des injections mail par les serveurs de messagerie. $this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers); - $this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol; + //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol; + $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol; $this->message.= $text_body . $files_encoded; $this->message.= "--" . $this->mixed_boundary . "--" . $this->eol; } @@ -961,8 +962,8 @@ class CMailFile //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol; - $out.= "Content-Type: multipart/mixed; boundary=\"".$this->mixed_boundary."\"".$this->eol2; - $out.= "Content-Transfer-Encoding: 8bit".$this->eol2; + $out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2; + $out.= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received. dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out); return $out; @@ -1014,23 +1015,23 @@ class CMailFile if ($this->atleastoneimage) { - $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; } // Make RFC821 Compliant, replace bare linefeeds - $strContent = preg_replace("/(?global->MAIN_FIX_FOR_BUGGED_MTA)) { - $strContent = preg_replace("/\r\n/si", "\n", $strContent); + $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars } $strContentAltText = ''; if ($this->msgishtml) { $strContentAltText = html_entity_decode(strip_tags($strContent)); - $strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n")); + $strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // Check if html header already in message, if not complete the message $strContent = $this->checkIfHTML($strContent); @@ -1038,31 +1039,35 @@ class CMailFile // Make RFC2045 Compliant, split lines //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content - $strContent = rtrim(wordwrap($strContent)); // TODO Using this method creates unexpected line break on text/plain content. + // TODO Encode main content into base64 and use the chunk_split, or quoted-printable + $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // TODO Using this method creates unexpected line break on text/plain content. if ($this->msgishtml) { if ($this->atleastoneimage) { $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message $out.= "--" . $this->alternative_boundary . $this->eol; - $out.= "Content-Type: multipart/related; boundary=\"".$this->related_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->related_boundary . $this->eol; } if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part { - $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol; + $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out.= $this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.$strContentAltText.$this->eol; $out.= "--" . $this->alternative_boundary . $this->eol; } $out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64 $out.= $this->eol.$strContent.$this->eol; if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part @@ -1073,6 +1078,7 @@ class CMailFile else { $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; + //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out.= $this->eol.$strContent.$this->eol; } diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 937634de5d4..666011b3f4a 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -510,6 +510,13 @@ abstract class CommonDocGenerator 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), ); + + // Units + if ($conf->global->PRODUCT_USE_UNITS) + { + $resarray['line_unit']=$outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short']=$outputlangs->trans($line->getLabelOfUnit('short')); + } // Retrieve extrafields $extrafieldkey=$line->element; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 3631a6509ee..47b27641436 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -101,7 +101,7 @@ abstract class CommonObject // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them. /** - * @var string[] Can be used to pass information when only object is provided to method + * @var array Can be used to pass information when only object is provided to method */ public $context=array(); @@ -340,7 +340,6 @@ abstract class CommonObject // No constructor as it is an abstract class - /** * Check an object id/ref exists * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch @@ -544,6 +543,90 @@ abstract class CommonObject return $out; } + /** + * Return the link of last main doc file for direct public download. + * + * @param string $modulepart Module related to document + * @param int $initsharekey Init the share key if it was not yet defined + * @return string Link or empty string if there is no download link + */ + function getLastMainDocLink($modulepart, $initsharekey=0) + { + global $user, $dolibarr_main_url_root; + + if (empty($this->last_main_doc)) + { + return ''; // No known last doc + } + + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($this->db); + $result = $ecmfile->fetch(0, '', $this->last_main_doc); + if ($result < 0) + { + $this->error = $ecmfile->error; + $this->errors = $ecmfile->errors; + return -1; + } + + if (empty($ecmfile->id)) + { + // Add entry into index + if ($initsharekey) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first + /* + $ecmfile->filepath = $rel_dir; + $ecmfile->filename = $filename; + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content + $ecmfile->fullpath_orig = ''; + $ecmfile->gen_or_uploaded = 'generated'; + $ecmfile->description = ''; // indexed content + $ecmfile->keyword = ''; // keyword content + $ecmfile->share = getRandomPassword(true); + $result = $ecmfile->create($user); + if ($result < 0) + { + $this->error = $ecmfile->error; + $this->errors = $ecmfile->errors; + } + */ + } + else return ''; + } + elseif (empty($ecmfile->share)) + { + // Add entry into index + if ($initsharekey) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + $ecmfile->update($user); + } + else return ''; + } + + // Define $urlwithroot + $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); + $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + + $forcedownload=1; + $rellink='/document.php?modulepart='.$modulepart; + if ($forcedownload) $rellink.='&attachment=1'; + if (! empty($ecmfile->entity)) $rellink.='&entity='.$ecmfile->entity; + //$rellink.='&file='.urlencode($filepath); // No need of name of file for public link, we will use the hash + $fulllink=$urlwithroot.$rellink; + //if (! empty($object->ref)) $fulllink.='&hashn='.$object->ref; // Hash of file path + //elseif (! empty($object->label)) $fulllink.='&hashc='.$object->label; // Hash of file content + if (! empty($ecmfile->share)) $fulllink.='&hashp='.$ecmfile->share; // Hash for public share + + // Here $ecmfile->share is defined + return $fulllink; + } + + /** * Add a link between element $this->element and a contact * @@ -1313,7 +1396,7 @@ abstract class CommonObject } /** - * Load properties id_previous and id_next + * Load properties id_previous and id_next by comparing $fieldid with $this->ref * * @param string $filter Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')" * @param string $fieldid Name of field to use for the select MAX and MIN @@ -1338,19 +1421,19 @@ abstract class CommonObject $sql = "SELECT MAX(te.".$fieldid.")"; $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && empty($user->rights->societe->client->voir))) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; $sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; if (! empty($filter)) { if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility $sql.=$filter; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; - //print $filter.' '.$sql."
"; + //print 'filter = '.$filter.' -> '.$sql."
"; $result = $this->db->query($sql); if (! $result) { @@ -1363,16 +1446,16 @@ abstract class CommonObject $sql = "SELECT MIN(te.".$fieldid.")"; $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc"; $sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists) - if (empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 && !$user->rights->societe->client->voir) $sql.= " AND sc.fk_user = " .$user->id; if (! empty($filter)) { if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND "; // For backward compatibility $sql.=$filter; } - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2 || ($this->element != 'societe' && empty($this->isnolinkedbythird) && !$user->rights->societe->client->voir)) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element, 1).')'; // Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null @@ -3619,8 +3702,7 @@ abstract class CommonObject if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) { $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : '')); - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("Label").'"'; - else $placeholder=' title="'.$langs->trans("Label").'"'; + $placeholder=' placeholder="'.$langs->trans("Label").'"'; $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU'); @@ -3648,11 +3730,12 @@ abstract class CommonObject * Return HTML table table of source object lines * TODO Move this and previous function into output html class file (htmlline.class.php). * If lines are into a template, title must also be into a template - * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. + * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects. * + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only * @return void */ - function printOriginLinesList() + function printOriginLinesList($restrictlist='') { global $langs, $hookmanager, $conf; @@ -3674,8 +3757,6 @@ abstract class CommonObject foreach ($this->lines as $line) { - - if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) { if (empty($line->fk_parent_line)) @@ -3687,7 +3768,7 @@ abstract class CommonObject } else { - $this->printOriginLine($line,$var); + $this->printOriginLine($line, $var, $restrictlist); } $i++; @@ -3700,11 +3781,12 @@ abstract class CommonObject * If lines are into a template, title must also be into a template * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. * - * @param CommonObjectLine $line Line - * @param string $var Var + * @param CommonObjectLine $line Line + * @param string $var Var + * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not) * @return void */ - function printOriginLine($line,$var) + function printOriginLine($line, $var, $restrictlist='') { global $langs, $conf; @@ -3803,9 +3885,13 @@ abstract class CommonObject $this->tpl['price'] = price($line->subprice); $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice); $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : ' '; - if($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $line->getLabelOfUnit('long'); + if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long')); $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : ' '; + // Is the line strike or not + $this->tpl['strike']=0; + if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1; + // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); @@ -4043,13 +4129,14 @@ abstract class CommonObject if (in_array(get_class($this), array('Adherent'))) { - $arrayofrecords = array(); // The write_file of templates of adherent class need this + $arrayofrecords = array(); // The write_file of templates of adherent class need this var $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); } else { $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); } + // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index. if ($resultwritefile > 0) { @@ -4076,9 +4163,24 @@ abstract class CommonObject include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile=new EcmFiles($this->db); $result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename); + + // Set the public "share" key + $setsharekey = false; + if ($this->element == 'propal' && ! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($setsharekey) + { + if (empty($ecmfile->share)) // Because object not found or share not set yet + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + } + } + if ($result > 0) { - $ecmfile->label = md5_file(dol_osencode($destfull)); + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content $ecmfile->fullpath_orig = ''; $ecmfile->gen_or_uploaded = 'generated'; $ecmfile->description = ''; // indexed content @@ -4091,9 +4193,10 @@ abstract class CommonObject } else { + $ecmfile->entity = $conf->entity; $ecmfile->filepath = $rel_dir; $ecmfile->filename = $filename; - $ecmfile->label = md5_file(dol_osencode($destfull)); + $ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content $ecmfile->fullpath_orig = ''; $ecmfile->gen_or_uploaded = 'generated'; $ecmfile->description = ''; // indexed content @@ -4104,6 +4207,21 @@ abstract class CommonObject setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); } } + + /*$this->result['fullname']=$destfull; + $this->result['filepath']=$ecmfile->filepath; + $this->result['filename']=$ecmfile->filename;*/ + + // Update the last_main_doc field into main object + $update_main_doc_field=0; + if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1; + if ($update_main_doc_field && ! empty($this->table_element)) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'"; + $sql.= ' WHERE rowid = '.$this->id; + $resql = $this->db->query($sql); + if (! $resql) dol_print_error($this->db); + } } } else @@ -4207,7 +4325,7 @@ abstract class CommonObject /** * Call trigger based on this instance. * Some context information may also be provided into array property this->context. - * NB: Error from trigger are stacked in interface->errors + * NB: Error from trigger are stacked in interface->errors * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction. * * @param string $trigger_name trigger's name to execute @@ -4360,11 +4478,15 @@ abstract class CommonObject * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) * This function delete record with all extrafields and insert them again from the array $this->array_options. * - * @return int -1=error, O=did nothing, 1=OK + * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY) + * @param User $userused Object user + * @return int -1=error, O=did nothing, 1=OK */ - function insertExtraFields() + function insertExtraFields($trigger='',$userused=null) { - global $conf,$langs; + global $conf,$langs,$user; + + if (empty($userused)) $userused=$user; $error=0; @@ -4381,7 +4503,7 @@ abstract class CommonObject //Eliminate copied source object extra_fields that do not exist in target object $new_array_options=array(); foreach ($this->array_options as $key => $value) { - if (in_array(substr($key,8), array_keys($target_extrafields))) + if (in_array(substr($key,8), array_keys($target_extrafields))) // We remove the 'options_' from $key $new_array_options[$key] = $value; } @@ -4467,6 +4589,7 @@ abstract class CommonObject $sql.=",".$attributeKey; } $sql .= ") VALUES (".$this->id; + foreach($new_array_options as $key => $value) { $attributeKey = substr($key,8); // Remove 'options_' prefix @@ -4490,6 +4613,22 @@ abstract class CommonObject if (! $resql) { $this->error=$this->db->lasterror(); + $error++; + } + else + { + if ($trigger) + { + // Call trigger + $this->context=array('extrafieldaddupdate'=>1); + $result=$this->call_trigger($trigger, $userused); + if ($result < 0) $error++; + // End call trigger + } + } + + if ($error) + { $this->db->rollback(); return -1; } @@ -4592,17 +4731,879 @@ abstract class CommonObject else return 0; } - /** - * Function to show lines of extrafields with output datas - * - * @param Extrafields $extrafields Extrafield Object - * @param string $mode Show output (view) or input (edit) for extrafield - * @param array $params Optional parameters - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * - * @return string - */ - function showOptionals($extrafields, $mode='view', $params=null, $keyprefix='') + + /** + * Return HTML string to put an input field into a page + * Code very similar with showInputField of extra fields + * + * @param array $val Array of properties for field to show + * @param string $key Key of attribute + * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) + * @param string $moreparam To add more parametes on html input tag + * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param mixed $showsize Value for css to define size. May also be a numeric. + * @return string + */ + function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0) + { + global $conf,$langs,$form; + + if (! is_object($form)) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + $form=new Form($this->db); + } + + $objectid = $this->id; + + $label=$val['label']; + $type =$val['type']; + $size =$val['css']; + + // Convert var to be able to share same code than showInputField of extrafields + if (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar + if (is_array($val['arrayofkeyval'])) $type='select'; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; + + //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used + $default=$val['default']; + $computed=$val['computed']; + $unique=$val['unique']; + $required=$val['required']; + $param=$val['param']; + if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) + { + $type='link'; + $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); + } + $langfile=$val['langfile']; + $list=$val['list']; + $hidden=(abs($val['visible'])!=1 ? 1 : 0); + $help=$val['help']; + + if ($computed) + { + if (! preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; + else return ''; + } + + if (empty($showsize)) + { + if ($type == 'date') + { + //$showsize=10; + $showsize = 'minwidth100imp'; + } + elseif ($type == 'datetime') + { + //$showsize=19; + $showsize = 'minwidth200imp'; + } + elseif (in_array($type,array('int','double','price'))) + { + //$showsize=10; + $showsize = 'maxwidth75'; + } + elseif ($type == 'url') + { + $showsize='minwidth400'; + } + elseif ($type == 'boolean') + { + $showsize=''; + } + else + { + if (round($size) < 12) + { + $showsize = 'minwidth100'; + } + else if (round($size) <= 48) + { + $showsize = 'minwidth200'; + } + else + { + //$showsize=48; + $showsize = 'minwidth400'; + } + } + } + + if (in_array($type,array('date','datetime'))) + { + $tmp=explode(',',$size); + $newsize=$tmp[0]; + + $showtime = in_array($type,array('datetime')) ? 1 : 0; + + // Do not show current date when field not required (see select_date() method) + if (!$required && $value == '') $value = '-1'; + + // TODO Must also support $moreparam + $out = $form->select_date($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, ($keyprefix != 'search_' ? 1 : 0), 1, 0, 1); + } + elseif (in_array($type,array('int','integer'))) + { + $tmp=explode(',',$size); + $newsize=$tmp[0]; + $out=''; + } + elseif (preg_match('/varchar/', $type)) + { + $out=''; + } + elseif (in_array($type, array('mail', 'phone', 'url'))) + { + $out=''; + } + elseif ($type == 'text') + { + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); + $out=$doleditor->Create(1); + } + elseif ($type == 'boolean') + { + $checked=''; + if (!empty($value)) { + $checked=' checked value="1" '; + } else { + $checked=' value="1" '; + } + $out=''; + } + elseif ($type == 'price') + { + if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. + $value=price($value); + } + $out=' '.$langs->getCurrencySymbol($conf->currency); + } + elseif ($type == 'double') + { + if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. + $value=price($value); + } + $out=' '; + } + elseif ($type == 'select') + { + $out = ''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); + } + + $out.=''; + } + elseif ($type == 'sellist') + { + $out = ''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); + } + + $out.=''; + } + elseif ($type == 'checkbox') + { + $value_arr=explode(',',$value); + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); + } + elseif ($type == 'radio') + { + $out=''; + foreach ($param['options'] as $keyopt => $val) + { + $out.=''.$val.'
'; + } + } + elseif ($type == 'chkbxlst') + { + if (is_array($value)) { + $value_arr = $value; + } + else { + $value_arr = explode(',', $value); + } + + if (is_array($param['options'])) { + $param_list = array_keys($param['options']); + $InfoFieldList = explode(":", $param_list[0]); + // 0 : tableName + // 1 : label field name + // 2 : key fields name (if differ of rowid) + // 3 : key field parent (for dependent lists) + // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value + $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid'); + + if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) { + list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]); + $keyList .= ', ' . $parentField; + } + if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) { + if (strpos($InfoFieldList[4], 'extra.') !== false) { + $keyList = 'main.' . $InfoFieldList[2] . ' as rowid'; + } else { + $keyList = $InfoFieldList[2] . ' as rowid'; + } + } + + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $keyList .= ', '; + $keyList .= implode(', ', $fields_label); + } + + $sqlwhere = ''; + $sql = 'SELECT ' . $keyList; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; + if (! empty($InfoFieldList[4])) { + + // can use SELECT request + if (strpos($InfoFieldList[4], '$SEL$')!==false) { + $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]); + } + + // current object id can be use into filter + if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) { + $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]); + } else { + $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]); + } + + // We have to join on extrafield table + if (strpos($InfoFieldList[4], 'extra') !== false) { + $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra'; + $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4]; + } else { + $sqlwhere .= ' WHERE ' . $InfoFieldList[4]; + } + } else { + $sqlwhere .= ' WHERE 1=1'; + } + // Some tables may have field, some other not. For the moment we disable it. + if (in_array($InfoFieldList[0], array ('tablewithentity'))) + { + $sqlwhere .= ' AND entity = ' . $conf->entity; + } + // $sql.=preg_replace('/^ AND /','',$sqlwhere); + // print $sql; + + $sql .= $sqlwhere; + dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + + $data=array(); + + while ( $i < $num ) { + $labeltoshow = ''; + $obj = $this->db->fetch_object($resql); + + // Several field into label (eq table:code|libelle:rowid) + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $notrans = true; + foreach ( $fields_label as $field_toshow ) { + $labeltoshow .= $obj->$field_toshow . ' '; + } + } else { + $labeltoshow = $obj->{$InfoFieldList[1]}; + } + $labeltoshow = dol_trunc($labeltoshow, 45); + + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + foreach ( $fields_label as $field_toshow ) { + $translabel = $langs->trans($obj->$field_toshow); + if ($translabel != $obj->$field_toshow) { + $labeltoshow = dol_trunc($translabel, 18) . ' '; + } else { + $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' '; + } + } + + $data[$obj->rowid]=$labeltoshow; + + } else { + if (! $notrans) { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + if ($translabel != $obj->{$InfoFieldList[1]}) { + $labeltoshow = dol_trunc($translabel, 18); + } else { + $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18); + } + } + if (empty($labeltoshow)) + $labeltoshow = '(not defined)'; + + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + $data[$obj->rowid]=$labeltoshow; + } + + if (! empty($InfoFieldList[3])) { + $parent = $parentName . ':' . $obj->{$parentField}; + } + + $data[$obj->rowid]=$labeltoshow; + } + + $i ++; + } + $this->db->free($resql); + + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); + + } else { + print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
'; + } + } + $out .= ''; + } + elseif ($type == 'link') + { + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + $showempty=(($val['notnull'] == 1 && $val['default'] != '')?0:1); + $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty); + } + elseif ($type == 'password') + { + // If prefix is 'search_', field is used as a filter, we use a common text field. + $out=''; + } + if (!empty($hidden)) { + $out=''; + } + /* Add comments + if ($type == 'date') $out.=' (YYYY-MM-DD)'; + elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; + */ + return $out; + } + + + /** + * Return HTML string to show a field into a page + * Code very similar with showOutputField of extra fields + * + * @param array $val Array of properties of field to show + * @param string $key Key of attribute + * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) + * @param string $moreparam To add more parametes on html input tag + * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param mixed $showsize Value for css to define size. May also be a numeric. + * @return string + */ + function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0) + { + global $conf,$langs,$form; + + if (! is_object($form)) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + $form=new Form($this->db); + } + + $objectid = $this->id; + $label=$val['label']; + $type =$val['type']; + $size =$val['css']; + + // Convert var to be able to share same code than showOutputField of extrafields + if (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar + if (is_array($val['arrayofkeyval'])) $type='select'; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; + + //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used + $default=$val['default']; + $computed=$val['computed']; + $unique=$val['unique']; + $required=$val['required']; + $param=$val['param']; + if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) + { + $type='link'; + $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); + } + $langfile=$val['langfile']; + $list=$val['list']; + $help=$val['help']; + $hidden=(($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + + if ($hidden) return ''; + + // If field is a computed field, value must become result of compute + if ($computed) + { + // Make the eval of compute string + //var_dump($computed); + $value = dol_eval($computed, 1, 0); + } + + if (empty($showsize)) + { + if ($type == 'date') + { + $showsize=10; + } + elseif ($type == 'datetime') + { + $showsize=19; + } + elseif ($type == 'int' || $type == 'integer') + { + $showsize=10; + } + else + { + $showsize=round($size); + if ($showsize > 48) $showsize=48; + } + } + + if ($key == 'ref') $value=$this->getNomUrl(1, '', 0, '', 1); + elseif ($key == 'status') $value=$this->getLibStatut(3); + elseif ($type == 'date') + { + $value=dol_print_date($value,'day'); + } + elseif ($type == 'datetime') + { + $value=dol_print_date($value,'dayhour'); + } + elseif ($type == 'double') + { + if (!empty($value)) { + $value=price($value); + } + } + elseif ($type == 'boolean') + { + $checked=''; + if (!empty($value)) { + $checked=' checked '; + } + $value=''; + } + elseif ($type == 'mail') + { + $value=dol_print_email($value,0,0,0,64,1,1); + } + elseif ($type == 'url') + { + $value=dol_print_url($value,'_blank',32,1); + } + elseif ($type == 'phone') + { + $value=dol_print_phone($value, '', 0, 0, '', ' ', 1); + } + elseif ($type == 'price') + { + $value=price($value,0,$langs,0,0,-1,$conf->currency); + } + elseif ($type == 'select') + { + $value=$params['options'][$value]; + } + elseif ($type == 'sellist') + { + $param_list=array_keys($params['options']); + $InfoFieldList = explode(":", $param_list[0]); + + $selectkey="rowid"; + $keyList='rowid'; + + if (count($InfoFieldList)>=3) + { + $selectkey = $InfoFieldList[2]; + $keyList=$InfoFieldList[2].' as rowid'; + } + + $fields_label = explode('|',$InfoFieldList[1]); + if(is_array($fields_label)) { + $keyList .=', '; + $keyList .= implode(', ', $fields_label); + } + + $sql = 'SELECT '.$keyList; + $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0]; + if (strpos($InfoFieldList[4], 'extra')!==false) + { + $sql.= ' as main'; + } + if ($selectkey=='rowid' && empty($value)) { + $sql.= " WHERE ".$selectkey."=0"; + } elseif ($selectkey=='rowid') { + $sql.= " WHERE ".$selectkey."=".$this->db->escape($value); + }else { + $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; + } + + //$sql.= ' AND entity = '.$conf->entity; + + dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $value=''; // value was used, so now we reste it to use it to build final output + + $obj = $this->db->fetch_object($resql); + + // Several field into label (eq table:code|libelle:rowid) + $fields_label = explode('|',$InfoFieldList[1]); + + if(is_array($fields_label) && count($fields_label)>1) + { + foreach ($fields_label as $field_toshow) + { + $translabel=''; + if (!empty($obj->$field_toshow)) { + $translabel=$langs->trans($obj->$field_toshow); + } + if ($translabel!=$field_toshow) { + $value.=dol_trunc($translabel,18).' '; + }else { + $value.=$obj->$field_toshow.' '; + } + } + } + else + { + $translabel=''; + if (!empty($obj->{$InfoFieldList[1]})) { + $translabel=$langs->trans($obj->{$InfoFieldList[1]}); + } + if ($translabel!=$obj->{$InfoFieldList[1]}) { + $value=dol_trunc($translabel,18); + }else { + $value=$obj->{$InfoFieldList[1]}; + } + } + } + else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING); + } + elseif ($type == 'radio') + { + $value=$params['options'][$value]; + } + elseif ($type == 'checkbox') + { + $value_arr=explode(',',$value); + $value=''; + if (is_array($value_arr)) + { + foreach ($value_arr as $keyval=>$valueval) { + $toprint[]='
  • '.$params['options'][$valueval].'
  • '; + } + } + $value='
      '.implode(' ', $toprint).'
    '; + } + elseif ($type == 'chkbxlst') + { + $value_arr = explode(',', $value); + + $param_list = array_keys($params['options']); + $InfoFieldList = explode(":", $param_list[0]); + + $selectkey = "rowid"; + $keyList = 'rowid'; + + if (count($InfoFieldList) >= 3) { + $selectkey = $InfoFieldList[2]; + $keyList = $InfoFieldList[2] . ' as rowid'; + } + + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($fields_label)) { + $keyList .= ', '; + $keyList .= implode(', ', $fields_label); + } + + $sql = 'SELECT ' . $keyList; + $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0]; + if (strpos($InfoFieldList[4], 'extra') !== false) { + $sql .= ' as main'; + } + // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; + // $sql.= ' AND entity = '.$conf->entity; + + dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $value = ''; // value was used, so now we reste it to use it to build final output + $toprint=array(); + while ( $obj = $this->db->fetch_object($resql) ) { + + // Several field into label (eq table:code|libelle:rowid) + $fields_label = explode('|', $InfoFieldList[1]); + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + if (is_array($fields_label) && count($fields_label) > 1) { + foreach ( $fields_label as $field_toshow ) { + $translabel = ''; + if (! empty($obj->$field_toshow)) { + $translabel = $langs->trans($obj->$field_toshow); + } + if ($translabel != $field_toshow) { + $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; + } else { + $toprint[]='
  • '.$obj->$field_toshow.'
  • '; + } + } + } else { + $translabel = ''; + if (! empty($obj->{$InfoFieldList[1]})) { + $translabel = $langs->trans($obj->{$InfoFieldList[1]}); + } + if ($translabel != $obj->{$InfoFieldList[1]}) { + $toprint[]='
  • '.dol_trunc($translabel, 18).'
  • '; + } else { + $toprint[]='
  • '.$obj->{$InfoFieldList[1]}.'
  • '; + } + } + } + } + $value='
      '.implode(' ', $toprint).'
    '; + + } else { + dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING); + } + } + elseif ($type == 'link') + { + $out=''; + + // only if something to display (perf) + if ($value) + { + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + + $InfoFieldList = explode(":", $param_list[0]); + $classname=$InfoFieldList[0]; + $classpath=$InfoFieldList[1]; + if (! empty($classpath)) + { + dol_include_once($InfoFieldList[1]); + if ($classname && class_exists($classname)) + { + $object = new $classname($this->db); + $object->fetch($value); + $value=$object->getNomUrl(3); + } + } + else + { + dol_syslog('Error bad setup of extrafield', LOG_WARNING); + return 'Error bad setup of extrafield'; + } + } + } + elseif ($type == 'text') + { + $value=dol_htmlentitiesbr($value); + } + elseif ($type == 'password') + { + $value=preg_replace('/./i','*',$value); + } + + //print $type.'-'.$size; + $out=$value; + + return $out; + } + + + /** + * Function to show lines of extrafields with output datas + * + * @param Extrafields $extrafields Extrafield Object + * @param string $mode Show output (view) or input (edit) for extrafield + * @param array $params Optional parameters + * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names) + * + * @return string + */ + function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='') { global $_POST, $conf, $langs, $action; @@ -4617,6 +5618,9 @@ abstract class CommonObject $e = 0; foreach($extrafields->attribute_label as $key=>$label) { + if (empty($extrafields->attribute_list[$key])) continue; // 0 = Never visible field + if (($mode == 'create' || $mode == 'edit') && abs($extrafields->attribute_list[$key]) != 1) continue; // <> -1 and <> 1 = not visible on forms, only on list + // Load language if required if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]); @@ -4630,12 +5634,12 @@ abstract class CommonObject switch($mode) { case "view": - $value=$this->array_options["options_".$key]; + $value=$this->array_options["options_".$key.$keysuffix]; break; case "edit": - $getposttemp = GETPOST('options_'.$key, 'none'); // GETPOST can get value from GET, POST or setup of default values. + $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values. // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc') - if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET('options_'.$key)) + if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)) { if (is_array($getposttemp)) { // $getposttemp is an array but following code expects a comma separated string @@ -4675,12 +5679,12 @@ abstract class CommonObject // Convert date into timestamp format (value in memory must be a timestamp) if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) { - $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$this->db->jdate($this->array_options['options_'.$key]); + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min",'int',3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year",'int',3)):$this->db->jdate($this->array_options['options_'.$key]); } // Convert float submited string into real php numeric (value in memory must be a php numeric) if (in_array($extrafields->attribute_type[$key],array('price','double'))) { - $value = isset($_POST["options_".$key])?price2num($_POST["options_".$key]):$this->array_options['options_'.$key]; + $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix,'int',3)):$this->array_options['options_'.$key]; } $labeltoshow = $langs->trans($label); @@ -4699,7 +5703,7 @@ abstract class CommonObject $out .= $extrafields->showOutputField($key, $value); break; case "edit": - $out .= $extrafields->showInputField($key, $value, '', $keyprefix, '', 0, $this->id); + $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id); break; } @@ -4712,8 +5716,8 @@ abstract class CommonObject } $out .= "\n"; // Add code to manage list depending on others - if (! empty($conf->use_javascript_ajax)) - $out .= ' + if (! empty($conf->use_javascript_ajax)) { + $out .= ' '."\n"; - $out .= ' '."\n"; + $out .= ' '."\n"; + } } return $out; } + /** * Returns the rights used for this class * @return stdClass @@ -5038,7 +6044,7 @@ abstract class CommonObject } /** - * Function to load data into current object this + * Function to load data from a SQL pointer into properties of current object $this * * @param stdClass $obj Contain data of object from database */ @@ -5076,8 +6082,10 @@ abstract class CommonObject { $this->{$field} = $obj->{$field}; } - } + + // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions. + if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id; } /** @@ -5114,6 +6122,8 @@ abstract class CommonObject */ public function createCommon(User $user, $notrigger = false) { + global $langs; + $error = 0; $now=dol_now(); @@ -5126,10 +6136,27 @@ abstract class CommonObject $keys=array(); $values = array(); foreach ($fieldvalues as $k => $v) { - $keys[] = $k; - $values[] = $this->quote($v, $this->fields[$k]); + $keys[$k] = $k; + $value = $this->fields[$k]; + $values[$k] = $this->quote($v, $value); } + // Clean and check mandatory + foreach($keys as $key) + { + if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]=''; // This is an implicit foreign key field + if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]=''; // This is an explicit foreign key field + + //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); + if ($this->fields[$key]['notnull'] == 1 && empty($values[$key])) + { + $error++; + $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); + } + } + + if ($error) return -1; + $this->db->begin(); if (! $error) @@ -5223,26 +6250,38 @@ abstract class CommonObject */ public function updateCommon(User $user, $notrigger = false) { + global $langs; + $error = 0; - $fieldvalues = $this->set_save_query(); - unset($fieldvalues['rowid']); // We don't update this field, it is the key to define which record to update. + $now=dol_now(); + $fieldvalues = $this->set_save_query(); + if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now); + if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id; + unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update. + + $keys=array(); foreach ($fieldvalues as $k => $v) { - if (is_array($key)){ - $i=array_search($k, $key); - if ( $i !== false) { - $where[] = $key[$i].'=' . $this->quote($v, $this->fields[$k]); - continue; - } - } else { - if ( $k == $key) { - $where[] = $k.'=' .$this->quote($v, $this->fields[$k]); - continue; - } - } + $keys[$k] = $k; $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]); } + + // Clean and check mandatory + foreach($keys as $key) + { + if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]=''; // This is an implicit foreign key field + if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]=''; // This is an explicit foreign key field + + //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1)); + /* + if ($this->fields[$key]['notnull'] == 1 && empty($values[$key])) + { + $error++; + $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']); + }*/ + } + $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ; $this->db->begin(); diff --git a/htdocs/core/class/commonobjectline.class.php b/htdocs/core/class/commonobjectline.class.php index 84c49f6392d..bed227eb408 100644 --- a/htdocs/core/class/commonobjectline.class.php +++ b/htdocs/core/class/commonobjectline.class.php @@ -51,8 +51,9 @@ abstract class CommonObjectLine extends CommonObject /** - * Returns the text label from units dictionary - * + * Returns the translation key from units dictionary. + * A langs->trans() must be called on result to get translated value. + * * @param string $type Label type (long or short) * @return string|int <0 if ko, label if ok */ diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index d603d1b6cc1..f2885a50951 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -81,14 +81,16 @@ class DolGraph /** * Constructor + * + * @param string $library 'jflot' (default) or 'artichow' (no more supported) */ - function __construct() + function __construct($library='jflot') { global $conf; global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet; // To use old feature - if (isset($conf->global->MAIN_GRAPH_LIBRARY) && $conf->global->MAIN_GRAPH_LIBRARY == 'artichow') + if ($library == 'artichow') { $this->_library='artichow'; @@ -586,7 +588,7 @@ class DolGraph } /** - * Build a graph onto disk using correct library + * Build a graph into memory using correct library (may also be wrote on disk, depending on library used) * * @param string $file Image file name to use to save onto disk (also used as javascript unique id) * @param string $fileurl Url path to show image if saved onto disk diff --git a/htdocs/core/class/emailsenderprofile.class.php b/htdocs/core/class/emailsenderprofile.class.php index 66e37744cc7..7f34165030b 100644 --- a/htdocs/core/class/emailsenderprofile.class.php +++ b/htdocs/core/class/emailsenderprofile.class.php @@ -43,15 +43,10 @@ class EmailSenderProfile extends CommonObject * @var string Name of table without prefix where object is stored */ public $table_element = 'c_email_senderprofile'; - - /** - * @var array Does this field is linked to a thirdparty ? - */ - protected $isnolinkedbythird = 1; /** * @var array Does emailsenderprofile support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe */ - protected $ismultientitymanaged = 1; + public $ismultientitymanaged = 1; /** * @var string String with name of icon for emailsenderprofile */ @@ -267,22 +262,24 @@ class EmailSenderProfile extends CommonObject function getNomUrl($withpicto=0) { global $db, $conf, $langs; - global $dolibarr_main_authentication, $dolibarr_main_demo; - global $menumanager; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; - $result = ''; - $companylink = ''; + $result = ''; + $companylink = ''; - $url=''; - //$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id; + $label=$this->label; + + $url=''; + //$url = dol_buildpath('/monmodule/emailsenderprofile_card.php',1).'?id='.$this->id; $linkstart = ''; $linkend=''; - if ($withpicto) - { - $result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend); - if ($withpicto != 2) $result.=' '; + if ($withpicto) + { + $result.=($linkstart.img_object($label, 'label', 'class="classfortooltip"').$linkend); + if ($withpicto != 2) $result.=' '; } $result.= $linkstart . $this->label . $linkend; return $result; diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 43af66e51e7..ca7bed7ff4e 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -140,8 +140,8 @@ class ExtraFields * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @param int $alwayseditable Is attribute always editable regardless of the document status * @param string $perms Permission to check - * @param int $list Into list view by default (-1, 0 or 1) - * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param int $list Visibilty + * @param int $ishidden Deprecated. Us visibility instead. * @param string $computed Computed value * @param string $entity Entity of extrafields * @param string $langfile Language file @@ -279,8 +279,8 @@ class ExtraFields * @param array|string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @param int $alwayseditable Is attribute always editable regardless of the document status * @param string $perms Permission to check - * @param int $list Into list view by default (-1, 0 or 1) - * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param int $list Visibily + * @param int $ishidden Deprecated. Use visibility instead. * @param string $default Default value (in database. use the default_value feature for default value on screen). * @param string $computed Computed value * @param string $entity Entity of extrafields @@ -328,7 +328,6 @@ class ExtraFields $sql.= " perms,"; $sql.= " langs,"; $sql.= " list,"; - $sql.= " ishidden,"; $sql.= " fielddefault,"; $sql.= " fieldcomputed,"; $sql.= " fk_user_author,"; @@ -349,7 +348,6 @@ class ExtraFields $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").","; $sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").","; $sql.= " ".$list.","; - $sql.= " ".$ishidden.","; $sql.= " ".($default?"'".$this->db->escape($default)."'":"null").","; $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").","; $sql .= " " . $user->id . ","; @@ -483,8 +481,8 @@ class ExtraFields * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @param int $alwayseditable Is attribute always editable regardless of the document status * @param string $perms Permission to check - * @param int $list Into list view by default - * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param int $list Visibility + * @param int $ishidden Deprecated. Use visiblity instead. * @param string $default Default value (in database. use the default_value feature for default value on screen). * @param string $computed Computed value * @param string $entity Entity of extrafields @@ -589,8 +587,8 @@ class ExtraFields * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) * @param int $alwayseditable Is attribute always editable regardless of the document status * @param string $perms Permission to check - * @param int $list Into list view by default - * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param int $list Visiblity + * @param int $ishidden Deprecated. Use visility instead. * @param string $default Default value (in database. use the default_value feature for default value on screen). * @param string $computed Computed value * @param string $entity Entity of extrafields @@ -639,7 +637,6 @@ class ExtraFields $sql.= " alwayseditable,"; $sql.= " param,"; $sql.= " list,"; - $sql.= " ishidden,"; $sql.= " fielddefault,"; $sql.= " fieldcomputed,"; $sql.= " fk_user_author,"; @@ -660,7 +657,6 @@ class ExtraFields $sql.= " '".$alwayseditable."',"; $sql.= " '".$param."',"; $sql.= " ".$list.", "; - $sql.= " ".$ishidden.", "; $sql.= " ".(($default!='')?"'".$this->db->escape($default)."'":"null").","; $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").","; $sql .= " " . $user->id . ","; @@ -714,7 +710,7 @@ class ExtraFields // We should not have several time this log. If we have, there is some optimization to do by calling a simple $object->fetch_optionals() that include cache management. dol_syslog("fetch_name_optionals_label elementtype=".$elementtype); - $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,ishidden,fielddefault,fieldcomputed"; + $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,fielddefault,fieldcomputed"; $sql .= ",entity"; $sql.= " FROM ".MAIN_DB_PREFIX."extrafields"; $sql.= " WHERE entity IN (0,".$conf->entity.")"; @@ -749,7 +745,6 @@ class ExtraFields $this->attribute_perms[$tab->name]=$tab->perms; $this->attribute_langfile[$tab->name]=$tab->langs; $this->attribute_list[$tab->name]=$tab->list; - $this->attribute_hidden[$tab->name]=$tab->ishidden; $this->attribute_entityid[$tab->name]=$tab->entity; // New usage @@ -767,7 +762,6 @@ class ExtraFields $this->attributes[$tab->elementtype]['perms'][$tab->name]=$tab->perms; $this->attributes[$tab->elementtype]['langfile'][$tab->name]=$tab->langs; $this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list; - $this->attributes[$tab->elementtype]['ishidden'][$tab->name]=$tab->ishidden; $this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity; if (!empty($conf->multicompany->enabled)) @@ -802,24 +796,33 @@ class ExtraFields /** * Return HTML string to put an input field into a page + * Code very similar with showInputField of common object * * @param string $key Key of attribute * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) * @param string $moreparam To add more parametes on html input tag - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * @param string $keysuffix Suffix string to add into name and id of field (can be used to avoid duplicate names) + * @param string $keysuffix Prefix string to add after name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add before name and id of field (can be used to avoid duplicate names) * @param mixed $showsize Value for css to define size. May also be a numeric. * @param int $objectid Current object id * @return string */ - function showInputField($key, $value, $moreparam='', $keyprefix='', $keysuffix='', $showsize=0, $objectid=0) + function showInputField($key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0, $objectid=0) { - global $conf,$langs; + global $conf,$langs,$form; + + if (! is_object($form)) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + $form=new Form($this->db); + } + + $keyprefix = $keyprefix.'options_'; // Because we work on extrafields $label=$this->attribute_label[$key]; $type =$this->attribute_type[$key]; $size =$this->attribute_size[$key]; - $elementtype=$this->attribute_elementtype[$key]; + $elementtype=$this->attribute_elementtype[$key]; // Seems not used $default=$this->attribute_default[$key]; $computed=$this->attribute_computed[$key]; $unique=$this->attribute_unique[$key]; @@ -831,51 +834,51 @@ class ExtraFields if ($computed) { - if ($keysuffix != 'search_') return ''.$langs->trans("AutomaticallyCalculated").''; - else return ''; + if (! preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; + else return ''; } if (empty($showsize)) { - if ($type == 'date') - { - //$showsize=10; - $showsize = 'minwidth100imp'; - } + if ($type == 'date') + { + //$showsize=10; + $showsize = 'minwidth100imp'; + } elseif ($type == 'datetime') - { - //$showsize=19; - $showsize = 'minwidth200imp'; - } - elseif (in_array($type,array('int','double','price'))) - { - //$showsize=10; - $showsize = 'maxwidth75'; - } - elseif ($type == 'url') - { - $showsize='minwidth400'; - } - elseif ($type == 'boolean') - { - $showsize=''; - } - else - { - if (round($size) < 12) - { - $showsize = 'minwidth100'; - } - else if (round($size) <= 48) - { - $showsize = 'minwidth200'; - } - else - { - //$showsize=48; - $showsize = 'minwidth400'; - } - } + { + //$showsize=19; + $showsize = 'minwidth200imp'; + } + elseif (in_array($type,array('int','integer','double','price'))) + { + //$showsize=10; + $showsize = 'maxwidth75'; + } + elseif ($type == 'url') + { + $showsize='minwidth400'; + } + elseif ($type == 'boolean') + { + $showsize=''; + } + else + { + if (round($size) < 12) + { + $showsize = 'minwidth100'; + } + else if (round($size) <= 48) + { + $showsize = 'minwidth200'; + } + else + { + //$showsize=48; + $showsize = 'minwidth400'; + } + } } if (in_array($type,array('date','datetime'))) @@ -888,31 +891,27 @@ class ExtraFields // Do not show current date when field not required (see select_date() method) if (!$required && $value == '') $value = '-1'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - global $form; - if (! is_object($form)) $form=new Form($this->db); - // TODO Must also support $moreparam - $out = $form->select_date($value, $keysuffix.'options_'.$key.$keyprefix, $showtime, $showtime, $required, '', 1, ($keysuffix != 'search_' ? 1 : 0), 1, 0, 1); + $out = $form->select_date($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, ($keyprefix != 'search_' ? 1 : 0), 1, 0, 1); } - elseif (in_array($type,array('int'))) + elseif (in_array($type,array('int','integer'))) { $tmp=explode(',',$size); $newsize=$tmp[0]; - $out=''; + $out=''; } - elseif ($type == 'varchar') + elseif (preg_match('/varchar/', $type)) { - $out=''; + $out=''; } elseif (in_array($type, array('mail', 'phone', 'url'))) { - $out=''; + $out=''; } elseif ($type == 'text') { require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor($keysuffix.'options_'.$key.$keyprefix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); + $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%'); $out=$doleditor->Create(1); } elseif ($type == 'boolean') @@ -923,21 +922,21 @@ class ExtraFields } else { $checked=' value="1" '; } - $out=''; + $out=''; } elseif ($type == 'price') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value=price($value); } - $out=' '.$langs->getCurrencySymbol($conf->currency); + $out=' '.$langs->getCurrencySymbol($conf->currency); } elseif ($type == 'double') { if (!empty($value)) { // $value in memory is a php numeric, we format it into user number format. $value=price($value); } - $out=' '; + $out=' '; } elseif ($type == 'select') { @@ -945,10 +944,10 @@ class ExtraFields if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keysuffix.'options_'.$key.$keyprefix, array(), 0); + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } - $out.=''; $out.=''; foreach ($param['options'] as $key => $val) { @@ -967,14 +966,15 @@ class ExtraFields if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; - $out.= ajax_combobox($keysuffix.'options_'.$key.$keyprefix, array(), 0); + $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } - $out.=''; if (is_array($param['options'])) { $param_list=array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); + $parentName=''; // 0 : tableName // 1 : label field name // 2 : key fields name (if differ of rowid) @@ -1059,8 +1059,9 @@ class ExtraFields $obj = $this->db->fetch_object($resql); // Several field into label (eq table:code|libelle:rowid) + $notrans = false; $fields_label = explode('|',$InfoFieldList[1]); - if(is_array($fields_label)) + if (is_array($fields_label)) { $notrans = true; foreach ($fields_label as $field_toshow) @@ -1074,7 +1075,7 @@ class ExtraFields } $labeltoshow=dol_trunc($labeltoshow,45); - if ($value==$obj->rowid) + if ($value == $obj->rowid) { foreach ($fields_label as $field_toshow) { @@ -1089,7 +1090,7 @@ class ExtraFields } else { - if(!$notrans) + if (! $notrans) { $translabel=$langs->trans($obj->{$InfoFieldList[1]}); if ($translabel!=$obj->{$InfoFieldList[1]}) { @@ -1128,23 +1129,19 @@ class ExtraFields } elseif ($type == 'checkbox') { - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form = new Form($db); - $value_arr=explode(',',$value); - $out=$form->multiselectarray($keysuffix.'options_'.$key.$keyprefix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); - + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%'); } elseif ($type == 'radio') { $out=''; foreach ($param['options'] as $keyopt => $val) { - $out.=''.$val.'
    '; + $out.='/>
    '; } } elseif ($type == 'chkbxlst') @@ -1268,25 +1265,22 @@ class ExtraFields if (empty($labeltoshow)) $labeltoshow = '(not defined)'; - if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) { + $data[$obj->rowid]=$labeltoshow; + } + + if (! empty($InfoFieldList[3])) { + $parent = $parentName . ':' . $obj->{$parentField}; + } + $data[$obj->rowid]=$labeltoshow; - } - - if (! empty($InfoFieldList[3])) { - $parent = $parentName . ':' . $obj->{$parentField}; - } - - $data[$obj->rowid]=$labeltoshow; } $i ++; } $this->db->free($resql); - require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $form = new Form($db); - - $out=$form->multiselectarray($keysuffix.'options_'.$key.$keyprefix, $data, $value_arr, '', 0, '', 0, '100%'); + $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%'); } else { print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.
    '; @@ -1296,62 +1290,39 @@ class ExtraFields } elseif ($type == 'link') { - $out=''; - - $param_list=array_keys($param['options']); - // 0 : ObjectName - // 1 : classPath - $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) - { - $valuetoshow=$value; - if (!empty($value)) - { - $object = new $InfoFieldList[0]($this->db); - $resfetch=$object->fetch($value); - if ($resfetch > 0) - { - $valuetoshow=$object->ref; - if ($object->element == 'societe') $valuetoshow=$object->name; // Special case for thirdparty because ->ref is not name but id (because name is not unique) - } - } - $out.=''; - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - $out.='Error bad setup of extrafield'; - } + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + $showempty=(($val['notnull'] == 1 && $val['default'] != '')?0:1); + $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty); } elseif ($type == 'password') { // If prefix is 'search_', field is used as a filter, we use a common text field. - $out=''; + $out=''; } if (!empty($hidden)) { - $out=''; + $out=''; } /* Add comments if ($type == 'date') $out.=' (YYYY-MM-DD)'; - elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; - */ + elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)'; + */ return $out; } + /** * Return HTML string to put an output field into a page * * @param string $key Key of attribute * @param string $value Value to show - * @param string $moreparam To add more parametes on html input tag (only checkbox use html input for output rendering) + * @param string $moreparam To add more parameters on html input tag (only checkbox use html input for output rendering) * @return string Formated value */ function showOutputField($key,$value,$moreparam='') { global $conf,$langs; - $elementtype=$this->attribute_elementtype[$key]; + $elementtype=$this->attribute_elementtype[$key]; // seems not used $label=$this->attribute_label[$key]; $type=$this->attribute_type[$key]; $size=$this->attribute_size[$key]; @@ -1359,11 +1330,13 @@ class ExtraFields $computed=$this->attribute_computed[$key]; $unique=$this->attribute_unique[$key]; $required=$this->attribute_required[$key]; - $params=$this->attribute_param[$key]; + $param=$this->attribute_param[$key]; $perms=$this->attribute_perms[$key]; $langfile=$this->attribute_langfile[$key]; $list=$this->attribute_list[$key]; - $hidden=$this->attribute_hidden[$key]; // warning, do not rely on this. If your module need a hidden data, it must use its own table. + $hidden=(($list != 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller) + + if ($hidden) return ''; // This is a protection. If field is hidden, we should just not call this method. // If field is a computed field, value must become result of compute if ($computed) @@ -1420,11 +1393,11 @@ class ExtraFields } elseif ($type == 'select') { - $value=$params['options'][$value]; + $value=$param['options'][$value]; } elseif ($type == 'sellist') { - $param_list=array_keys($params['options']); + $param_list=array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); $selectkey="rowid"; @@ -1501,7 +1474,7 @@ class ExtraFields } elseif ($type == 'radio') { - $value=$params['options'][$value]; + $value=$param['options'][$value]; } elseif ($type == 'checkbox') { @@ -1510,7 +1483,7 @@ class ExtraFields if (is_array($value_arr)) { foreach ($value_arr as $keyval=>$valueval) { - $toprint[]='
  • '.$params['options'][$valueval].'
  • '; + $toprint[]='
  • '.$param['options'][$valueval].'
  • '; } } $value='
      '.implode(' ', $toprint).'
    '; @@ -1519,7 +1492,7 @@ class ExtraFields { $value_arr = explode(',', $value); - $param_list = array_keys($params['options']); + $param_list = array_keys($param['options']); $InfoFieldList = explode(":", $param_list[0]); $selectkey = "rowid"; @@ -1591,22 +1564,26 @@ class ExtraFields // only if something to display (perf) if ($value) { - $param_list=array_keys($params['options']); - // 0 : ObjectName - // 1 : classPath + $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' + $InfoFieldList = explode(":", $param_list[0]); - dol_include_once($InfoFieldList[1]); - if ($InfoFieldList[0] && class_exists($InfoFieldList[0])) - { - $object = new $InfoFieldList[0]($this->db); - $object->fetch($value); - $value=$object->getNomUrl(3); - } - else - { - dol_syslog('Error bad setup of extrafield', LOG_WARNING); - $out.='Error bad setup of extrafield'; - } + $classname=$InfoFieldList[0]; + $classpath=$InfoFieldList[1]; + if (! empty($classpath)) + { + dol_include_once($InfoFieldList[1]); + if ($classname && class_exists($classname)) + { + $object = new $classname($this->db); + $object->fetch($value); + $value=$object->getNomUrl(3); + } + } + else + { + dol_syslog('Error bad setup of extrafield', LOG_WARNING); + return 'Error bad setup of extrafield'; + } } } elseif ($type == 'text') @@ -1626,10 +1603,6 @@ class ExtraFields //print $type.'-'.$size; $out=$value; - if (!empty($hidden)) { - $out=''; - } - return $out; } diff --git a/htdocs/core/class/fiscalyear.class.php b/htdocs/core/class/fiscalyear.class.php index 38804442033..5e5ff6e3ce8 100644 --- a/htdocs/core/class/fiscalyear.class.php +++ b/htdocs/core/class/fiscalyear.class.php @@ -32,7 +32,7 @@ class Fiscalyear extends CommonObject public $table_element='accounting_fiscalyear'; public $table_element_line = ''; public $fk_element = ''; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe var $rowid; diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index faf26f7c111..7df1fd1f4a2 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -438,8 +438,11 @@ class Form $s='';$textfordialog=''; - $htmltext=str_replace('"',""",$htmltext); - if ($tooltiptrigger != '') + if ($tooltiptrigger == '') + { + $htmltext=str_replace('"',""",$htmltext); + } + else { $classfortooltip='classfortooltiponclick'; $textfordialog.=''; @@ -501,7 +504,7 @@ class Form global $conf, $langs; $alt = ''; - if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp"); + if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp"); //For backwards compatibility if ($type == '0') $type = 'info'; @@ -724,7 +727,7 @@ class Form * @param string $page Defined the form action * @param string $htmlname Name of html select object * @param string $htmloption Options html on select object - * @param int $forcecombo Force to use standard combo box (no ajax use) + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) * @param array $events Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) * @return string HTML string with select and input */ @@ -956,7 +959,7 @@ class Form * @param int $filter Filter on thirdparty * @param int $limit Limit on number of returned lines * @param array $ajaxoptions Options for ajax_autocompleter - * @param int $forcecombo Force to use combo box + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) * @return string Return select box for thirdparty. * @deprecated 3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0) */ @@ -973,7 +976,7 @@ class Form * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)') * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) * @param array $events Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) * @param int $limit Maximum number of elements * @param string $morecss Add more css styles to the SELECT component @@ -1004,20 +1007,15 @@ class Form // mode 1 $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:''); $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); - $out.=''; + $out.=''; if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; else if ($hidelabel > 1) { - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; - else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; + $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; if ($hidelabel == 2) { $out.= img_picto($langs->trans("Search"), 'search'); } } - $out.= 'global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; + $out.= 'global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; if ($hidelabel == 3) { $out.= img_picto($langs->trans("Search"), 'search'); } @@ -1040,7 +1038,7 @@ class Form * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)') * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box + * @param int $forcecombo Force to use standard HTML select component without beautification * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) * @param string $filterkey Filter on key value * @param int $outputmode 0=HTML select string, 1=Array @@ -1149,17 +1147,23 @@ class Form if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier"); if ($obj->client || $obj->fournisseur) $label.=')'; } - if ($selected > 0 && $selected == $obj->rowid) + + if (empty($outputmode)) { - $out.= ''; + if ($selected > 0 && $selected == $obj->rowid) + { + $out.= ''; + } + else + { + $out.= ''; + } } else { - $out.= ''; + array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label)); } - array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label)); - $i++; if (($i % 10) == 0) $out.="\n"; } @@ -1813,8 +1817,7 @@ class Form } if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : '; else if ($hidelabel > 1) { - if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; - else $placeholder=' title="'.$langs->trans("RefOrLabel").'"'; + $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"'; if ($hidelabel == 2) { print img_picto($langs->trans("Search"), 'search'); } @@ -2561,6 +2564,8 @@ class Form $this->db->free($result); + $out.=ajax_combobox($htmlname); + if (empty($outputmode)) return $out; return $outarray; } @@ -4519,6 +4524,8 @@ class Form { global $langs,$conf,$mysoc; + $langs->load('errors'); + $return=''; // Define defaultnpr, defaultttx and defaultcode @@ -4687,7 +4694,7 @@ class Form * * @param timestamp $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0). * @param string $prefix Prefix for fields name - * @param int $h 1=Show also hours + * @param int $h 1=Show also hours (-1 has same effect, but hour and minutes are prefilled with 23:59 if $set_time = -1) * @param int $m 1=Show also minutes * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only * @param string $form_name Not used @@ -4742,6 +4749,13 @@ class Form { $shour = dol_print_date($set_time, "%H"); $smin = dol_print_date($set_time, "%M"); + $ssec = dol_print_date($set_time, "%S"); + } + else + { + $shour = ''; + $smin = ''; + $ssec = ''; } } else @@ -4750,8 +4764,9 @@ class Form $syear = ''; $smonth = ''; $sday = ''; - $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? '' : $conf->global->MAIN_DEFAULT_DATE_HOUR; - $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? '' : $conf->global->MAIN_DEFAULT_DATE_MIN; + $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR; + $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN; + $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC; } // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery' @@ -4932,6 +4947,8 @@ class Form $retstring.=''; } $retstring.=''; + + $retstring.=''; } // Add a "Now" link @@ -5112,6 +5129,202 @@ class Form } + /** + * Generic method to select a component from a combo list. + * This is the generic method that will replace all specific existing methods. + * + * @param string $objectdesc Objectclassname:Objectclasspath + * @param string $htmlname Name of HTML select component + * @param int $preselectedvalue Preselected value (ID of element) + * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...) + * @param string $searchkey Search criteria + * @param string $placeholder Place holder + * @param string $morecss More CSS + * @param string $moreparams More params provided to ajax call + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) + * @return string Return HTML string + * @see selectForFormsList select_thirdparty + */ + function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0) + { + global $conf, $user; + + $objecttmp = null; + + $InfoFieldList = explode(":", $objectdesc); + $classname=$InfoFieldList[0]; + $classpath=$InfoFieldList[1]; + if (! empty($classpath)) + { + dol_include_once($classpath); + if ($classname && class_exists($classname)) + { + $objecttmp = new $classname($this->db); + } + } + if (! is_object($objecttmp)) + { + dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING); + return 'Error bad setup of type for field '.join(',', $InfoFieldList); + } + + $prefixforautocompletemode=$objecttmp->element; + if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company'; + $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT + + dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG); + + $out=''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo) + { + $objectdesc=$classname.':'.$classpath; + $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php'; + //if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php'; + + // No immediate load of all database + $urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:''); + // Activate the auto complete using ajax call. + $out.= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array()); + $out.= ''; + if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"'; + $out.= ''; + } + else + { + // Immediate load of all database + $out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo); + } + + return $out; + } + + /** + * Output html form to select an object. + * Note, this function is called by selectForForms or by ajax selectobject.php + * + * @param Object $objecttmp Object + * @param string $htmlname Name of HTML select component + * @param int $preselectedvalue Preselected value (ID of element) + * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...) + * @param string $searchkey Search value + * @param string $placeholder Place holder + * @param string $morecss More CSS + * @param string $moreparams More params provided to ajax call + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) + * @param int $outputmode 0=HTML select string, 1=Array + * @return string Return HTML string + * @see selectForForms + */ + function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0) + { + global $conf, $langs, $user; + + $prefixforautocompletemode=$objecttmp->element; + if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company'; + $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT + + $fieldstoshow='t.ref'; + if (! empty($objecttmp->fields)) + { + $tmpfieldstoshow=''; + foreach($objecttmp->fields as $key => $val) + { + if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key; + } + if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow; + } + + $out=''; + $outarray=array(); + + $num=0; + + // Search data + $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t"; + if ($objecttmp->ismultientitymanaged == 2) + if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql.= " WHERE t.entity IN (".getEntity($objecttmp->table_element).")"; + if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id)) $sql.= " AND t.fk_soc = ".$user->societe_id; + if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey); + if ($objecttmp->ismultientitymanaged == 2) + if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + $sql.=$this->db->order($fieldstoshow,"ASC"); + //$sql.=$this->db->plimit($limit, 0); + + // Build output string + $resql=$this->db->query($sql); + if ($resql) + { + if ($conf->use_javascript_ajax && ! $forcecombo) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; + $comboenhancement =ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode); + $out.= $comboenhancement; + } + + // Construct $out and $outarray + $out.= ''."\n"; + } + else + { + dol_print_error($this->db); + } + + $this->result=array('nbofelement'=>$num); + + if ($outputmode) return $outarray; + return $out; + } + + /** * Return a HTML select string, built from an array of key+value. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice. @@ -5163,7 +5376,9 @@ class Form } } - $out.='global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return ''; - $out=''; + $out=''; $tmpplugin='select2'; $outdelayed="\n".' @@ -5267,51 +5485,48 @@ class Form url: "'.$url.'", dataType: \'json\', delay: 250, - data: function (searchTerm, pageNumber, context) { + data: function (params) { return { - q: searchTerm, // search term - page: pageNumber + q: params.term, // search term + page: params.page }; }, - results: function (remoteData, pageNumber, query) { - console.log(remoteData); - saveRemoteData = remoteData; + processResults: function (data) { + // parse the results into the format expected by Select2. + // since we are using custom formatting functions we do not need to alter the remote JSON data + //console.log(data); + saveRemoteData = data; /* format json result for select2 */ result = [] - $.each( remoteData, function( key, value ) { + $.each( data, function( key, value ) { result.push({id: key, text: value.text}); }); //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false} - return {results: result, more:false} - }, - /*processResults: function (data, page) { - // parse the results into the format expected by Select2. - // since we are using custom formatting functions we do not need to - // alter the remote JSON data - console.log(data); - return { - results: data.items - }; - },*/ + //console.log(result); + return {results: result, more: false} + }, cache: true }, - dropdownCssClass: "css-'.$htmlname.'", + language: select2arrayoflanguage, + containerCssClass: \':all:\', /* Line to add class or origin SELECT propagated to the new next_prev_filter set to add SQL criterias. + * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias. * * @param object $object Object to show. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link. * @param string $morehtml More html content to output just before the nav bar. * @param int $shownav Show Condition (navigation is shown if value is 1). - * @param string $fieldid Name of field id into database to use for select next and previous (we make the select max and min on this field). Use 'none' to disable next/prev. + * @param string $fieldid Name of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref. * @param string $morehtmlref More html to show after ref. * @param string $moreparam More param to add in nav link url. Must start with '&...'. @@ -5979,7 +6194,7 @@ class Form if ($shownav) { //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam"; - $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''),$fieldid,$nodbprefix); + $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix); $navurl = $_SERVER["PHP_SELF"]; // Special case for project/task page @@ -6442,7 +6657,7 @@ class Form */ function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array()) { - global $db,$conf,$langs; + global $db, $conf, $langs, $user; $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1'; $sql.= ' AND entity IN (0,'.getEntity('').')'; @@ -6453,13 +6668,14 @@ class Form if ($resql) { $out = ''; + if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); if (!empty($target)) { diff --git a/htdocs/core/class/html.formactions.class.php b/htdocs/core/class/html.formactions.class.php index 7d5bffb6e54..7db6ec3331a 100644 --- a/htdocs/core/class/html.formactions.class.php +++ b/htdocs/core/class/html.formactions.class.php @@ -249,16 +249,16 @@ class FormActions print $action->type; print ''; print ''.$label.''; - print ''.dol_print_date($action->datep,'dayhour'); + print ''.dol_print_date($action->datep, 'dayhour', 'tzuserrel'); if ($action->datef) { $tmpa=dol_getdate($action->datep); $tmpb=dol_getdate($action->datef); if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) { - if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($action->datef,'hour'); + if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($action->datef, 'hour', 'tzuserrel'); } - else print '-'.dol_print_date($action->datef,'dayhour'); + else print '-'.dol_print_date($action->datef, 'dayhour', 'tzuserrel'); } print ''; print ''; diff --git a/htdocs/core/class/html.formadmin.class.php b/htdocs/core/class/html.formadmin.class.php index e2a423e9ca4..fd0470c63f4 100644 --- a/htdocs/core/class/html.formadmin.class.php +++ b/htdocs/core/class/html.formadmin.class.php @@ -51,7 +51,7 @@ class FormAdmin * @param string $htmlname Name of HTML select * @param int $showauto Show 'auto' choice * @param array $filter Array of keys to exclude in list - * @param string $showempty 1=Add empty value or string to show + * @param string $showempty '1'=Add empty value or string to show * @param int $showwarning Show a warning if language is not complete * @param int $disabled Disable edit of select * @param string $morecss Add more css styles diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php index 7559179c87d..f105ef78263 100644 --- a/htdocs/core/class/html.formfile.class.php +++ b/htdocs/core/class/html.formfile.class.php @@ -34,289 +34,289 @@ */ class FormFile { - private $db; + private $db; - public $error; - public $numoffiles; - public $infofiles; // Used to return informations by function getDocumentsLink + public $error; + public $numoffiles; + public $infofiles; // Used to return informations by function getDocumentsLink - /** + /** * Constructor * * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - $this->numoffiles=0; - return 1; - } + */ + function __construct($db) + { + $this->db = $db; + $this->numoffiles=0; + return 1; + } - /** - * Show form to upload a new file + /** + * Show form to upload a new file * - * @param string $url Url - * @param string $title Title zone (Title or '' or 'none') - * @param int $addcancel 1=Add 'Cancel' button - * @param int $sectionid If upload must be done inside a particular ECM section - * @param int $perm Value of permission to allow upload - * @param int $size Length of input file area. Deprecated. - * @param Object $object Object to use (when attachment is done on an element) - * @param string $options Add an option column - * @param integer $useajax Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). 2 should never be used. - * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__' - * @param integer $linkfiles 1=Also add form to link files, 0=Do not show form to link files - * @param string $htmlname Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM) - * @param string $accept Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*') - * @return int <0 if KO, >0 if OK - */ - function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='') - { - global $conf,$langs, $hookmanager; - $hookmanager->initHooks(array('formfile')); + * @param string $url Url + * @param string $title Title zone (Title or '' or 'none') + * @param int $addcancel 1=Add 'Cancel' button + * @param int $sectionid If upload must be done inside a particular ECM section + * @param int $perm Value of permission to allow upload + * @param int $size Length of input file area. Deprecated. + * @param Object $object Object to use (when attachment is done on an element) + * @param string $options Add an option column + * @param integer $useajax Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). 2 should never be used. + * @param string $savingdocmask Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__' + * @param integer $linkfiles 1=Also add form to link files, 0=Do not show form to link files + * @param string $htmlname Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM) + * @param string $accept Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*') + * @return int <0 if KO, >0 if OK + */ + function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='') + { + global $conf,$langs, $hookmanager; + $hookmanager->initHooks(array('formfile')); - if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0; + if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0; if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2)) - { - // TODO: Check this works with 2 forms on same page - // TODO: Check this works with GED module, otherwise, force useajax to 0 - // TODO: This does not support option savingdocmask - // TODO: This break feature to upload links too - return $this->_formAjaxFileUpload($object); - } - else - { - //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed - if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { - return 1; - } + { + // TODO: Check this works with 2 forms on same page + // TODO: Check this works with GED module, otherwise, force useajax to 0 + // TODO: This does not support option savingdocmask + // TODO: This break feature to upload links too + return $this->_formAjaxFileUpload($object); + } + else + { + //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed + if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { + return 1; + } - $maxlength=$size; + $maxlength=$size; - $out = "\n\n\n"; + $out = "\n\n\n"; - if (empty($title)) $title=$langs->trans("AttachANewFile"); - if ($title != 'none') $out.=load_fiche_titre($title, null, null); + if (empty($title)) $title=$langs->trans("AttachANewFile"); + if ($title != 'none') $out.=load_fiche_titre($title, null, null); - $out .= '
    '; - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; - $out .= ''; - $out .= ''; + $out .= '
    '; + $out .= ''; - if (! empty($options)) $out .= ''; + if (! empty($options)) $out .= ''; - $out .= '"; + if (! empty($conf->global->MAIN_UPLOAD_DOC)) + { + if ($perm) + { + $langs->load('other'); + $out .= ' '; + $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1); + } + } + else + { + $out .= ' ('.$langs->trans("UploadDisabled").')'; + } + $out .= ""; - if ($savingdocmask) - { - $out .= ''; - if (! empty($options)) $out .= ''; - $out .= ''; + if (! empty($options)) $out .= ''; + $out .= ''; - $out .= ''; - } + $out .= ''; + $out .= ''; + } - $out .= "
    '.$options.''.$options.''; + $out .= ''; - $max=$conf->global->MAIN_UPLOAD_DOC; // En Kb - $maxphp=@ini_get('upload_max_filesize'); // En inconnu - if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1; - if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024; - if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024; - if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024; - // Now $max and $maxphp are in Kb - if ($maxphp > 0) $max=min($max,$maxphp); + $max=$conf->global->MAIN_UPLOAD_DOC; // En Kb + $maxphp=@ini_get('upload_max_filesize'); // En inconnu + if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1; + if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024; + if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024; + if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024; + // Now $max and $maxphp are in Kb + if ($maxphp > 0) $max=min($max,$maxphp); - if ($max > 0) - { - $out .= ''; - } + if ($max > 0) + { + $out .= ''; + } - $out .= 'global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple'); - $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); - $out .= (!empty($accept)?' accept="'.$accept.'"':' accept=""'); - $out .= '>'; - $out .= ' '; - $out .= 'global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); - $out .= '>'; + $out .= 'global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple'); + $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); + $out .= (!empty($accept)?' accept="'.$accept.'"':' accept=""'); + $out .= '>'; + $out .= ' '; + $out .= 'global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); + $out .= '>'; - if ($addcancel) - { - $out .= '   '; - $out .= ''; - } + if ($addcancel) + { + $out .= '   '; + $out .= ''; + } - if (! empty($conf->global->MAIN_UPLOAD_DOC)) - { - if ($perm) - { - $langs->load('other'); - $out .= ' '; - $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1); - } - } - else - { - $out .= ' ('.$langs->trans("UploadDisabled").')'; - } - $out .= "
    '.$options.''; + if ($savingdocmask) + { + $out .= '
    '.$options.''; $out .= ' '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName")); - $out .= '
    "; + $out .= ""; - $out .= '
    '; - if (empty($sectionid)) $out .= '
    '; + $out .= ''; + if (empty($sectionid)) $out .= '
    '; - $out .= "\n\n"; + $out .= "\n\n"; - if ($linkfiles) - { - $out .= "\n\n"; - $langs->load('link'); - $title = $langs->trans("LinkANewFile"); - $out .= load_fiche_titre($title, null, null); - $out .= '
    '; - $parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm); - $res = $hookmanager->executeHooks('formattachOptions',$parameters,$object); + $out .= '
    '; + $out .= '
    '; + if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= ' '; + $out .= ''; + $out .= '
    '; + $out .= '
    '; + if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= ' '; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= '
    '; + $out .= '
    '; + $out .= 'global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':''); + $out .= '>'; + $out .= '
    '; + $out .= '
    '; + $out .= '
    '; + $out .= '
    '; + $parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm); + $res = $hookmanager->executeHooks('formattachOptions',$parameters,$object); - $out .= "\n\n"; - } + $out .= "\n\n"; + } - if (empty($res)) - { - print '
    '; - print $out; - print '
    '; - } + if (empty($res)) + { + print '
    '; + print $out; + print '
    '; + } - print $hookmanager->resPrint; + print $hookmanager->resPrint; - return 1; - } - } + return 1; + } + } - /** - * Show the box with list of available documents for object - * - * @param string $modulepart propal, facture, facture_fourn, ... - * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. - * @param string $filedir Directory to scan - * @param string $urlsource Url of origin page (for return) - * @param int $genallowed Generation is allowed (1/0 or array of formats) - * @param int $delallowed Remove is allowed (1/0) - * @param string $modelselected Model to preselect by default - * @param integer $allowgenifempty Show warning if no model activated - * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) - * @param int $iconPDF Show only PDF icon with link (1/0) - * @param int $notused Not used - * @param integer $noform Do not output html form tags - * @param string $param More param on http links - * @param string $title Title to show on top of form - * @param string $buttonlabel Label on submit button - * @param string $codelang Default language code to use on lang combo box if multilang is enabled - * @return int <0 if KO, number of shown files if OK - * @deprecated Use print xxx->showdocuments() instead. - */ - function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='') - { - $this->numoffiles=0; - print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang); - return $this->numoffiles; - } + /** + * Show the box with list of available documents for object + * + * @param string $modulepart propal, facture, facture_fourn, ... + * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. + * @param string $filedir Directory to scan + * @param string $urlsource Url of origin page (for return) + * @param int $genallowed Generation is allowed (1/0 or array of formats) + * @param int $delallowed Remove is allowed (1/0) + * @param string $modelselected Model to preselect by default + * @param integer $allowgenifempty Show warning if no model activated + * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) + * @param int $iconPDF Show only PDF icon with link (1/0) + * @param int $notused Not used + * @param integer $noform Do not output html form tags + * @param string $param More param on http links + * @param string $title Title to show on top of form + * @param string $buttonlabel Label on submit button + * @param string $codelang Default language code to use on lang combo box if multilang is enabled + * @return int <0 if KO, number of shown files if OK + * @deprecated Use print xxx->showdocuments() instead. + */ + function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='') + { + $this->numoffiles=0; + print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang); + return $this->numoffiles; + } - /** - * Return a string to show the box with list of available documents for object. - * This also set the property $this->numoffiles - * - * @param string $modulepart Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...) - * @param string $modulesubdir Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. - * @param string $filedir Directory to scan - * @param string $urlsource Url of origin page (for return) - * @param int $genallowed Generation is allowed (1/0 or array list of templates) - * @param int $delallowed Remove is allowed (1/0) - * @param string $modelselected Model to preselect by default - * @param integer $allowgenifempty Allow generation even if list of template ($genallowed) is empty (show however a warning) - * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) - * @param int $iconPDF Deprecated, see getDocumentsLink - * @param int $notused Not used - * @param integer $noform Do not output html form tags - * @param string $param More param on http links - * @param string $title Title to show on top of form - * @param string $buttonlabel Label on submit button - * @param string $codelang Default language code to use on lang combo box if multilang is enabled - * @param string $morepicto Add more HTML content into cell with picto - * @param Object $object Object when method is called from an object card. - * @return string Output string with HTML array of documents (might be empty string) - */ - function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null) - { + /** + * Return a string to show the box with list of available documents for object. + * This also set the property $this->numoffiles + * + * @param string $modulepart Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...) + * @param string $modulesubdir Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. + * @param string $filedir Directory to scan + * @param string $urlsource Url of origin page (for return) + * @param int $genallowed Generation is allowed (1/0 or array list of templates) + * @param int $delallowed Remove is allowed (1/0) + * @param string $modelselected Model to preselect by default + * @param integer $allowgenifempty Allow generation even if list of template ($genallowed) is empty (show however a warning) + * @param integer $forcenomultilang Do not show language option (even if MAIN_MULTILANGS defined) + * @param int $iconPDF Deprecated, see getDocumentsLink + * @param int $notused Not used + * @param integer $noform Do not output html form tags + * @param string $param More param on http links + * @param string $title Title to show on top of form + * @param string $buttonlabel Label on submit button + * @param string $codelang Default language code to use on lang combo box if multilang is enabled + * @param string $morepicto Add more HTML content into cell with picto + * @param Object $object Object when method is called from an object card. + * @return string Output string with HTML array of documents (might be empty string) + */ + function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null) + { // Deprecation warning if (0 !== $iconPDF) { dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING); } - global $langs, $conf, $user, $hookmanager; - global $form, $bc; + global $langs, $conf, $user, $hookmanager; + global $form, $bc; - if (! is_object($form)) $form=new Form($this->db); + if (! is_object($form)) $form=new Form($this->db); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - // For backward compatibility - if (! empty($iconPDF)) { - return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir); - } + // For backward compatibility + if (! empty($iconPDF)) { + return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir); + } - $printer=0; - if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport'))) // The direct print feature is implemented only for such elements - { - $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false; - } + $printer=0; + if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport'))) // The direct print feature is implemented only for such elements + { + $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false; + } - $hookmanager->initHooks(array('formfile')); - $forname='builddoc'; - $out=''; + $hookmanager->initHooks(array('formfile')); + $forname='builddoc'; + $out=''; - $headershown=0; - $showempty=0; - $i=0; + $headershown=0; + $showempty=0; + $i=0; - $out.= "\n".''."\n"; - //print 'filedir='.$filedir; + $out.= "\n".''."\n"; + //print 'filedir='.$filedir; - if (preg_match('/massfilesarea_/', $modulepart)) - { - $out.='

    '."\n"; + if (preg_match('/massfilesarea_/', $modulepart)) + { + $out.='

    '."\n"; $title=$langs->trans("MassFilesArea").' ('.$langs->trans("Hide").')'; $title.=''; - } + } - $titletoshow=$langs->trans("Documents"); - if (! empty($title)) $titletoshow=$title; + $titletoshow=$langs->trans("Documents"); + if (! empty($title)) $titletoshow=$title; - // Show table - if ($genallowed) - { - $modellist=array(); + // Show table + if ($genallowed) + { + $modellist=array(); - if ($modulepart == 'company') - { - $showempty=1; - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php'; - $modellist=ModeleThirdPartyDoc::liste_modeles($this->db); - } - } - else if ($modulepart == 'propal') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php'; - $modellist=ModelePDFPropales::liste_modeles($this->db); - } - } + if ($modulepart == 'company') + { + $showempty=1; + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php'; + $modellist=ModeleThirdPartyDoc::liste_modeles($this->db); + } + } + else if ($modulepart == 'propal') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php'; + $modellist=ModelePDFPropales::liste_modeles($this->db); + } + } else if ($modulepart == 'supplier_proposal') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php'; - $modellist=ModelePDFSupplierProposal::liste_modeles($this->db); - } - } - else if ($modulepart == 'commande') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; - $modellist=ModelePDFCommandes::liste_modeles($this->db); - } - } - elseif ($modulepart == 'expedition') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; - $modellist=ModelePDFExpedition::liste_modeles($this->db); - } - } - elseif ($modulepart == 'livraison') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php'; - $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db); - } - } - else if ($modulepart == 'ficheinter') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php'; - $modellist=ModelePDFFicheinter::liste_modeles($this->db); - } - } - elseif ($modulepart == 'facture') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; - $modellist=ModelePDFFactures::liste_modeles($this->db); - } - } - elseif ($modulepart == 'contract') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; - $modellist=ModelePDFContract::liste_modeles($this->db); - } - } - elseif ($modulepart == 'project') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php'; - $modellist=ModelePDFProjects::liste_modeles($this->db); - } - } - elseif ($modulepart == 'project_task') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php'; - $modellist=ModelePDFTask::liste_modeles($this->db); - } - } - elseif ($modulepart == 'product') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php'; - $modellist=ModelePDFProduct::liste_modeles($this->db); - } - } - elseif ($modulepart == 'export') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; - $modellist=ModeleExports::liste_modeles($this->db); - } - } - else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php'; - $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db); - } - } - else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; - $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db); - } - } + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php'; + $modellist=ModelePDFSupplierProposal::liste_modeles($this->db); + } + } + else if ($modulepart == 'commande') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php'; + $modellist=ModelePDFCommandes::liste_modeles($this->db); + } + } + elseif ($modulepart == 'expedition') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php'; + $modellist=ModelePDFExpedition::liste_modeles($this->db); + } + } + elseif ($modulepart == 'livraison') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php'; + $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db); + } + } + else if ($modulepart == 'ficheinter') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php'; + $modellist=ModelePDFFicheinter::liste_modeles($this->db); + } + } + elseif ($modulepart == 'facture') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; + $modellist=ModelePDFFactures::liste_modeles($this->db); + } + } + elseif ($modulepart == 'contract') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; + $modellist=ModelePDFContract::liste_modeles($this->db); + } + } + elseif ($modulepart == 'project') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php'; + $modellist=ModelePDFProjects::liste_modeles($this->db); + } + } + elseif ($modulepart == 'project_task') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php'; + $modellist=ModelePDFTask::liste_modeles($this->db); + } + } + elseif ($modulepart == 'product') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php'; + $modellist=ModelePDFProduct::liste_modeles($this->db); + } + } + elseif ($modulepart == 'export') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; + $modellist=ModeleExports::liste_modeles($this->db); + } + } + else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php'; + $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db); + } + } + else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php'; + $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db); + } + } else if ($modulepart == 'supplier_payment') { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php'; - $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db); - } - } - else if ($modulepart == 'remisecheque') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php'; - $modellist=ModeleChequeReceipts::liste_modeles($this->db); - } - } - elseif ($modulepart == 'donation') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php'; - $modellist=ModeleDon::liste_modeles($this->db); - } - } - elseif ($modulepart == 'member') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php'; - $modellist=ModelePDFCards::liste_modeles($this->db); - } - } - elseif ($modulepart == 'agenda') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php'; - $modellist=ModeleAction::liste_modeles($this->db); - } - } - else if ($modulepart == 'expensereport') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php'; - $modellist=ModeleExpenseReport::liste_modeles($this->db); - } - } - else if ($modulepart == 'unpaid') - { - $modellist=''; - } - elseif ($modulepart == 'user') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php'; - $modellist=ModelePDFUser::liste_modeles($this->db); - } - } - elseif ($modulepart == 'usergroup') - { - if (is_array($genallowed)) $modellist=$genallowed; - else - { - include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php'; - $modellist=ModelePDFUserGroup::liste_modeles($this->db); - } - } - else //if ($modulepart != 'agenda') - { - // For normalized standard modules - $file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); - if (file_exists($file)) - { - $res=include_once $file; - } - // For normalized external modules - else + if (is_array($genallowed)) $modellist=$genallowed; + else { - $file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); - $res=include_once $file; - } - $class='Modele'.ucfirst($modulepart); - if (class_exists($class)) - { - $modellist=call_user_func($class.'::liste_modeles',$this->db); - } - else - { - dol_print_error($this->db,'Bad value for modulepart'); - return -1; - } - } + include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php'; + $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db); + } + } + else if ($modulepart == 'remisecheque') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php'; + $modellist=ModeleChequeReceipts::liste_modeles($this->db); + } + } + elseif ($modulepart == 'donation') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php'; + $modellist=ModeleDon::liste_modeles($this->db); + } + } + elseif ($modulepart == 'member') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php'; + $modellist=ModelePDFCards::liste_modeles($this->db); + } + } + elseif ($modulepart == 'agenda') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php'; + $modellist=ModeleAction::liste_modeles($this->db); + } + } + else if ($modulepart == 'expensereport') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php'; + $modellist=ModeleExpenseReport::liste_modeles($this->db); + } + } + else if ($modulepart == 'unpaid') + { + $modellist=''; + } + elseif ($modulepart == 'user') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php'; + $modellist=ModelePDFUser::liste_modeles($this->db); + } + } + elseif ($modulepart == 'usergroup') + { + if (is_array($genallowed)) $modellist=$genallowed; + else + { + include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php'; + $modellist=ModelePDFUserGroup::liste_modeles($this->db); + } + } + else //if ($modulepart != 'agenda') + { + // For normalized standard modules + $file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); + if (file_exists($file)) + { + $res=include_once $file; + } + // For normalized external modules + else + { + $file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0); + $res=include_once $file; + } + $class='Modele'.ucfirst($modulepart); + if (class_exists($class)) + { + $modellist=call_user_func($class.'::liste_modeles',$this->db); + } + else + { + dol_print_error($this->db,'Bad value for modulepart'); + return -1; + } + } - // Set headershown to avoit to have table opened a second time later - $headershown=1; + // Set headershown to avoit to have table opened a second time later + $headershown=1; - $buttonlabeltoshow=$buttonlabel; - if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate'); + $buttonlabeltoshow=$buttonlabel; + if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate'); - if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form'; // So we switch to form after a generation - if (empty($noform)) $out.= '
    '; - $out.= ''; - $out.= ''; + if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form'; // So we switch to form after a generation + if (empty($noform)) $out.= ''; + $out.= ''; + $out.= ''; - $out.= load_fiche_titre($titletoshow, '', ''); - $out.= '
    '; - $out.= ''; + $out.= load_fiche_titre($titletoshow, '', ''); + $out.= '
    '; + $out.= '
    '; - $out.= ''; + $out.= ''; - $addcolumforpicto=($delallowed || $printer || $morepicto); - $out.= ''; + // Button + $genbutton = 'dol_no_mouse_hover) && $modulepart != 'unpaid') + { + $langs->load("errors"); + $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); + } + if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton=''; + if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton=''; + $out.= $genbutton; + $out.= ''; - if (!empty($hookmanager->hooks['formfile'])) - { - foreach($hookmanager->hooks['formfile'] as $module) - { - if (method_exists($module, 'formBuilddocLineOptions')) $out .= ''; - } - } - $out.= ''; + if (!empty($hookmanager->hooks['formfile'])) + { + foreach($hookmanager->hooks['formfile'] as $module) + { + if (method_exists($module, 'formBuilddocLineOptions')) $out .= ''; + } + } + $out.= ''; - // Execute hooks - $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart); - if (is_object($hookmanager)) - { - $reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']); - $out.= $hookmanager->resPrint; - } + // Execute hooks + $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart); + if (is_object($hookmanager)) + { + $reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']); + $out.= $hookmanager->resPrint; + } - } + } - // Get list of files - if (! empty($filedir)) - { - $file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC); + // Get list of files + if (! empty($filedir)) + { + $file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC); - $link_list = array(); - if (is_object($object)) - { - require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; - $link = new Link($this->db); - $sortfield = $sortorder = null; - $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder); - } + $link_list = array(); + if (is_object($object)) + { + require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; + $link = new Link($this->db); + $sortfield = $sortorder = null; + $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder); + } - $out.= ''."\n"; + $out.= ''."\n"; - // Show title of array if not already shown - if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown) - { - $headershown=1; - $out.= '
    '.$titletoshow.'
    '."\n"; - $out.= '
    '; - $out.= '
    '; + $addcolumforpicto=($delallowed || $printer || $morepicto); + $out.= ''; - // Model - if (! empty($modellist)) - { - $out.= ''.$langs->trans('Model').' '; - if (is_array($modellist) && count($modellist) == 1) // If there is only one element - { - $arraykeys=array_keys($modellist); - $modelselected=$arraykeys[0]; - } - $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - $out.= ajax_combobox('model'); - } - else - { - $out.= '
    '.$langs->trans("Files").'
    '; - } + // Model + if (! empty($modellist)) + { + $out.= ''.$langs->trans('Model').' '; + if (is_array($modellist) && count($modellist) == 1) // If there is only one element + { + $arraykeys=array_keys($modellist); + $modelselected=$arraykeys[0]; + } + $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out.= ajax_combobox('model'); + } + else + { + $out.= '
    '.$langs->trans("Files").'
    '; + } - // Language code (if multilang) - if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; - $formadmin=new FormAdmin($this->db); - $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); - $morecss='maxwidth150'; - if (! empty($conf->browser->phone)) $morecss='maxwidth100'; - $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss); - } - else - { - $out.= ' '; - } + // Language code (if multilang) + if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin=new FormAdmin($this->db); + $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); + $morecss='maxwidth150'; + if (! empty($conf->browser->phone)) $morecss='maxwidth100'; + $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss); + } + else + { + $out.= ' '; + } - // Button - $genbutton = 'dol_no_mouse_hover) && $modulepart != 'unpaid') - { - $langs->load("errors"); - $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated")); - } - if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton=''; - if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton=''; - $out.= $genbutton; - $out.= '
    '."\n"; - } + // Show title of array if not already shown + if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown) + { + $headershown=1; + $out.= '
    '.$titletoshow.'
    '."\n"; + $out.= '
    '; + $out.= '
    '."\n"; + } - // Loop on each file found + // Loop on each file found if (is_array($file_list)) { foreach($file_list as $file) { // Define relative path for download link (depends on module) $relativepath=$file["name"]; // Cas general - if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"]; // Cas propal, facture... + if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"]; // Cas propal, facture... if ($modulepart == 'export') $relativepath = $file["name"]; // Other case $out.= ''; @@ -713,8 +713,8 @@ class FormFile // Show file name with link to download $out.= ''; - } + $out.=''; + } - if (is_object($hookmanager)) - { - $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath); - $res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file); - if (empty($res)) - { - $out .= $hookmanager->resPrint; // Complete line - $out.= ''; - } - else $out = $hookmanager->resPrint; // Replace line - } + if (is_object($hookmanager)) + { + $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath); + $res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file); + if (empty($res)) + { + $out .= $hookmanager->resPrint; // Complete line + $out.= ''; + } + else $out = $hookmanager->resPrint; // Replace line + } } - $this->numoffiles++; - } - // Loop on each file found - if (is_array($link_list)) - { - $colspan=2; + $this->numoffiles++; + } + // Loop on each file found + if (is_array($link_list)) + { + $colspan=2; - foreach($link_list as $file) - { - $out.=''; - $out.=''; - $out.=''; - if ($delallowed || $printer || $morepicto) $out.=''; - $out.=''."\n"; - } - $this->numoffiles++; - } + foreach($link_list as $file) + { + $out.=''; + $out.=''; + $out.=''; + if ($delallowed || $printer || $morepicto) $out.=''; + $out.=''."\n"; + } + $this->numoffiles++; + } if (count($file_list) == 0 && count($link_list) == 0 && $headershown) - { - $out.=''."\n"; - } + { + $out.=''."\n"; + } - } + } - if ($headershown) - { - // Affiche pied du tableau - $out.= "
    '; - $tmp = $this->showPreview($file,$modulepart,$relativepath,0,$param); - $out.= ($tmp?$tmp.' ':''); + $tmp = $this->showPreview($file,$modulepart,$relativepath,0,$param); + $out.= ($tmp?$tmp.' ':''); $out.= 'trans("PrintFile", $relativepath),'printer.png').''; + $out.= ' '.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').''; } if ($morepicto) { $morepicto=preg_replace('/__FILENAMEURLENCODED__/',urlencode($relativepath),$morepicto); - $out.=$morepicto; + $out.=$morepicto; } - $out.='
    '; - $out.=''; - $out.=$file->label; - $out.=''; - $out.=''; - $out.=dol_print_date($file->datea,'dayhour'); - $out.='
    '; + $out.=''; + $out.=$file->label; + $out.=''; + $out.=''; + $out.=dol_print_date($file->datea,'dayhour'); + $out.='
    '.$langs->trans("None").'
    '.$langs->trans("None").'
    \n"; - $out.= "
    \n"; - if ($genallowed) - { - if (empty($noform)) $out.= '
    '."\n"; - } - } - $out.= ''."\n"; - //return ($i?$i:$headershown); - return $out; - } + if ($headershown) + { + // Affiche pied du tableau + $out.= "\n"; + $out.= "
    \n"; + if ($genallowed) + { + if (empty($noform)) $out.= ''."\n"; + } + } + $out.= ''."\n"; + //return ($i?$i:$headershown); + return $out; + } - /** - * Show a Document icon with link(s) - * You may want to call this into a div like this: - * print '
    '.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'
    '; - * - * @param string $modulepart propal, facture, facture_fourn, ... - * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. - * @param string $filedir Full path to directory to scan - * @param string $filter Filter filenames on this regex string (Example: '\.pdf$') - * @return string Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles - */ - function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='') - { - global $conf, $langs; + /** + * Show a Document icon with link(s) + * You may want to call this into a div like this: + * print '
    '.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'
    '; + * + * @param string $modulepart propal, facture, facture_fourn, ... + * @param string $modulesubdir Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module. + * @param string $filedir Full path to directory to scan + * @param string $filter Filter filenames on this regex string (Example: '\.pdf$') + * @return string Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles + */ + function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='') + { + global $conf, $langs; - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $out=''; - $this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array()); + $out=''; + $this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array()); - $filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+'; + $filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+'; - $file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files) + $file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files) - // For ajax treatment + // For ajax treatment $out.= ''."\n"; - if (! empty($file_list)) - { - $out='
    '; - } - else - { - // TODO Add link to regenerate doc ? - //$out.= '
    '.img_picto('', 'refresh').'
    '."\n"; - } + } + else + { + // TODO Add link to regenerate doc ? + //$out.= '
    '.img_picto('', 'refresh').'
    '."\n"; + } - return $out; - } + return $out; + } - /** - * Show list of documents in $filearray (may be they are all in same directory but may not) - * This also sync database if $upload_dir is defined. - * - * @param array $filearray Array of files loaded by dol_dir_list('files') function before calling this. - * @param Object $object Object on which document is linked to. - * @param string $modulepart Value for modulepart used by download or viewimage wrapper. - * @param string $param Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd) - * @param int $forcedownload Force to open dialog box "Save As" when clicking on file. - * @param string $relativepath Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT. - * @param int $permonobject Permission on object (so permission to delete or crop document) - * @param int $useinecm Change output for use in ecm module - * @param string $textifempty Text to show if filearray is empty ('NoFileFound' if not defined) - * @param int $maxlength Maximum length of file name shown. - * @param string $title Title before list - * @param string $url Full url to use for click links ('' = autodetect) + /** + * Show list of documents in $filearray (may be they are all in same directory but may not) + * This also sync database if $upload_dir is defined. + * + * @param array $filearray Array of files loaded by dol_dir_list('files') function before calling this. + * @param Object $object Object on which document is linked to. + * @param string $modulepart Value for modulepart used by download or viewimage wrapper. + * @param string $param Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd) + * @param int $forcedownload Force to open dialog box "Save As" when clicking on file. + * @param string $relativepath Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT. + * @param int $permonobject Permission on object (so permission to delete or crop document) + * @param int $useinecm Change output for use in ecm module + * @param string $textifempty Text to show if filearray is empty ('NoFileFound' if not defined) + * @param int $maxlength Maximum length of file name shown. + * @param string $title Title before list + * @param string $url Full url to use for click links ('' = autodetect) * @param int $showrelpart 0=Show only filename (default), 1=Show first level 1 dir * @param int $permtoeditline Permission to edit document line (You must provide a value, -1 is deprecated and must not be used any more) - * @param string $upload_dir Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this if you want to complete file data with database indexes. - * @param string $sortfield Sort field ('name', 'size', 'position', ...) - * @param string $sortorder Sort order ('ASC' or 'DESC') - * @param int $disablemove 1=Disable move button, 0=Position move is possible. - * @param int $addfilterfields Add line with filters - * @return int <0 if KO, nb of files shown if OK - */ + * @param string $upload_dir Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this if you want to complete file data with database indexes. + * @param string $sortfield Sort field ('name', 'size', 'position', ...) + * @param string $sortorder Sort order ('ASC' or 'DESC') + * @param int $disablemove 1=Disable move button, 0=Position move is possible. + * @param int $addfilterfields Add line with filters + * @return int <0 if KO, nb of files shown if OK + */ function list_of_documents($filearray,$object,$modulepart,$param='',$forcedownload=0,$relativepath='',$permonobject=1,$useinecm=0,$textifempty='',$maxlength=0,$title='',$url='', $showrelpart=0, $permtoeditline=-1,$upload_dir='',$sortfield='',$sortorder='ASC', $disablemove=1, $addfilterfields=0) { global $user, $conf, $langs, $hookmanager; @@ -937,21 +937,21 @@ class FormFile // Define relative path used to store the file if (empty($relativepath)) { - $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/'; - if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath - if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.'; + $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/'; + if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath + if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.'; } // For backward compatiblity, we detect file is stored into an old path if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $file['level1name'] == 'photos') { - $relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/'; + $relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/'; } // Defined relative dir to DOL_DATA_ROOT $relativedir = ''; if ($upload_dir) { - $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); - $relativedir = preg_replace('/^[\\/]/','',$relativedir); + $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir); + $relativedir = preg_replace('/^[\\/]/','',$relativedir); } $hookmanager->initHooks(array('formfile')); @@ -981,17 +981,17 @@ class FormFile if ($permtoeditline < 0) // Old behaviour for backward compatibility. New feature should call method with value 0 or 1 { - $permtoeditline=0; - if (in_array($modulepart, array('product','produit','service'))) - { - if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1; - if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1; - } + $permtoeditline=0; + if (in_array($modulepart, array('product','produit','service'))) + { + if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1; + if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1; + } } if (empty($conf->global->MAIN_UPLOAD_DOC)) { - $permtoeditline=0; - $permonobject=0; + $permtoeditline=0; + $permonobject=0; } // Show list of existing files @@ -1001,10 +1001,10 @@ class FormFile print ''."\n"; if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline) { - print '
    '; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; } print '
    '; @@ -1038,11 +1038,11 @@ class FormFile /*var_dump($sortfield); var_dump($sortorder);*/ - if ($sortfield && $sortorder) - { - $filearray=dol_sort_array($filearray, $sortfield, $sortorder); - } - //var_dump($filearray); + if ($sortfield && $sortorder) + { + $filearray=dol_sort_array($filearray, $sortfield, $sortorder); + } + //var_dump($filearray); } $nboffiles=count($filearray); @@ -1059,9 +1059,9 @@ class FormFile $editline=0; $nboflines++; - print ''."\n"; - // Do we have entry into database ? - print ''."\n"; + print ''."\n"; + // Do we have entry into database ? + print ''."\n"; print ''; print ''; @@ -1081,15 +1081,15 @@ class FormFile //print dol_trunc($file['name'],$maxlength,'middle'); if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile'))) { - print ''; - print ''; - print ''; - $editline=1; + print ''; + print ''; + print ''; + $editline=1; } else { - print $file['name']; - print ''; + print $file['name']; + print ''; } print "\n"; @@ -1105,13 +1105,13 @@ class FormFile print ''; if (image_format_supported($file['name']) > 0) { - $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original - if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension - //print $file['path'].'/'.$minifile.'
    '; + $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original + if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_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']), 0, '&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 ''; + $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 0, '&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 ''; print ''; print ''; } @@ -1120,77 +1120,77 @@ class FormFile } if (! $editline) { - // Delete or view link - // ($param must start with &) - print ''; - if ($useinecm) - { - print ''.img_view('default', 0, 'class="paddingrightonly"').''; - } - else - { - $newmodulepart=$modulepart; - if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; + // Delete or view link + // ($param must start with &) + print ''; + if ($useinecm) + { + print ''.img_view('default', 0, 'class="paddingrightonly"').''; + } + else + { + $newmodulepart=$modulepart; + if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; - $disablecrop=1; - if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0; + $disablecrop=1; + if (in_array($modulepart, array('product','produit','service','expensereport','holiday','project','user'))) $disablecrop=0; - if (! $disablecrop && image_format_supported($file['name']) > 0) - { - if ($permtoeditline) - { - // Link to resize - print ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).''; - } - } + if (! $disablecrop && image_format_supported($file['name']) > 0) + { + if ($permtoeditline) + { + // Link to resize + print ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','class="paddingrightonly"',1).''; + } + } - if ($permtoeditline) - { - print ''.img_edit('default',0,'class="paddingrightonly"').''; - } - } - if ($permonobject) - { - /* + if ($permtoeditline) + { + print ''.img_edit('default',0,'class="paddingrightonly"').''; + } + } + if ($permonobject) + { + /* if ($file['level1name'] <> $object->id) $filepath=$file['level1name'].'/'.$file['name']; else $filepath=$file['name']; */ - $useajax=1; - if (! empty($conf->dol_use_jmobile)) $useajax=0; - if (empty($conf->use_javascript_ajax)) $useajax=0; - if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0; + $useajax=1; + if (! empty($conf->dol_use_jmobile)) $useajax=0; + if (empty($conf->use_javascript_ajax)) $useajax=0; + if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0; - print ''.img_delete().''; - } - print ""; + print ''.img_delete().''; + } + print ""; - if (empty($disablemove)) - { - if ($nboffiles > 1 && empty($conf->browser->phone)) { - print ''; - if ($i > 0) { - print 'id.'">'.img_up('default',0,'imgupforline').''; - } - if ($i < $nboffiles-1) { - print 'id.'">'.img_down('default',0,'imgdownforline').''; - } - print ''; - } - else { - print 'browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>'; - print ''; - } + if (empty($disablemove)) + { + if ($nboffiles > 1 && empty($conf->browser->phone)) { + print ''; + if ($i > 0) { + print 'id.'">'.img_up('default',0,'imgupforline').''; + } + if ($i < $nboffiles-1) { + print 'id.'">'.img_down('default',0,'imgdownforline').''; + } + print ''; + } + else { + print 'browser->phone) && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>'; + print ''; + } } } else { - print ''; - print ''; - print ''; - print ''; - if (empty($disablemove)) print ''; + print ''; + print ''; + print ''; + print ''; + if (empty($disablemove)) print ''; } print "\n"; @@ -1199,8 +1199,8 @@ class FormFile } if ($nboffiles == 0) { - $colspan=(empty($useinecm)?'5':'5'); - if (empty($disablemove)) $colspan++; + $colspan=(empty($useinecm)?'5':'5'); + if (empty($disablemove)) $colspan++; print ''; if (empty($textifempty)) print $langs->trans("NoFileFound"); else print $textifempty; @@ -1211,14 +1211,14 @@ class FormFile if (! $editline && $nboflines > 1) { if (! empty($conf->use_javascript_ajax) && $permtoeditline) { - $table_element_line = 'ecm_files'; - include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + $table_element_line = 'ecm_files'; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } } if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline) { - print ''; + print ''; } return $nboffiles; @@ -1226,459 +1226,459 @@ class FormFile } - /** - * Show list of documents in a directory - * - * @param string $upload_dir Directory that was scanned - * @param array $filearray Array of files loaded by dol_dir_list function before calling this function - * @param string $modulepart Value for modulepart used by download wrapper - * @param string $param Parameters on sort links - * @param int $forcedownload Force to open dialog box "Save As" when clicking on file - * @param string $relativepath Relative path of docs (autodefined if not provided) - * @param int $permtodelete Permission to delete - * @param int $useinecm Change output for use in ecm module - * @param int $textifempty Text to show if filearray is empty - * @param int $maxlength Maximum length of file name shown - * @param string $url Full url to use for click links ('' = autodetect) - * @param int $addfilterfields Add line with filters - * @return int <0 if KO, nb of files shown if OK - */ - function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='',$addfilterfields=0) - { - global $user, $conf, $langs, $form; - global $bc; - global $sortfield, $sortorder; + /** + * Show list of documents in a directory + * + * @param string $upload_dir Directory that was scanned + * @param array $filearray Array of files loaded by dol_dir_list function before calling this function + * @param string $modulepart Value for modulepart used by download wrapper + * @param string $param Parameters on sort links + * @param int $forcedownload Force to open dialog box "Save As" when clicking on file + * @param string $relativepath Relative path of docs (autodefined if not provided) + * @param int $permtodelete Permission to delete + * @param int $useinecm Change output for use in ecm module + * @param int $textifempty Text to show if filearray is empty + * @param int $maxlength Maximum length of file name shown + * @param string $url Full url to use for click links ('' = autodetect) + * @param int $addfilterfields Add line with filters + * @return int <0 if KO, nb of files shown if OK + */ + function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='',$addfilterfields=0) + { + global $user, $conf, $langs, $form; + global $bc; + global $sortfield, $sortorder; global $search_doc_ref; - dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart); + dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart); - // Show list of documents - if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles")); - if (empty($url)) $url=$_SERVER["PHP_SELF"]; + // Show list of documents + if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles")); + if (empty($url)) $url=$_SERVER["PHP_SELF"]; - if (! empty($addfilterfields)) - { - print '
    '; - print ''; - } + if (! empty($addfilterfields)) + { + print ''; + print ''; + } print '
    '; - print ''."\n"; + print '
    '."\n"; - if (! empty($addfilterfields)) - { - print ''; - print ''; - print ''; - print ''; - print ''; + if (! empty($addfilterfields)) + { + print ''; + print ''; + print ''; + print ''; + print ''; // Action column print ''; - print "\n"; - } + print "\n"; + } - print ''; - $sortref="fullname"; - if ($modulepart == 'invoice_supplier') $sortref='level1name'; - print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre('','',''); - print ''."\n"; + print ''; + $sortref="fullname"; + if ($modulepart == 'invoice_supplier') $sortref='level1name'; + print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre('','',''); + print ''."\n"; - // To show ref or specific information according to view to show (defined by $module) - if ($modulepart == 'company') - { - include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $object_instance=new Societe($this->db); - } - else if ($modulepart == 'invoice') - { - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $object_instance=new Facture($this->db); - } - else if ($modulepart == 'invoice_supplier') - { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - $object_instance=new FactureFournisseur($this->db); - } - else if ($modulepart == 'propal') - { - include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $object_instance=new Propal($this->db); - } - else if ($modulepart == 'supplier_proposal') - { - include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; - $object_instance=new SupplierProposal($this->db); - } - else if ($modulepart == 'order') - { - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $object_instance=new Commande($this->db); - } - else if ($modulepart == 'order_supplier') - { - include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; - $object_instance=new CommandeFournisseur($this->db); - } - else if ($modulepart == 'contract') - { - include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; - $object_instance=new Contrat($this->db); - } - else if ($modulepart == 'product') - { - include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $object_instance=new Product($this->db); - } - else if ($modulepart == 'tax') - { - include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; - $object_instance=new ChargeSociales($this->db); - } - else if ($modulepart == 'project') - { - include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - $object_instance=new Project($this->db); - } - else if ($modulepart == 'fichinter') - { - include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; - $object_instance=new Fichinter($this->db); - } - else if ($modulepart == 'user') - { - include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - $object_instance=new User($this->db); - } - else if ($modulepart == 'expensereport') - { - include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; - $object_instance=new ExpenseReport($this->db); - } + // To show ref or specific information according to view to show (defined by $module) + if ($modulepart == 'company') + { + include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + $object_instance=new Societe($this->db); + } + else if ($modulepart == 'invoice') + { + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $object_instance=new Facture($this->db); + } + else if ($modulepart == 'invoice_supplier') + { + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; + $object_instance=new FactureFournisseur($this->db); + } + else if ($modulepart == 'propal') + { + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + $object_instance=new Propal($this->db); + } + else if ($modulepart == 'supplier_proposal') + { + include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; + $object_instance=new SupplierProposal($this->db); + } + else if ($modulepart == 'order') + { + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + $object_instance=new Commande($this->db); + } + else if ($modulepart == 'order_supplier') + { + include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; + $object_instance=new CommandeFournisseur($this->db); + } + else if ($modulepart == 'contract') + { + include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; + $object_instance=new Contrat($this->db); + } + else if ($modulepart == 'product') + { + include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + $object_instance=new Product($this->db); + } + else if ($modulepart == 'tax') + { + include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; + $object_instance=new ChargeSociales($this->db); + } + else if ($modulepart == 'project') + { + include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + $object_instance=new Project($this->db); + } + else if ($modulepart == 'fichinter') + { + include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; + $object_instance=new Fichinter($this->db); + } + else if ($modulepart == 'user') + { + include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + $object_instance=new User($this->db); + } + else if ($modulepart == 'expensereport') + { + include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $object_instance=new ExpenseReport($this->db); + } - $var=true; - foreach($filearray as $key => $file) - { - if (!is_dir($file['name']) - && $file['name'] != '.' - && $file['name'] != '..' - && $file['name'] != 'CVS' - && ! preg_match('/\.meta$/i',$file['name'])) - { - // Define relative path used to store the file - $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']); + $var=true; + foreach($filearray as $key => $file) + { + if (!is_dir($file['name']) + && $file['name'] != '.' + && $file['name'] != '..' + && $file['name'] != 'CVS' + && ! preg_match('/\.meta$/i',$file['name'])) + { + // Define relative path used to store the file + $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']); - //var_dump($file); - $id=0; $ref=''; $label=''; + //var_dump($file); + $id=0; $ref=''; $label=''; - // To show ref or specific information according to view to show (defined by $module) - if ($modulepart == 'company') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'invoice') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } } // $ref may be also id with old supplier invoices - if ($modulepart == 'propal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + // To show ref or specific information according to view to show (defined by $module) + if ($modulepart == 'company') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'invoice') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } } // $ref may be also id with old supplier invoices + if ($modulepart == 'propal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'order') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'order_supplier') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'contract') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'product') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } - if ($modulepart == 'project') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} - if ($modulepart == 'fichinter') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} - if ($modulepart == 'user') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} - if ($modulepart == 'expensereport') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'order') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'order_supplier') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'contract') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'product') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); } + if ($modulepart == 'project') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'fichinter') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'user') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} + if ($modulepart == 'expensereport') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:'');} - if (! $id && ! $ref) continue; - $found=0; - if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) - { - $found=1; - } - else - { - //print 'Fetch '.$id." - ".$ref.'
    '; + if (! $id && ! $ref) continue; + $found=0; + if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) + { + $found=1; + } + else + { + //print 'Fetch '.$id." - ".$ref.'
    '; - if ($id) { - $result = $object_instance->fetch($id); - } else { - //fetchOneLike looks for objects with wildcards in its reference. - //It is useful for those masks who get underscores instead of their actual symbols - //fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned - //that's why we look only look fetchOneLike when fetch returns 0 - if (!$result = $object_instance->fetch('', $ref)) { - $result = $object_instance->fetchOneLike($ref); - } - } + if ($id) { + $result = $object_instance->fetch($id); + } else { + //fetchOneLike looks for objects with wildcards in its reference. + //It is useful for those masks who get underscores instead of their actual symbols + //fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned + //that's why we look only look fetchOneLike when fetch returns 0 + if (!$result = $object_instance->fetch('', $ref)) { + $result = $object_instance->fetchOneLike($ref); + } + } if ($result > 0) { // Save object into a cache $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance; } - if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); } - } + if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); } + } - if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files + if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files - print ''."\n"; - print ''; - print ''; + print ''; + print ''; - // File - print '\n"; - print ''; - print ''; - print '\n"; - } - } + print "\n"; + print ''; + print ''; + print '\n"; + } + } - if (count($filearray) == 0) - { - print ''; - } - print "
    '; $searchpicto=$form->showFilterButtons(); print $searchpicto; print '
    '; - if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document'); - else print $langs->trans("ObjectDeleted",($id?$id:$ref)); + print ''."\n"; + print '
    '; + if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document'); + else print $langs->trans("ObjectDeleted",($id?$id:$ref)); - //$modulesubdir=dol_sanitizeFileName($ref); - $modulesubdir=dirname($relativefile); + //$modulesubdir=dol_sanitizeFileName($ref); + $modulesubdir=dirname($relativefile); - //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $filedir=$file['path']; - //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - //print $formfile->getDocumentsLink($modulepart, $filename, $filedir); + //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $filedir=$file['path']; + //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + //print $formfile->getDocumentsLink($modulepart, $filename, $filedir); - print ''; - //print "XX".$file['name']; //$file['name'] must be utf8 - print ''; - print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' '; - print dol_trunc($file['name'],$maxlength,'middle'); - print ''; + // File + print ''; + //print "XX".$file['name']; //$file['name'] must be utf8 + print ''; + print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' '; + print dol_trunc($file['name'],$maxlength,'middle'); + print ''; - print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$'); + print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$'); - print "'.dol_print_size($file['size'],1,1).''.dol_print_date($file['date'],"dayhour").''; - //if (! empty($useinecm)) print ''; - //print img_view().'   '; - //if ($permtodelete) print ''.img_delete().''; - //else print ' '; - print "
    '.dol_print_size($file['size'],1,1).''.dol_print_date($file['date'],"dayhour").''; + //if (! empty($useinecm)) print ''; + //print img_view().'   '; + //if ($permtodelete) print ''.img_delete().''; + //else print ' '; + print "
    '; - if (empty($textifempty)) print $langs->trans("NoFileFound"); - else print $textifempty; - print '
    "; - print '
    '; + if (count($filearray) == 0) + { + print ''; + if (empty($textifempty)) print $langs->trans("NoFileFound"); + else print $textifempty; + print ''; + } + print ""; + print '
    '; - if (! empty($addfilterfields)) print ''; - // Fin de zone - } + if (! empty($addfilterfields)) print ''; + // Fin de zone + } - /** - * Show form to upload a new file with jquery fileupload. - * This form use the fileupload.php file. - * - * @param Object $object Object to use - * @return void - */ - private function _formAjaxFileUpload($object) - { - global $langs; + /** + * Show form to upload a new file with jquery fileupload. + * This form use the fileupload.php file. + * + * @param Object $object Object to use + * @return void + */ + private function _formAjaxFileUpload($object) + { + global $langs; - // PHP post_max_size - $post_max_size = ini_get('post_max_size'); - $mul_post_max_size = substr($post_max_size, -1); - $mul_post_max_size = ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1))); - $post_max_size = $mul_post_max_size * (int) $post_max_size; - // PHP upload_max_filesize - $upload_max_filesize = ini_get('upload_max_filesize'); - $mul_upload_max_filesize = substr($upload_max_filesize, -1); - $mul_upload_max_filesize = ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1))); - $upload_max_filesize = $mul_upload_max_filesize * (int) $upload_max_filesize; - // Max file size - $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize); + // PHP post_max_size + $post_max_size = ini_get('post_max_size'); + $mul_post_max_size = substr($post_max_size, -1); + $mul_post_max_size = ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1))); + $post_max_size = $mul_post_max_size * (int) $post_max_size; + // PHP upload_max_filesize + $upload_max_filesize = ini_get('upload_max_filesize'); + $mul_upload_max_filesize = substr($upload_max_filesize, -1); + $mul_upload_max_filesize = ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1))); + $upload_max_filesize = $mul_upload_max_filesize * (int) $upload_max_filesize; + // Max file size + $max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize); - // Include main - include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php'; + // Include main + include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php'; - // Include template - include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php'; + // Include template + include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php'; - } + } - /** - * Show array with linked files - * - * @param Object $object Object - * @param int $permtodelete Deletion is allowed - * @param string $action Action - * @param string $selected ??? - * @param string $param More param to add into URL - * @return int Number of links - */ - public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='') - { - global $user, $conf, $langs, $user; - global $bc; - global $sortfield, $sortorder; + /** + * Show array with linked files + * + * @param Object $object Object + * @param int $permtodelete Deletion is allowed + * @param string $action Action + * @param string $selected ??? + * @param string $param More param to add into URL + * @return int Number of links + */ + public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='') + { + global $user, $conf, $langs, $user; + global $bc; + global $sortfield, $sortorder; - $langs->load("link"); + $langs->load("link"); - require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; - $link = new Link($this->db); - $links = array(); - if ($sortfield == "name") { - $sortfield = "label"; - } elseif ($sortfield == "date") { - $sortfield = "datea"; - } else { - $sortfield = null; - } - $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder); - $param .= (isset($object->id)?'&id=' . $object->id : ''); + require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php'; + $link = new Link($this->db); + $links = array(); + if ($sortfield == "name") { + $sortfield = "label"; + } elseif ($sortfield == "date") { + $sortfield = "datea"; + } else { + $sortfield = null; + } + $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder); + $param .= (isset($object->id)?'&id=' . $object->id : ''); - // Show list of associated links - print load_fiche_titre($langs->trans("LinkedFiles")); + // Show list of associated links + print load_fiche_titre($langs->trans("LinkedFiles")); - print '
    '; + print ''; - print ''; - print ''; - print_liste_field_titre( - $langs->trans("Links"), - $_SERVER['PHP_SELF'], - "name", - "", - $param, - 'align="left"', - $sortfield, - $sortorder - ); - print_liste_field_titre( - "", - "", - "", - "", - "", - 'align="right"' - ); - print_liste_field_titre( - $langs->trans("Date"), - $_SERVER['PHP_SELF'], - "date", - "", - $param, - 'align="center"', - $sortfield, - $sortorder - ); - print_liste_field_titre( - '', - $_SERVER['PHP_SELF'], - "", - "", - $param, - 'align="center"' - ); - print_liste_field_titre('','',''); - print ''; - $nboflinks = count($links); - if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; + print '
    '; + print ''; + print_liste_field_titre( + $langs->trans("Links"), + $_SERVER['PHP_SELF'], + "name", + "", + $param, + 'align="left"', + $sortfield, + $sortorder + ); + print_liste_field_titre( + "", + "", + "", + "", + "", + 'align="right"' + ); + print_liste_field_titre( + $langs->trans("Date"), + $_SERVER['PHP_SELF'], + "date", + "", + $param, + 'align="center"', + $sortfield, + $sortorder + ); + print_liste_field_titre( + '', + $_SERVER['PHP_SELF'], + "", + "", + $param, + 'align="center"' + ); + print_liste_field_titre('','',''); + print ''; + $nboflinks = count($links); + if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - $var = true; - foreach ($links as $link) - { - $var =! $var; - print ''; - //edit mode - if ($action == 'update' && $selected === $link->id) - { - print ''; - print ''; - print ''; - print ''; - print ''; - } - else + $var = true; + foreach ($links as $link) + { + $var =! $var; + print ''; + //edit mode + if ($action == 'update' && $selected === $link->id) { - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - } - print "\n"; - } - if ($nboflinks == 0) - { - print ''; - } - print "
    '; - print ''; - print ''; - print ''; - print $langs->trans('Link') . ': '; - print ''; - print $langs->trans('Label') . ': '; - print '' . dol_print_date(dol_now(), "dayhour", "tzuser") . ''; - print ''; - print ''; - print '
    '; - print img_picto('', 'object_globe').' '; - print ''; - print $link->label; - print ''; - print '' . dol_print_date($link->datea, "dayhour", "tzuser") . ''; - print '' . img_edit() . ''; // id= is included into $param - if ($permtodelete) { - print '   ' . img_delete() . ''; // id= is included into $param - } else { - print ' '; - } - print '
    '; - print $langs->trans("NoLinkFound"); - print '
    "; + print ''; + print ''; + print ''; + print ''; + print $langs->trans('Link') . ': '; + print ''; + print ''; + print $langs->trans('Label') . ': '; + print ''; + print '' . dol_print_date(dol_now(), "dayhour", "tzuser") . ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + else + { + print ''; + print img_picto('', 'object_globe').' '; + print ''; + print $link->label; + print ''; + print ''."\n"; + print ''; + print '' . dol_print_date($link->datea, "dayhour", "tzuser") . ''; + print ''; + print ''; + print '' . img_edit() . ''; // id= is included into $param + if ($permtodelete) { + print '   ' . img_delete() . ''; // id= is included into $param + } else { + print ' '; + } + print ''; + } + print "\n"; + } + if ($nboflinks == 0) + { + print ''; + print $langs->trans("NoLinkFound"); + print ''; + } + print ""; - print '
    '; + print ''; - return $nboflinks; - } + return $nboflinks; + } - /** - * Show detail icon with link for preview - * - * @param array $file File - * @param string $modulepart propal, facture, facture_fourn, ... - * @param string $relativepath Relative path of docs - * @param string $ruleforpicto Rule for picto: 0=Preview picto, 1=Use picto of mime type of file) - * @param string $param More param on http links - * @return string $out Output string with HTML - */ - public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='') - { - global $langs, $conf; + /** + * Show detail icon with link for preview + * + * @param array $file File + * @param string $modulepart propal, facture, facture_fourn, ... + * @param string $relativepath Relative path of docs + * @param string $ruleforpicto Rule for picto: 0=Preview picto, 1=Use picto of mime type of file) + * @param string $param More param on http links + * @return string $out Output string with HTML + */ + public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='') + { + global $langs, $conf; - $out=''; - if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax)) - { - $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview. - if (count($urladvancedpreview)) - { - $out.= ''; - //$out.= ''; - if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); - else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); - $out.= ''; - } - } - return $out; - } + $out=''; + if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax)) + { + $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview. + if (count($urladvancedpreview)) + { + $out.= ''; + //$out.= ''; + if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); + else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); + $out.= ''; + } + } + return $out; + } } diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index cc09b8bb521..a9ebafc4769 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -282,578 +282,578 @@ class FormMail extends Form $outputlangs->load('other'); } - // Get message template for $this->param["models"] into c_email_templates + // Get message template for $this->param["models"] into c_email_templates $arraydefaultmessage=array(); if ($this->param['models'] != 'none') { $model_id=0; - if (array_key_exists('models_id',$this->param)) - { - $model_id=$this->param["models_id"]; - } - $arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, ($model_id ? $model_id : -1)); // we set -1 if model_id empty - } - //var_dump($this->param["models"]); - //var_dump($model_id); - //var_dump($arraydefaultmessage); - - - // Define list of attached files - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined - - if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1')) - { - $this->clear_attached_files(); - if (! empty($arraydefaultmessage['joinfiles']) && is_array($this->param['fileinit'])) - { - foreach($this->param['fileinit'] as $file) - { - $this->add_attached_files($file, basename($file), dol_mimetype($file)); - } - } - } - - if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); - if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); - if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); - - - $out.= "\n".'
    '."\n"; - if ($this->withform == 1) - { - $out.= '
    '."\n"; - $out.= ''; - $out.= ''; - $out.= ''; - $out.= ''; - } - if (! empty($this->withfrom)) - { - if (! empty($this->withfromreadonly)) - { - $out.= ''; - $out.= ''; - } - } - foreach ($this->param as $key=>$value) - { - $out.= ''."\n"; - } - - $modelmail_array=array(); - if ($this->param['models'] != 'none') - { - $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs); - if ($result < 0) - { - setEventMessages($this->error, $this->errors, 'errors'); - } - foreach($this->lines_model as $line) - { - $langs->trans("members"); - if (preg_match('/\((.*)\)/', $line->label, $reg)) - { - $modelmail_array[$line->id]=$langs->trans($reg[1]); // langs->trans when label is __(xxx)__ - } - else - { - $modelmail_array[$line->id]=$line->label; - } - if ($line->lang) $modelmail_array[$line->id].=' ('.$line->lang.')'; - if ($line->private) $modelmail_array[$line->id].=' - '.$langs->trans("Private"); - //if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' '; - } - } - - // Zone to select email template - if (count($modelmail_array)>0) - { - // If list of template is filled - $out.= '
    '."\n"; - $out.= ''.$langs->trans('SelectMailModel').': '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100'); - if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); - $out.= '   '; - $out.= ''; - $out.= '   '; - $out.= '
    '; - } - elseif (! empty($this->param['models']) && in_array($this->param['models'], array( - 'propal_send','order_send','facture_send', - 'shipping_send','fichinter_send','supplier_proposal_send','order_supplier_send', - 'invoice_supplier_send','thirdparty','contract','user','all' - ))) - { - // If list of template is empty - $out.= '
    '."\n"; - $out.= $langs->trans('SelectMailModel').': '; // Do not put 'disabled' on 'option' tag, it is already on 'select' and it makes chrome crazy. - if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); - $out.= '   '; - $out.= ''; - $out.= '   '; - $out.= '
    '; - } - - - - $out.= ''."\n"; - - // Substitution array - if (! empty($this->withsubstit)) // Unset of set ->withsubstit=0 to disable this. - { - $out.= '\n"; - //$out.=''; - } - - // From - if (! empty($this->withfrom)) - { - if (! empty($this->withfromreadonly)) - { - $out.= '\n"; - } - else - { - $out.= '\n"; - } - } - - // To - if (! empty($this->withto) || is_array($this->withto)) - { - $out.= '\n"; - } - - // withoptiononeemailperrecipient - if (! empty($this->withoptiononeemailperrecipient)) - { - $out.= ''; - } - - // CC - if (! empty($this->withtocc) || is_array($this->withtocc)) - { - $out.= '\n"; - } - - // CCC - if (! empty($this->withtoccc) || is_array($this->withtoccc)) - { - $out.= '\n"; - } - - // Replyto - if (! empty($this->withreplyto)) - { - if ($this->withreplytoreadonly) - { - $out.= ''; - $out.= ''; - $out.= "\n"; - } - } - - // Errorsto - if (! empty($this->witherrorsto)) - { - //if (! $this->errorstomail) $this->errorstomail=$this->frommail; - $errorstomail = (! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail); - if ($this->witherrorstoreadonly) - { - $out.= ''; - $out.= '\n"; - } - else - { - $out.= '\n"; - } - } - - // Ask delivery receipt - if (! empty($this->withdeliveryreceipt)) - { - $out.= '\n"; - } - - // Topic - if (! empty($this->withtopic)) - { - $defaulttopic=GETPOST('subject','none'); - if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') + if (array_key_exists('models_id',$this->param)) { - if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['topic']) $defaulttopic=$arraydefaultmessage['topic']; - elseif (! is_numeric($this->withtopic)) $defaulttopic=$this->withtopic; + $model_id=$this->param["models_id"]; + } + $arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, ($model_id ? $model_id : -1)); // we set -1 if model_id empty + } + //var_dump($this->param["models"]); + //var_dump($model_id); + //var_dump($arraydefaultmessage); + + + // Define list of attached files + $listofpaths=array(); + $listofnames=array(); + $listofmimes=array(); + $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + + if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1')) + { + $this->clear_attached_files(); + if (! empty($arraydefaultmessage['joinfiles']) && is_array($this->param['fileinit'])) + { + foreach($this->param['fileinit'] as $file) + { + $this->add_attached_files($file, basename($file), dol_mimetype($file)); + } + } + } + + if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]); + if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]); + if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]); + + + $out.= "\n".'
    '."\n"; + if ($this->withform == 1) + { + $out.= ''."\n"; + $out.= ''; + $out.= ''; + $out.= ''; + $out.= ''; + } + if (! empty($this->withfrom)) + { + if (! empty($this->withfromreadonly)) + { + $out.= ''; + $out.= ''; + } + } + foreach ($this->param as $key=>$value) + { + $out.= ''."\n"; + } + + $modelmail_array=array(); + if ($this->param['models'] != 'none') + { + $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs); + if ($result < 0) + { + setEventMessages($this->error, $this->errors, 'errors'); + } + foreach($this->lines_model as $line) + { + $langs->trans("members"); + if (preg_match('/\((.*)\)/', $line->label, $reg)) + { + $modelmail_array[$line->id]=$langs->trans($reg[1]); // langs->trans when label is __(xxx)__ + } + else + { + $modelmail_array[$line->id]=$line->label; + } + if ($line->lang) $modelmail_array[$line->id].=' ('.$line->lang.')'; + if ($line->private) $modelmail_array[$line->id].=' - '.$langs->trans("Private"); + //if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' '; + } + } + + // Zone to select email template + if (count($modelmail_array)>0) + { + // If list of template is filled + $out.= '
    '."\n"; + $out.= ''.$langs->trans('SelectMailModel').': '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); + $out.= '   '; + $out.= ''; + $out.= '   '; + $out.= '
    '; + } + elseif (! empty($this->param['models']) && in_array($this->param['models'], array( + 'propal_send','order_send','facture_send', + 'shipping_send','fichinter_send','supplier_proposal_send','order_supplier_send', + 'invoice_supplier_send','thirdparty','contract','user','all' + ))) + { + // If list of template is empty + $out.= '
    '."\n"; + $out.= $langs->trans('SelectMailModel').': '; // Do not put 'disabled' on 'option' tag, it is already on 'select' and it makes chrome crazy. + if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1); + $out.= '   '; + $out.= ''; + $out.= '   '; + $out.= '
    '; + } + + + + $out.= '
    '; - //$out.='
    '; - $help=""; - foreach($this->substit as $key => $val) - { - $help.=$key.' -> '.$langs->trans(dol_string_nohtmltag($val)).'
    '; - } - if (is_numeric($this->withsubstit)) $out.= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $help, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage - else $out.= $form->textwithpicto($langs->trans('AvailableVariables'), $help, 1, 'help', '', 0, 2, 'substittooltip'); // New usage - $out.= "
    '.$langs->trans("MailFrom").''; - - if (! ($this->fromtype === 'user' && $this->fromid > 0) - && ! ($this->fromtype === 'company') - && ! preg_match('/user_aliases/', $this->fromtype) - && ! preg_match('/global_aliases/', $this->fromtype) - && ! preg_match('/senderprofile/', $this->fromtype)) - { - // Use this->fromname and this->frommail or error if not defined - $out.= $this->fromname; - if ($this->frommail) - { - $out.= ' <'.$this->frommail.'>'; - } - else - { - if ($this->fromtype) - { - $langs->load('errors'); - $out.= ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'> '; - } - } - } else { - $liste = array(); - - // Add user email - if (empty($user->email)) - { - $langs->load('errors'); - $liste['user'] = $user->getFullName($langs) . ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'>'; - } - else - { - $liste['user'] = $user->getFullName($langs) .' <'.$user->email.'>'; - } - - // Add also company main email - $liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; - - // Add also email aliases if there is some - $listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); - - // Add also email aliases from the c_email_senderprofile table - $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1 ORDER BY position'; - $resql = $this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - $i=0; - while($i < $num) - { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; - } - $i++; - } - } - else dol_print_error($this->db); - - foreach($listaliases as $typealias => $listalias) - { - $posalias=0; - $listaliasarray=explode(',', $listalias); - foreach ($listaliasarray as $listaliasval) - { - $posalias++; - $listaliasval=trim($listaliasval); - if ($listaliasval) - { - $listaliasval=preg_replace('//', '>', $listaliasval); - if (! preg_match('/</', $listaliasval)) $listaliasval='<'.$listaliasval.'>'; - $liste[$typealias.'_'.$posalias]=$listaliasval; - } - } - } - $out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', '', 0, '', $disablebademails); - //$out.= ajax_combobox('fromtype'); - } - - $out.= "
    '.$langs->trans("MailFrom").""; - $out.= $langs->trans("Name").':'; - $out.= '    '; - $out.= $langs->trans("EMail").':<>'; - $out.= "
    '; - if ($this->withtofree) $out.= $form->textwithpicto($langs->trans("MailTo"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); - else $out.= $langs->trans("MailTo"); - $out.= ''; - if ($this->withtoreadonly) - { - if (! empty($this->toname) && ! empty($this->tomail)) - { - $out.= ''; - $out.= ''; - if ($this->totype == 'thirdparty') - { - $soc=new Societe($this->db); - $soc->fetch($this->toid); - $out.= $soc->getNomUrl(1); - } - else if ($this->totype == 'contact') - { - $contact=new Contact($this->db); - $contact->fetch($this->toid); - $out.= $contact->getNomUrl(1); - } - else - { - $out.= $this->toname; - } - $out.= ' <'.$this->tomail.'>'; - if ($this->withtofree) - { - $out.= '
    '.$langs->trans("and").' withto) :"").'" />'; - } - } - else - { - // Note withto may be a text like 'AllRecipientSelected' - $out.= (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:""; - } - } - else - { - if (! empty($this->withtofree)) - { - $out.= 'withto) :"").'" />'; - } - if (! empty($this->withto) && is_array($this->withto)) - { - if (! empty($this->withtofree)) $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; - // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time - $tmparray = $this->withto; - foreach($tmparray as $key => $val) - { - $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); - } - $withtoselected=GETPOST("receiver",'none'); // Array of selected value - if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend') - { - $withtoselected = array_keys($tmparray); - } - $out.= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, ""); - } - } - $out.= "
    '; - $out.= $langs->trans("GroupEmails"); - $out.= ''; - $out.=' withoptiononeemailperrecipient > 0?' checked="checked"':'').'> '; - $out.= $langs->trans("OneEmailPerRecipient").' - '; - $out.= $langs->trans("WarningIfYouCheckOneRecipientPerEmail"); - $out.= '
    '; - $out.= $form->textwithpicto($langs->trans("MailCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); - $out.= ''; - if ($this->withtoccreadonly) - { - $out.= (! is_array($this->withtocc) && ! is_numeric($this->withtocc))?$this->withtocc:""; - } - else - { - $out.= 'withtocc) : (isset($_POST["sendtocc"])?$_POST["sendtocc"]:"") ).'" />'; - if (! empty($this->withtocc) && is_array($this->withtocc)) - { - $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; - // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time - $tmparray = $this->withtocc; - foreach($tmparray as $key => $val) - { - $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); - } - $withtoccselected=GETPOST("receivercc"); // Array of selected value - $out.= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500',null, ""); - } - } - $out.= "
    '; - $out.= $form->textwithpicto($langs->trans("MailCCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); - $out.= ''; - if (! empty($this->withtocccreadonly)) - { - $out.= (! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))?$this->withtoccc:""; - } - else - { - $out.= 'withtoccc) : (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:"") ).'" />'; - if (! empty($this->withtoccc) && is_array($this->withtoccc)) - { - $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; - // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time - $tmparray = $this->withtoccc; - foreach($tmparray as $key => $val) - { - $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); - } - $withtocccselected=GETPOST("receiverccc"); // Array of selected value - $out.= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null,null, "90%"); - } - } - - $showinfobcc=''; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO; - if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO; - if ($showinfobcc) $out.=' + '.$showinfobcc; - $out.= "
    ".$langs->trans("MailReply")."".$this->replytoname.($this->replytomail?(" <".$this->replytomail.">"):""); - $out.= "
    '.$langs->trans("MailErrorsTo").''; - $out.= $errorstomail; - $out.= "
    '.$langs->trans("MailErrorsTo").''; - $out.= ''; - $out.= "
    '.$langs->trans("DeliveryReceipt").''; - - if (! empty($this->withdeliveryreceiptreadonly)) - { - $out.= yn($this->withdeliveryreceipt); - } - else - { - $defaultvaluefordeliveryreceipt=0; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $defaultvaluefordeliveryreceipt=1; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $defaultvaluefordeliveryreceipt=1; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $defaultvaluefordeliveryreceipt=1; - if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $defaultvaluefordeliveryreceipt=1; - $out.= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"])?$_POST["deliveryreceipt"]:$defaultvaluefordeliveryreceipt), 1); - } - - $out.= "
    '."\n"; + + // Substitution array + if (! empty($this->withsubstit)) // Unset of set ->withsubstit=0 to disable this. + { + $out.= '\n"; + //$out.=''; + } + + // From + if (! empty($this->withfrom)) + { + if (! empty($this->withfromreadonly)) + { + $out.= '\n"; + } + else + { + $out.= '\n"; + } + } + + // To + if (! empty($this->withto) || is_array($this->withto)) + { + $out.= '\n"; + } + + // withoptiononeemailperrecipient + if (! empty($this->withoptiononeemailperrecipient)) + { + $out.= ''; + } + + // CC + if (! empty($this->withtocc) || is_array($this->withtocc)) + { + $out.= '\n"; + } + + // CCC + if (! empty($this->withtoccc) || is_array($this->withtoccc)) + { + $out.= '\n"; + } - $out.= ''; - $out.= ''; - $out.= '\n"; - } + // Replyto + if (! empty($this->withreplyto)) + { + if ($this->withreplytoreadonly) + { + $out.= ''; + $out.= ''; + $out.= "\n"; + } + } - // Attached files - if (! empty($this->withfile)) - { - $out.= ''; - $out.= ''; + // Errorsto + if (! empty($this->witherrorsto)) + { + //if (! $this->errorstomail) $this->errorstomail=$this->frommail; + $errorstomail = (! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail); + if ($this->witherrorstoreadonly) + { + $out.= ''; + $out.= '\n"; + } + else + { + $out.= '\n"; + } + } - $out.= '\n"; + } + + // Topic + if (! empty($this->withtopic)) + { + $defaulttopic=GETPOST('subject','none'); + if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') + { + if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['topic']) $defaulttopic=$arraydefaultmessage['topic']; + elseif (! is_numeric($this->withtopic)) $defaulttopic=$this->withtopic; + } + + $defaulttopic=make_substitutions($defaulttopic,$this->substit); + + $out.= ''; + $out.= ''; + $out.= '\n"; + } + + // Attached files + if (! empty($this->withfile)) + { + $out.= ''; + $out.= ''; + + $out.= '\n"; - } + $out.= "\n"; + } - // Message - if (! empty($this->withbody)) - { - $defaultmessage=GETPOST('message','none'); + // Message + if (! empty($this->withbody)) + { + $defaultmessage=GETPOST('message','none'); if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1') { if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['content']) $defaultmessage=$arraydefaultmessage['content']; - elseif (! is_numeric($this->withbody)) $defaultmessage=$this->withbody; + elseif (! is_numeric($this->withbody)) $defaultmessage=$this->withbody; } - // Complete substitution array - $paymenturl=''; - if (! empty($conf->global->PAYMENT_ADD_PAYMENT_URL) // Option to enable to add online link into __PERSONALIZED__ - || (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_ADD_PAYMENT_URL)) - ) - { - if (empty($this->substit['__REF__'])) - { - //$paymenturl='LinkToPayOnlineNotAvailableInThisContext'; - $paymenturl=''; - } - else - { - // Set the online payment message and url link into __PERSONALIZED__ key - require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; - $langs->load('paypal'); - $typeforonlinepayment='free'; - if ($this->param["models"]=='order_send') $typeforonlinepayment='order'; // TODO use detection on something else than template - if ($this->param["models"]=='facture_send') $typeforonlinepayment='invoice'; // TODO use detection on something else than template - if ($this->param["models"]=='member_send') $typeforonlinepayment='member'; // TODO use detection on something else than template - $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']); - //$paymenturl=str_replace('\n',"\n",$langs->transnoentitiesnoconv("PredefinedMailContentLink",$url)); - $paymenturl=$url; - } - } - $this->substit['__PERSONALIZED__']=$paymenturl; // deprecated - $this->substit['__ONLINE_PAYMENT_URL__']=$paymenturl; + // Complete substitution array + $paymenturl=''; + if (! empty($conf->global->PAYMENT_ADD_PAYMENT_URL) // Option to enable to add online link into __PERSONALIZED__ + || (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_ADD_PAYMENT_URL)) + ) + { + if (empty($this->substit['__REF__'])) + { + //$paymenturl='LinkToPayOnlineNotAvailableInThisContext'; + $paymenturl=''; + } + else + { + // Set the online payment message and url link into __PERSONALIZED__ key + require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; + $langs->load('paypal'); + $typeforonlinepayment='free'; + if ($this->param["models"]=='order_send') $typeforonlinepayment='order'; // TODO use detection on something else than template + if ($this->param["models"]=='facture_send') $typeforonlinepayment='invoice'; // TODO use detection on something else than template + if ($this->param["models"]=='member_send') $typeforonlinepayment='member'; // TODO use detection on something else than template + $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']); + //$paymenturl=str_replace('\n',"\n",$langs->transnoentitiesnoconv("PredefinedMailContentLink",$url)); + $paymenturl=$url; + } + } + $this->substit['__PERSONALIZED__']=$paymenturl; // deprecated + $this->substit['__ONLINE_PAYMENT_URL__']=$paymenturl; - //Add lines substitution key from each line - $lines = ''; - $defaultlines = $arraydefaultmessage['content_lines']; - if (isset($defaultlines)) - { - foreach ($this->substit_lines as $substit_line) - { - $lines .= make_substitutions($defaultlines,$substit_line)."\n"; - } - } - $this->substit['__LINES__']=$lines; + //Add lines substitution key from each line + $lines = ''; + $defaultlines = $arraydefaultmessage['content_lines']; + if (isset($defaultlines)) + { + foreach ($this->substit_lines as $substit_line) + { + $lines .= make_substitutions($defaultlines,$substit_line)."\n"; + } + } + $this->substit['__LINES__']=$lines; $defaultmessage=str_replace('\n',"\n",$defaultmessage); diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index 049ec0c5d75..432a7bb37de 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -1001,8 +1001,8 @@ class FormOther { if (! empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user $label=$langs->transnoentitiesnoconv($box->boxlabel); - if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; - //$label = ''.$label; KO with select2. No html rendering. + //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; + if (preg_match('/graph/',$box->class)) $label=$label.' '; $arrayboxtoactivatelabel[$box->id]=$label; // We keep only boxes not shown for user, to show into combo list } foreach($boxidactivatedforuser as $boxid) @@ -1014,6 +1014,7 @@ class FormOther //var_dump($boxidactivatedforuser); // Class Form must have been already loaded + $selectboxlist.=''."\n"; $selectboxlist.=''; $selectboxlist.=''; $selectboxlist.=''; @@ -1086,6 +1087,7 @@ class FormOther var self = this; // because JQuery can modify this var boxid=self.id.substring(8); var label=jQuery(\'#boxlabelentry\'+boxid).val(); + console.log("We close box "+boxid); jQuery(\'#boxto_\'+boxid).remove(); if (boxid > 0) jQuery(\'#boxcombo\').append(new Option(label, boxid)); updateBoxOrder(1); /* 1 to avoid message after a remove */ diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 66735c62606..55aac773420 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -624,7 +624,7 @@ class Translate $str=str_replace(array('<','>','"',),array('__lt__','__gt__','__quot__'),$str); // Crypt string into HTML - $str=htmlentities($str,ENT_QUOTES,$this->charset_output); + $str=htmlentities($str, ENT_COMPAT, $this->charset_output); // Do not convert simple quotes in translation (strings in html are enmbraced by "). Use dol_escape_htmltag around text in HTML content // Restore HTML tags $str=str_replace(array('__lt__','__gt__','__quot__'),array('<','>','"',),$str); diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index 9fc1739334c..99b799d5d6e 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -59,7 +59,7 @@ abstract class DoliDB implements Database public $lastqueryerror; /** @var string Last error message */ public $lasterror; - /** @var int Last error number */ + /** @var string Last error number. For example: 'DB_ERROR_RECORD_ALREADY_EXISTS', '12345', ... */ public $lasterrno; /** @var bool Status */ @@ -238,16 +238,16 @@ abstract class DoliDB implements Database else $return.=', '; $return.=preg_replace('/[^0-9a-z_\.]/i','',$val); - + $tmpsortorder = trim($orders[$i]); - + // Only ASC and DESC values are valid SQL if (strtoupper($tmpsortorder) === 'ASC') { $return .= ' ASC'; } elseif (strtoupper($tmpsortorder) === 'DESC') { $return .= ' DESC'; } - + $i++; } return $return; diff --git a/htdocs/core/db/pgsql.class.php b/htdocs/core/db/pgsql.class.php index bc967ffb0b7..f0c437e0b96 100644 --- a/htdocs/core/db/pgsql.class.php +++ b/htdocs/core/db/pgsql.class.php @@ -274,7 +274,15 @@ class DoliDBPgsql extends DoliDB $line.= "ALTER TABLE ".$reg[1]." ADD PRIMARY KEY (".$reg[3]; } - // Translate order to drop foreign keys + // Translate order to drop primary keys + // ALTER TABLE llx_dolibarr_modules DROP PRIMARY KEY pk_xxx + if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+PRIMARY\s+KEY\s*([^;]+)$/i',$line,$reg)) + { + $line = "-- ".$line." replaced by --\n"; + $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2]; + } + + // Translate order to drop foreign keys // ALTER TABLE llx_dolibarr_modules DROP FOREIGN KEY fk_xxx if (preg_match('/ALTER\s+TABLE\s*(.*)\s*DROP\s+FOREIGN\s+KEY\s*(.*)$/i',$line,$reg)) { diff --git a/htdocs/core/filemanagerdol/connectors/php/config.php b/htdocs/core/filemanagerdol/connectors/php/config.php index de8b4d7e8bf..8df350ef150 100644 --- a/htdocs/core/filemanagerdol/connectors/php/config.php +++ b/htdocs/core/filemanagerdol/connectors/php/config.php @@ -48,7 +48,7 @@ $Config['Enabled'] = true ; $extEntity=(empty($entity) ? 1 : $entity); // For multicompany with external access $Config['UserFilesPath'] = DOL_URL_ROOT.'/viewimage.php?modulepart=medias'.(empty($website)?'':'_'.$website).'&entity='.$extEntity.'&file=' ; -$Config['UserFilesAbsolutePathRelative'] = (empty($website) ? ((!empty($entity) ? '/' . $entity : '') . '/medias/') : ('/websites/'.$website)); +$Config['UserFilesAbsolutePathRelative'] = (empty($website) ? ((!empty($entity) ? '/' . $entity : '') . '/medias/') : ('/website/'.$website)); // Fill the following value it you prefer to specify the absolute path for the diff --git a/htdocs/core/get_menudiv.php b/htdocs/core/get_menudiv.php index 4ffee2caad9..451747b4a6e 100644 --- a/htdocs/core/get_menudiv.php +++ b/htdocs/core/get_menudiv.php @@ -34,7 +34,6 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML',1); if (! defined('DISABLE_JQUERY_TABLEDND')) define('DISABLE_JQUERY_TABLEDND',1); -if (! defined('DISABLE_JQUERY_TIPTIP')) define('DISABLE_JQUERY_TIPTIP',1); if (! defined('DISABLE_JQUERY_JNOTIFY')) define('DISABLE_JQUERY_JNOTIFY',1); if (! defined('DISABLE_JQUERY_FLOT')) define('DISABLE_JQUERY_FLOT',1); if (! defined('DISABLE_JQUERY_JEDITABLE')) define('DISABLE_JQUERY_JEDITABLE',1); diff --git a/htdocs/core/js/lib_head.js.php b/htdocs/core/js/lib_head.js.php index a68995e5eeb..3ac4303ea8a 100644 --- a/htdocs/core/js/lib_head.js.php +++ b/htdocs/core/js/lib_head.js.php @@ -152,237 +152,27 @@ jQuery(function($){ /** - * Set select2 translations (if module was loaded). + * Set array used for select2 translations */ -(function ($) { - "use strict"; - if (typeof $.fn.select2 != "undefined") { - /* console.log($.fn.select2); - console.log("ok"); */ - - $.fn.select2.locales['xx'] = { - formatMatches: function (matches) { return matches + " trans("Select2ResultFoundUseArrows")); ?>"; }, - formatNoMatches: function () { return "trans("Select2NotFound")); ?>"; }, - formatInputTooShort: function (input, min) { var n = min - input.length; - if (n > 1) return "trans("Select2Enter")); ?> " + n + " trans("Select2MoreCharacters")); ?>"; - else return "trans("Select2Enter")); ?> " + n + " trans("Select2MoreCharacter")); ?>" - }, - formatLoadMore: function (pageNumber) { return "trans("Select2LoadingMoreResults")); ?>"; }, - formatSearching: function () { return "trans("Select2SearchInProgress")); ?>"; } - }; - - $.extend($.fn.select2.defaults, $.fn.select2.locales['xx']); - - } -})(jQuery); +var select2arrayoflanguage = { + matches: function (matches) { return matches + " transnoentitiesnoconv("Select2ResultFoundUseArrows")); ?>"; }, + noResults: function () { return "transnoentitiesnoconv("Select2NotFound")); ?>"; }, + inputTooShort: function (input) { + var n = input.minimum; + /*console.log(input); + console.log(input.minimum);*/ + if (n > 1) return "transnoentitiesnoconv("Select2Enter")); ?> " + n + " transnoentitiesnoconv("Select2MoreCharacters")); ?>"; + else return "transnoentitiesnoconv("Select2Enter")); ?> " + n + " transnoentitiesnoconv("Select2MoreCharacter")); ?>" + }, + loadMore: function (pageNumber) { return "transnoentitiesnoconv("Select2LoadingMoreResults")); ?>"; }, + searching: function () { return "transnoentitiesnoconv("Select2SearchInProgress")); ?>"; } +}; -/* - * ================================================================= - * Purpose: - * Pour la saisie des dates par calendrier Input: base "/theme/eldy" dateFieldID - * "dateo" Nom du champ format "dd/MM/yyyy" Format issu de Dolibarr de - * SimpleDateFormat a utiliser pour retour - * ================================================================== +/** + * For calendar input */ - /* -function showDP(base,dateFieldID,format,codelang) -{ - // check to see if another box is already showing - var alreadybox=getObjectFromID("DPCancel"); - if (alreadybox) closeDPBox(); // This erase value of showDP.datefieldID - - // alert("showDP "+codelang); - showDP.datefieldID=dateFieldID; // Must be after the close - - var dateField=getObjectFromID(dateFieldID); - - // get positioning - var thetop=getTop(dateField)+dateField.offsetHeight; - -// var xxx=getObjectFromID('bottompage'); -// alert(xxx.style.pixelTop); -// alert(document.body.clientHeight); -// alert(document.body.style.offsetTop); -// alert(thetop); -// alert(window.innerHeight); - if (thetop+160 > window.innerHeight) - thetop=thetop-160-20; - var theleft=getLeft(dateField); - if (theleft+140 > window.innerWidth) - theleft= theleft-140+dateField.offsetWidth-15; - - showDP.box=document.createElement("div"); - showDP.box.className="bodyline"; - showDP.box.style.display="block"; - showDP.box.style.zIndex="1000"; - showDP.box.style.position="absolute"; - showDP.box.style.top=thetop + "px"; - showDP.box.style.left=theleft + "px"; - - if (dateField.value) // Si il y avait valeur initiale dans champ - { - selDate=getDateFromFormat(dateField.value,format); - if (selDate) - { - // Success to parse value in field according to format - year=selDate.getFullYear(); - month=selDate.getMonth()+1; - day=selDate.getDate(); - datetime=selDate.getTime(); - ymd=formatDate(selDate,'yyyyMMdd'); - } - else - { - // Failed to parse value in field according to format - selDate=new Date(); - year=selDate.getFullYear(); - month=selDate.getUTCMonth()+1; - day=selDate.getDate(); - datetime=selDate.getTime(); - ymd=formatDate(selDate,'yyyyMMdd'); - } - } - else - { - selDate=new Date(); - year=selDate.getFullYear(); - month=selDate.getUTCMonth()+1; - day=selDate.getDate(); - datetime=selDate.getTime(); - ymd=formatDate(selDate,'yyyyMMdd'); - } - loadMonth(base,month,year,ymd,codelang); - hideSelectBoxes(); - document.body.appendChild(showDP.box); -} - -function resetDP(base,dateFieldID,format,codelang) -{ - var dateField=getObjectFromID(dateFieldID); - dateField.value = formatDate(new Date(), format); - dpChangeDay(dateFieldID,format); - - var alreadybox=getObjectFromID("DPCancel"); - if (alreadybox) showDP(base,dateFieldID,format,codelang); -} - -function loadMonth(base,month,year,ymd,codelang) -{ - // showDP.box.innerHTML="Loading..."; - // alert(codelang); - var theURL=base+"datepicker.php?cm=shw&lang="+codelang; - theURL+="&m="+encodeURIComponent(month); - theURL+="&y="+encodeURIComponent(year); - if (selDate) - { - theURL+="&sd="+ymd; - } - - var req=null; - - req=loadXMLDoc(theURL,null,false); - if (req.responseText == '') alert('Failed to get URL '.theURL); - // alert(theURL+' - '+req.responseText); // L'url doit avoir la meme racine - // que la pages et elements sinon pb de securite. - showDP.box.innerHTML=req.responseText; -} - -function closeDPBox() -{ - document.body.removeChild(showDP.box); - displaySelectBoxes(); - showDP.box=null; - showDP.datefieldID=null; -} - -function dpClickDay(year,month,day,format) -{ - var thefield=getObjectFromID(showDP.datefieldID); - var thefieldday=getObjectFromID(showDP.datefieldID+"day"); - var thefieldmonth=getObjectFromID(showDP.datefieldID+"month"); - var thefieldyear=getObjectFromID(showDP.datefieldID+"year"); - - var dt = new Date(year, month-1, day); - - thefield.value=formatDate(dt,format); - if(thefield.onchange) thefield.onchange.call(thefield); - - thefieldday.value=day; - if(thefieldday.onchange) thefieldday.onchange.call(thefieldday); - thefieldmonth.value=month; - if(thefieldmonth.onchange) thefieldmonth.onchange.call(thefieldmonth); - thefieldyear.value=year; - if(thefieldyear.onchange) thefieldyear.onchange.call(thefieldyear); - - closeDPBox(); -} - -function dpHighlightDay(year,month,day,months){ - var displayinfo=getObjectFromID("dpExp"); - displayinfo.innerHTML=months[month-1]+" "+day+", "+year; -} - -// This Function returns the top position of an object -function getTop(theitem){ - var offsetTrail = theitem; - var offsetTop = 0; - while (offsetTrail) { - offsetTop += offsetTrail.offsetTop; - offsetTrail = offsetTrail.offsetParent; - } - if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") - offsetTop += document.body.TopMargin; - return offsetTop; -} - -// This Function returns the left position of an object -function getLeft(theitem){ - var offsetTrail = theitem; - var offsetLeft = 0; - while (offsetTrail) { - offsetLeft += offsetTrail.offsetLeft; - offsetTrail = offsetTrail.offsetParent; - } - if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") - offsetLeft += document.body.leftMargin; - return offsetLeft; -} - -// To hide/show select Boxes with IE6 (and only IE6 because IE6 has a bug and -// not put popup completely on the front) -// Used only bu popup calendar -function hideSelectBoxes() { - var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10); - if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE 6") > -1) - { - for(var i = 0; i < document.all.length; i++) - { - if(document.all[i].tagName) - if(document.all[i].tagName == "SELECT") - document.all[i].style.visibility="hidden"; - } - } -} -// To hide/show select Boxes with IE6 (and only IE6 because IE6 has a bug and -// not put popup completely on the front) -// Used only bu popup calendar -function displaySelectBoxes() { - var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10); - if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE 6") > -1) - { - for(var i = 0; i < document.all.length; i++) - { - if(document.all[i].tagName) - if(document.all[i].tagName == "SELECT") - document.all[i].style.visibility="visible"; - } - } -} - -*/ - // Returns an object given an id function getObjectFromID(id){ @@ -426,69 +216,6 @@ function dpChangeDay(dateFieldID,format) } } - - - - -// Create XMLHttpRequest object and load url -// Used by calendar or other ajax processes -// Return req built or false if error -function loadXMLDoc(url,readyStateFunction,async) -{ - // req must be defined by caller with - // var req = false; - - // branch for native XMLHttpRequest object (Mozilla, Safari...) - if (window.XMLHttpRequest) - { - req = new XMLHttpRequest(); - -// if (req.overrideMimeType) { -// req.overrideMimeType('text/xml'); -// } - } - // branch for IE/Windows ActiveX version - else if (window.ActiveXObject) - { - try - { - req = new ActiveXObject("Msxml2.XMLHTTP"); - } - catch (e) - { - try { - req = new ActiveXObject("Microsoft.XMLHTTP"); - } catch (e) {} - } - } - - // If XMLHttpRequestObject req is ok, call URL - if (! req) - { - alert('Cannot create XMLHTTP instance'); - return false; - } - - if (readyStateFunction) req.onreadystatechange = readyStateFunction; - // Exemple of function for readyStateFuncyion: - // function () - // { - // if ( (req.readyState == 4) && (req.status == 200) ) { - // if (req.responseText == 1) { newStatus = 'AAA'; } - // if (req.responseText == 0) { newStatus = 'BBB'; } - // if (currentStatus != newStatus) { - // if (newStatus == "AAA") { obj.innerHTML = 'AAA'; } - // else { obj.innerHTML = 'BBB'; } - // currentStatus = newStatus; - // } - // } - // } - req.open("GET", url, async); - req.send(null); - return req; -} - - /* * ================================================================= * Function: @@ -552,9 +279,9 @@ function formatDate(date,format) /* * ================================================================= - * Function: - * getDateFromFormat(date_string, format_string) Purpose: This function takes a - * date string and a format string. It parses the date string with format and it + * Function: getDateFromFormat(date_string, format_string) + * Purpose: This function takes a date string and a format string. + * It parses the date string with format and it * returns the date as a javascript Date() object. If date does not match * format, it returns 0. The format string can use the following tags: * Field | Tags @@ -650,9 +377,8 @@ function getDateFromFormat(val,format) /* * ================================================================= - * Function: - * stringIsInteger(string) - * Purpose: Return true if string is an integer + * Function: stringIsInteger(string) + * Purpose: Return true if string is an integer * ================================================================== */ function stringIsInteger(str) @@ -670,9 +396,8 @@ function stringIsInteger(str) /* * ================================================================= - * Function: - * getIntegerInString(string,pos,minlength,maxlength) - * Purpose: Return part of string from position i that is integer + * Function: getIntegerInString(string,pos,minlength,maxlength) + * Purpose: Return part of string from position i that is integer * ================================================================== */ function getIntegerInString(str,i,minlength,maxlength) @@ -689,10 +414,9 @@ function getIntegerInString(str,i,minlength,maxlength) /* * ================================================================= - * Purpose: - * Clean string to have it url encoded - * Input: s - * Author: Laurent Destailleur + * Purpose: Clean string to have it url encoded + * Input: s + * Author: Laurent Destailleur * Licence: GPL * ================================================================== */ @@ -703,11 +427,32 @@ function urlencode(s) { return news; } +/* + * ================================================================= + * Purpose: Clean string to have it url encoded + * Input: s + * Author: Laurent Destailleur + * Licence: GPL + * ================================================================== + */ +function htmlEntityDecodeJs(inp){ + var replacements = {'<':'<','>':'>','/':'/','"':'"',''':'\'','&':'&',' ':' '}; + if (inp) + { + for(var r in replacements){ + inp = inp.replace(new RegExp(r,'g'),replacements[r]); + } + return inp.replace(/&#(\d+);/g, function(match, dec) { + return String.fromCharCode(dec); + }); + } + else { return ''; } +} + /* * ================================================================= - * Purpose: - * Applique un delai avant execution. Used for autocompletion of companies. + * Purpose: Applique un delai avant execution. Used for autocompletion of companies. * Input: funct, delay * Author: Regis Houssin * Licence: GPL @@ -955,6 +700,7 @@ function confirmConstantAction(action, url, code, input, box, entity, yesButton, } } + /* * ================================================================= * This is to allow to transform all select box into ajax autocomplete box @@ -1070,6 +816,7 @@ function confirmConstantAction(action, url, code, input, box, entity, yesButton, })( jQuery ); + /** * Function to output a dialog bog for copy/paste * @@ -1303,7 +1050,7 @@ function price2numjs(amount) { // If rounding higher than max shown if (rounding > main_max_dec_shown) rounding = main_max_dec_shown; if (thousand != ',' && thousand != '.') amount = amount.replace(',', '.'); - amount = amount.replace(' ', ''); // To avoid spaces + amount = amount.replace(' ', ''); // To avoid spaces amount = amount.replace(thousand, ''); // Replace of thousand before replace of dec to avoid pb if thousand is . amount = amount.replace(dec, '.'); //console.log("amount before="+amount+" rouding="+rounding) diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php index 500bbbb3ffb..825f99d6e98 100644 --- a/htdocs/core/lib/ajax.lib.php +++ b/htdocs/core/lib/ajax.lib.php @@ -27,9 +27,9 @@ /** * Generic function that return javascript to add to a page to transform a common input field into an autocomplete field by calling an Ajax page (ex: /societe/ajaxcompanies.php). * The HTML field must be an input text with id=search_$htmlname. - * This use the jQuery "autocomplete" function. + * This use the jQuery "autocomplete" function. If we want to use the select2, we must also convert the input into select on funcntions that call this method. * - * @param string $selected Preselecte value + * @param string $selected Preselected value * @param string $htmlname HTML name of input field * @param string $url Url for request: /path/page.php. Must return a json array ('key'=>id, 'value'=>String shown into input field once selected, 'label'=>String shown into combo list) * @param string $urloption More parameters on URL request @@ -387,6 +387,7 @@ function ajax_autoselect($htmlname, $addlink='') * @param int $forcefocus Force focus on field * @param string $widthTypeOfAutocomplete 'resolve' or 'off' * @return string Return html string to convert a select field into a combo, or '' if feature has been disabled for some reason. + * @see selectArrayAjax of html.form.class */ function ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve') { @@ -404,10 +405,29 @@ function ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $ $msg="\n".''."\n"; - } + print "\n"; + print ''."\n"; } // End of tuning @@ -6791,3 +6862,37 @@ function getDictvalue($tablename, $field, $id, $checkentity=false, $rowidfield=' return ''; } } + +/** + * Return true if the color is light + * + * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255') + * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light + */ +function colorIsLight($stringcolor) +{ + $res = -1; + if (!empty($stringcolor)) + { + $res = 0; + $tmp=explode(',', $stringcolor); + if (count($tmp) > 1) // This is a comma RGB ('255','255','255') + { + $r = $tmp[0]; + $g = $tmp[1]; + $b = $tmp[2]; + } + else + { + $hexr=$stringcolor[0].$stringcolor[1]; + $hexg=$stringcolor[2].$stringcolor[3]; + $hexb=$stringcolor[4].$stringcolor[5]; + $r = hexdec($hexr); + $g = hexdec($hexg); + $b = hexdec($hexb); + } + $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm + if ($bright > 0.6) $res = 1; + } + return $res; +} diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 3d2e2bb359b..7697c4e56a9 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -1606,7 +1606,8 @@ function getListOfModels($db,$type,$maxfilenamelength=0) if (! $tmpdir) { unset($listofdir[$key]); continue; } if (is_dir($tmpdir)) { - $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0); + // all type of template is allowed + $tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0); if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles); } } @@ -2153,40 +2154,6 @@ function colorStringToArray($stringcolor,$colorifnotfound=array(88,88,88)) return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3])); } -/** - * Return true if the color is light - * - * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255') - * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light - */ -function colorIsLight($stringcolor) -{ - $res = -1; - if (!empty($stringcolor)) - { - $res = 0; - $tmp=explode(',', $stringcolor); - if (count($tmp) > 1) // This is a comma RGB ('255','255','255') - { - $r = $tmp[0]; - $g = $tmp[1]; - $b = $tmp[2]; - } - else - { - $hexr=$stringcolor[0].$stringcolor[1]; - $hexg=$stringcolor[2].$stringcolor[3]; - $hexb=$stringcolor[4].$stringcolor[5]; - $r = hexdec($hexr); - $g = hexdec($hexg); - $b = hexdec($hexb); - } - $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm - if ($bright > 0.6) $res = 1; - } - return $res; -} - /** * Applies the Cartesian product algorithm to an array * Source: http://stackoverflow.com/a/15973172 diff --git a/htdocs/core/lib/modulebuilder.lib.php b/htdocs/core/lib/modulebuilder.lib.php index 23d6597b227..c437d47ce69 100644 --- a/htdocs/core/lib/modulebuilder.lib.php +++ b/htdocs/core/lib/modulebuilder.lib.php @@ -132,9 +132,9 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir=' $texttoinsert.= " 'notnull'=>".($val['notnull']!=''?$val['notnull']:-1).","; if ($val['index']) $texttoinsert.= " 'index'=>".$val['index'].","; if ($val['searchall']) $texttoinsert.= " 'searchall'=>".$val['searchall'].","; - if ($val['comment']) $texttoinsert.= " 'comment'=>'".$val['comment']."',"; + if ($val['comment']) $texttoinsert.= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\","; // addslashes is escape for PHP if ($val['isameasure']) $texttoinsert.= " 'isameasure'=>'".$val['isameasure']."',"; - if ($val['help']) $texttoinsert.= " 'help'=>'".$val['help']."',"; + if ($val['help']) $texttoinsert.= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\","; // addslashes is escape for PHP if ($val['arrayofkeyval']) { $texttoinsert.= " 'arrayofkeyval'=>array("; @@ -215,8 +215,8 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir='', $pathoffiletoclasssrc=$readdir.'/class/'.strtolower($objectname).'.class.php'; // Edit .sql file - $pathoffiletoeditsrc=$readdir.'/sql/llx_'.strtolower($objectname).'.sql'; - $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($objectname).'.sql'.($readdir != $destdir ? '.new' : ''); + $pathoffiletoeditsrc=$readdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql'; + $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql'.($readdir != $destdir ? '.new' : ''); if (! dol_is_file($pathoffiletoeditsrc)) { $langs->load("errors"); @@ -251,9 +251,22 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir='', foreach($object->fields as $key => $val) { $i++; - $texttoinsert.= "\t".$key." ".$val['type']; + + $type = $val['type']; + $type = preg_replace('/:.*$/', '', $type); // For case type = 'integer:Societe:societe/class/societe.class.php' + + $texttoinsert.= "\t".$key." ".$type; if ($key == 'rowid') $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY'; if ($key == 'entity') $texttoinsert.= ' DEFAULT 1'; + else + { + if ($val['default'] != '') + { + if (preg_match('/^null$/i', $val['default'])) $texttoinsert.= " DEFAULT NULL"; + else if (preg_match('/varchar/', $val['type'])) $texttoinsert.= " DEFAULT '".$db->escape($val['default'])."'"; + else $texttoinsert.= (($val['default'] > 0)?' DEFAULT '.$val['default']:''); + } + } $texttoinsert.= (($val['notnull'] > 0)?' NOT NULL':''); if ($i < count($object->fields)) $texttoinsert.=", "; $texttoinsert.= "\n"; @@ -274,8 +287,8 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir='', } // Edit .key.sql file - $pathoffiletoeditsrc=$destdir.'/sql/llx_'.strtolower($objectname).'.key.sql'; - $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($objectname).'.key.sql'.($readdir != $destdir ? '.new' : ''); + $pathoffiletoeditsrc=$destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.key.sql'; + $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.key.sql'.($readdir != $destdir ? '.new' : ''); $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r'); @@ -288,7 +301,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir='', $i++; if ($val['index']) { - $texttoinsert.= "ALTER TABLE llx_".strtolower($objectname)." ADD INDEX idx_".strtolower($objectname)."_".$key." (".$key.");"; + $texttoinsert.= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD INDEX idx_".strtolower($module).'_'.strtolower($objectname)."_".$key." (".$key.");"; $texttoinsert.= "\n"; } } diff --git a/htdocs/core/lib/order.lib.php b/htdocs/core/lib/order.lib.php index 5d9f9280cc8..92a11c907d4 100644 --- a/htdocs/core/lib/order.lib.php +++ b/htdocs/core/lib/order.lib.php @@ -61,10 +61,13 @@ function commande_prepare_head(Commande $object) if (($conf->expedition_bon->enabled && $user->rights->expedition->lire) || ($conf->livraison_bon->enabled && $user->rights->expedition->livraison->lire)) { + $nbShipments=$object->getNbOfShipments(); $nbReceiption=0; $head[$h][0] = DOL_URL_ROOT.'/expedition/shipment.php?id='.$object->id; if ($conf->expedition_bon->enabled) $text=$langs->trans("Shipments"); + if ($nbShipments > 0) $text.= ' '.$nbShipments.''; if ($conf->expedition_bon->enabled && $conf->livraison_bon->enabled) $text.='/'; if ($conf->livraison_bon->enabled) $text.=$langs->trans("Receivings"); + if ($nbReceiption > 0) $text.= ' '.$nbReceiption.''; $head[$h][1] = $text; $head[$h][2] = 'shipping'; $h++; diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php index aaaa0934890..3a398e50f69 100644 --- a/htdocs/core/lib/payments.lib.php +++ b/htdocs/core/lib/payments.lib.php @@ -99,7 +99,7 @@ function showOnlinePaymentUrl($type,$ref) { global $conf, $langs; - $langs->load("PAYMENT"); + $langs->load("payment"); $langs->load("paybox"); $servicename='Online'; @@ -110,7 +110,6 @@ function showOnlinePaymentUrl($type,$ref) return $out; } - /** * Return string with full Url * diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 99181d2c294..73df708ca27 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -590,16 +590,17 @@ function pdf_pagehead(&$pdf,$outputlangs,$page_height) /** - * Return array of possible substitutions for PDF content (without external module substitutions). + * Return array of possible substitutions for PDF content (without external module substitutions). * - * @param Translate $outputlangs Output language - * @param array $exclude Array of family keys we want to exclude. For example array('mycompany', 'object', 'date', 'user', ...) - * @param Object $object Object - * @return array Array of substitutions + * @param Translate $outputlangs Output language + * @param array $exclude Array of family keys we want to exclude. For example array('mycompany', 'object', 'date', 'user', ...) + * @param Object $object Object + * @param int $onlykey 1=Do not calculate some heavy values of keys (performance enhancement when we need only the keys), 2=Values are truncated and html sanitized (to use for help tooltip) + * @return array Array of substitutions */ -function pdf_getSubstitutionArray($outputlangs, $exclude=null, $object=null) +function pdf_getSubstitutionArray($outputlangs, $exclude=null, $object=null, $onlykey=0) { - $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, $exclude, $object); + $substitutionarray = getCommonSubstitutionArray($outputlangs, $onlykey, $exclude, $object); $substitutionarray['__FROM_NAME__']='__FROM_NAME__'; $substitutionarray['__FROM_EMAIL__']='__FROM_EMAIL__'; return $substitutionarray; @@ -1822,7 +1823,7 @@ function pdf_getlineremisepercent($object,$i,$outputlangs,$hidedetails=0) function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookmanager = null) { if (empty($hookmanager)) global $hookmanager; - + $reshook=0; $result=''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index b9c1eb1f1fb..2e1c58af27c 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -589,9 +589,10 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t * @param int $restricteditformytask 0=No restriction, 1=Enable add time only if task is a task i am affected to * @param int $preselectedday Preselected day * @param array $isavailable Array with data that say if user is available for several days for morning and afternoon + * @param int $oldprojectforbreak Old project id of last project break * @return $inc */ -function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, $preselectedday, &$isavailable) +function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, $preselectedday, &$isavailable, $oldprojectforbreak=0) { global $conf, $db, $user, $bc, $langs; global $form, $formother, $projectstatic, $taskstatic, $thirdpartystatic; @@ -611,7 +612,10 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr } } - $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_BREAK_ON_PROJECT)?0:-1); // 0 to start break , -1 no break + if (empty($oldprojectforbreak)) + { + $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:-1); // 0 to start break , -1 no break + } //dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); for ($i = 0 ; $i < $numlines ; $i++) @@ -776,7 +780,7 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $idw = 0; $tableCell=''; - $tableCell.=''; + $tableCell.=''; $tableCell.=' + '; //$tableCell.='   '; $tableCell.=$form->select_duration($lines[$i]->id.'duration','',$disabledtask,'text',0,1); @@ -818,8 +822,8 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $level++; if ($lines[$i]->id > 0) { - if ($parent == 0) projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable); - else projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable); + if ($parent == 0) projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable, $oldprojectforbreak); + else projectLinesPerDay($inc, $lines[$i]->id, $fuser, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable, $oldprojectforbreak); } $level--; } @@ -847,9 +851,10 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr * @param string $mine Show only task lines I am assigned to * @param int $restricteditformytask 0=No restriction, 1=Enable add time only if task is a task i am affected to * @param array $isavailable Array with data that say if user is available for several days for morning and afternoon + * @param int $oldprojectforbreak Old project id of last project break * @return $inc */ -function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, &$isavailable) +function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$level, &$projectsrole, &$tasksrole, $mine, $restricteditformytask, &$isavailable, $oldprojectforbreak=0) { global $conf, $db, $user, $bc, $langs; global $form, $formother, $projectstatic, $taskstatic, $thirdpartystatic; @@ -871,7 +876,10 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_BREAK_ON_PROJECT)?0:-1); // 0 = start break, -1 = never break + if (empty($oldprojectforbreak)) + { + $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:-1); // 0 = start break, -1 = never break + } for ($i = 0 ; $i < $numlines ; $i++) { @@ -1032,7 +1040,7 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $tableCell =''; $texte.= '
    '; + //$out.='
    '; + $help=""; + foreach($this->substit as $key => $val) + { + $help.=$key.' -> '.$langs->trans(dol_string_nohtmltag($val)).'
    '; + } + if (is_numeric($this->withsubstit)) $out.= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $help, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage + else $out.= $form->textwithpicto($langs->trans('AvailableVariables'), $help, 1, 'help', '', 0, 2, 'substittooltip'); // New usage + $out.= "
    '.$langs->trans("MailFrom").''; + + if (! ($this->fromtype === 'user' && $this->fromid > 0) + && ! ($this->fromtype === 'company') + && ! preg_match('/user_aliases/', $this->fromtype) + && ! preg_match('/global_aliases/', $this->fromtype) + && ! preg_match('/senderprofile/', $this->fromtype)) + { + // Use this->fromname and this->frommail or error if not defined + $out.= $this->fromname; + if ($this->frommail) + { + $out.= ' <'.$this->frommail.'>'; + } + else + { + if ($this->fromtype) + { + $langs->load('errors'); + $out.= ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'> '; + } + } + } else { + $liste = array(); + + // Add user email + if (empty($user->email)) + { + $langs->load('errors'); + $liste['user'] = $user->getFullName($langs) . ' <'.$langs->trans('ErrorNoMailDefinedForThisUser').'>'; + } + else + { + $liste['user'] = $user->getFullName($langs) .' <'.$user->email.'>'; + } + + // Add also company main email + $liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + + // Add also email aliases if there is some + $listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + + // Add also email aliases from the c_email_senderprofile table + $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1 ORDER BY position'; + $resql = $this->db->query($sql); + if ($resql) + { + $num = $this->db->num_rows($resql); + $i=0; + while($i < $num) + { + $obj = $this->db->fetch_object($resql); + if ($obj) + { + $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>'; + } + $i++; + } + } + else dol_print_error($this->db); + + foreach($listaliases as $typealias => $listalias) + { + $posalias=0; + $listaliasarray=explode(',', $listalias); + foreach ($listaliasarray as $listaliasval) + { + $posalias++; + $listaliasval=trim($listaliasval); + if ($listaliasval) + { + $listaliasval=preg_replace('//', '>', $listaliasval); + if (! preg_match('/</', $listaliasval)) $listaliasval='<'.$listaliasval.'>'; + $liste[$typealias.'_'.$posalias]=$listaliasval; + } + } + } + $out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', '', 0, '', $disablebademails); + //$out.= ajax_combobox('fromtype'); + } + + $out.= "
    '.$langs->trans("MailFrom").""; + $out.= $langs->trans("Name").':'; + $out.= '    '; + $out.= $langs->trans("EMail").':<>'; + $out.= "
    '; + if ($this->withtofree) $out.= $form->textwithpicto($langs->trans("MailTo"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); + else $out.= $langs->trans("MailTo"); + $out.= ''; + if ($this->withtoreadonly) + { + if (! empty($this->toname) && ! empty($this->tomail)) + { + $out.= ''; + $out.= ''; + if ($this->totype == 'thirdparty') + { + $soc=new Societe($this->db); + $soc->fetch($this->toid); + $out.= $soc->getNomUrl(1); + } + else if ($this->totype == 'contact') + { + $contact=new Contact($this->db); + $contact->fetch($this->toid); + $out.= $contact->getNomUrl(1); + } + else + { + $out.= $this->toname; + } + $out.= ' <'.$this->tomail.'>'; + if ($this->withtofree) + { + $out.= '
    '.$langs->trans("and").' withto) :"").'" />'; + } + } + else + { + // Note withto may be a text like 'AllRecipientSelected' + $out.= (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:""; + } + } + else + { + if (! empty($this->withtofree)) + { + $out.= 'withto) :"").'" />'; + } + if (! empty($this->withto) && is_array($this->withto)) + { + if (! empty($this->withtofree)) $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; + // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time + $tmparray = $this->withto; + foreach($tmparray as $key => $val) + { + $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); + } + $withtoselected=GETPOST("receiver",'none'); // Array of selected value + if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend') + { + $withtoselected = array_keys($tmparray); + } + $out.= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, ""); + } + } + $out.= "
    '; + $out.= $langs->trans("GroupEmails"); + $out.= ''; + $out.=' withoptiononeemailperrecipient > 0?' checked="checked"':'').'> '; + $out.= $langs->trans("OneEmailPerRecipient").' - '; + $out.= $langs->trans("WarningIfYouCheckOneRecipientPerEmail"); + $out.= '
    '; + $out.= $form->textwithpicto($langs->trans("MailCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); + $out.= ''; + if ($this->withtoccreadonly) + { + $out.= (! is_array($this->withtocc) && ! is_numeric($this->withtocc))?$this->withtocc:""; + } + else + { + $out.= 'withtocc) : (isset($_POST["sendtocc"])?$_POST["sendtocc"]:"") ).'" />'; + if (! empty($this->withtocc) && is_array($this->withtocc)) + { + $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; + // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time + $tmparray = $this->withtocc; + foreach($tmparray as $key => $val) + { + $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); + } + $withtoccselected=GETPOST("receivercc"); // Array of selected value + $out.= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500',null, ""); + } + } + $out.= "
    '; + $out.= $form->textwithpicto($langs->trans("MailCCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients")); + $out.= ''; + if (! empty($this->withtocccreadonly)) + { + $out.= (! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))?$this->withtoccc:""; + } + else + { + $out.= 'withtoccc) : (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:"") ).'" />'; + if (! empty($this->withtoccc) && is_array($this->withtoccc)) + { + $out.= " ".$langs->trans("and")."/".$langs->trans("or")." "; + // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time + $tmparray = $this->withtoccc; + foreach($tmparray as $key => $val) + { + $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true); + } + $withtocccselected=GETPOST("receiverccc"); // Array of selected value + $out.= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null,null, "90%"); + } } - $defaulttopic=make_substitutions($defaulttopic,$this->substit); + $showinfobcc=''; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO; + if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO; + if ($showinfobcc) $out.=' + '.$showinfobcc; + $out.= "
    '.$langs->trans("MailTopic").''; - if ($this->withtopicreadonly) - { - $out.= $defaulttopic; - $out.= ''; - } - else - { - $out.= ''; - } - $out.= "
    ".$langs->trans("MailReply")."".$this->replytoname.($this->replytomail?(" <".$this->replytomail.">"):""); + $out.= "
    '.$langs->trans("MailFile").'
    '.$langs->trans("MailErrorsTo").''; + $out.= $errorstomail; + $out.= "
    '.$langs->trans("MailErrorsTo").''; + $out.= ''; + $out.= "
    '; - if (! empty($this->withmaindocfile)) - { - if ($this->withmaindocfile == 1) - { - $out.=''; - } - if ($this->withmaindocfile == -1) - { - $out.=''; - } - $out.=' '.$langs->trans("JoinMainDoc").'.
    '; - } + // Ask delivery receipt + if (! empty($this->withdeliveryreceipt)) + { + $out.= '
    '.$langs->trans("DeliveryReceipt").''; - if (is_numeric($this->withfile)) - { + if (! empty($this->withdeliveryreceiptreadonly)) + { + $out.= yn($this->withdeliveryreceipt); + } + else + { + $defaultvaluefordeliveryreceipt=0; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $defaultvaluefordeliveryreceipt=1; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $defaultvaluefordeliveryreceipt=1; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $defaultvaluefordeliveryreceipt=1; + if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $defaultvaluefordeliveryreceipt=1; + $out.= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"])?$_POST["deliveryreceipt"]:$defaultvaluefordeliveryreceipt), 1); + } + + $out.= "
    '.$langs->trans("MailTopic").''; + if ($this->withtopicreadonly) + { + $out.= $defaulttopic; + $out.= ''; + } + else + { + $out.= ''; + } + $out.= "
    '.$langs->trans("MailFile").''; + if (! empty($this->withmaindocfile)) + { + if ($this->withmaindocfile == 1) + { + $out.=''; + } + if ($this->withmaindocfile == -1) + { + $out.=''; + } + $out.=' '.$langs->trans("JoinMainDoc").'.
    '; + } + + if (is_numeric($this->withfile)) + { // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript - $out.= ''."\n"; - $out.= ''."\n"; - if (count($listofpaths)) - { - foreach($listofpaths as $key => $val) - { - $out.= '
    '; - $out.= img_mime($listofnames[$key]).' '.$listofnames[$key]; - if (! $this->withfilereadonly) - { - $out.= ' '; - //$out.= ' '.img_delete($langs->trans("Delete").''; - } - $out.= '
    '; - } - } - else if (empty($this->withmaindocfile)) // Do not show message if we asked to show the checkbox - { - $out.= $langs->trans("NoAttachedFiles").'
    '; - } - if ($this->withfile == 2) // Can add other files - { - if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) $out.= ''; + $out.= ''."\n"; + $out.= ''."\n"; + if (count($listofpaths)) + { + foreach($listofpaths as $key => $val) + { + $out.= '
    '; + $out.= img_mime($listofnames[$key]).' '.$listofnames[$key]; + if (! $this->withfilereadonly) + { + $out.= ' '; + //$out.= ' '.img_delete($langs->trans("Delete").''; + } + $out.= '
    '; + } + } + else if (empty($this->withmaindocfile)) // Do not show message if we asked to show the checkbox + { + $out.= $langs->trans("NoAttachedFiles").'
    '; + } + if ($this->withfile == 2) // Can add other files + { + if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) $out.= ''; else $out.= ''; - $out.= ' '; - $out.= ''; - } - } - else - { - $out.=$this->withfile; - } + $out.= ' '; + $out.= ''; + } + } + else + { + $out.=$this->withfile; + } - $out.= "
    '; if ($alreadyspent) { - $tableCell.=''; + $tableCell.=''; //$placeholder=' placeholder="00:00"'; $placeholder=''; //$tableCell.='+'; @@ -1065,8 +1073,8 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $level++; if ($lines[$i]->id > 0) { - if ($parent == 0) projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable); - else projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable); + if ($parent == 0) projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lineswithoutlevel0, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak); + else projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, $lines, $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak); } $level--; } @@ -1147,6 +1155,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= $arrayidtypeofcontact=array(); + print '
    '; print ''; $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; @@ -1346,6 +1355,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks= } print "
    "; + print '
    '; if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) { diff --git a/htdocs/core/lib/security.lib.php b/htdocs/core/lib/security.lib.php index 11232f37ea7..fed22dafdfb 100644 --- a/htdocs/core/lib/security.lib.php +++ b/htdocs/core/lib/security.lib.php @@ -74,24 +74,24 @@ function dol_decode($chain) * If constant MAIN_SECURITY_SALT is defined, we use it as a salt. * * @param string $chain String to hash - * @param int $type Type of hash (0:auto, 1:sha1, 2:sha1+md5, 3:md5, 4:md5 for OpenLdap). Use 3 here, if hash is not needed for security purpose, for security need, prefer 0. + * @param string $type Type of hash ('0':auto, '1':sha1, '2':sha1+md5, '3':md5, '4':md5 for OpenLdap). Use '3' here, if hash is not needed for security purpose, for security need, prefer '0'. * @return string Hash of string */ -function dol_hash($chain,$type=0) +function dol_hash($chain, $type='0') { global $conf; // Salt value if (! empty($conf->global->MAIN_SECURITY_SALT)) $chain=$conf->global->MAIN_SECURITY_SALT.$chain; - if ($type == 1) return sha1($chain); - else if ($type == 2) return sha1(md5($chain)); - else if ($type == 3) return md5($chain); - else if ($type == 4) return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 (based on an unencrypted password in base) + if ($type == '1' || $type == 'sha1') return sha1($chain); + else if ($type == '2' || $type == 'sha1md5') return sha1(md5($chain)); + else if ($type == '3' || $type == 'md5') return md5($chain); + else if ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5,$chain)); // For OpenLdap with md5 (based on an unencrypted password in base) else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain); else if (! empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain)); - // No particular enconding defined, use default + // No particular encoding defined, use default return md5($chain); } @@ -387,8 +387,12 @@ function checkUserAccessToObject($user, $featuresarray, $objectid=0, $tableandsh $nocheck = array('barcode','stock','fournisseur'); // No test $checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...). - // If dbtable not defined, we use same name for table than module name - if (empty($dbtablename)) $dbtablename = $feature; + // If dbtablename not defined, we use same name for table than module name + if (empty($dbtablename)) + { + $dbtablename = $feature; + $sharedelement = (! empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too. + } // Check permission for object with entity if (in_array($feature,$check)) diff --git a/htdocs/core/lib/security2.lib.php b/htdocs/core/lib/security2.lib.php index 4d79b87122e..c526d57bee0 100644 --- a/htdocs/core/lib/security2.lib.php +++ b/htdocs/core/lib/security2.lib.php @@ -439,7 +439,7 @@ function encodedecode_dbpassconf($level=0) /** * Return a generated password using default module * - * @param boolean $generic true=Create generic password (use md5, sha1 depending on setup), false=Use the configured password generation module + * @param boolean $generic true=Create generic password (32 chars/numbers), false=Use the configured password generation module * @return string New value for password */ function getRandomPassword($generic=false) @@ -447,7 +447,48 @@ function getRandomPassword($generic=false) global $db,$conf,$langs,$user; $generated_password=''; - if ($generic) $generated_password=dol_hash(mt_rand()); + if ($generic) + { + $length = 32; + $lowercase = "qwertyuiopasdfghjklzxcvbnm"; + $uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP"; + $numbers = "1234567890"; + $randomCode = ""; + if (function_exists('random_int')) // Cryptographic random + { + $max = strlen($lowercase) - 1; + for ($x = 0; $x < abs($length/3); $x++) { + $randomCode .= $lowercase{random_int(0, $max)}; + } + $max = strlen($uppercase) - 1; + for ($x = 0; $x < abs($length/3); $x++) { + $randomCode .= $uppercase{random_int(0, $max)}; + } + $max = strlen($numbers) - 1; + for ($x = 0; $x < abs($length/3); $x++) { + $randomCode .= $numbers{random_int(0, $max)}; + } + + $generated_password=str_shuffle($randomCode); + } + else // Old platform, non cryptographic random + { + $max = strlen($lowercase) - 1; + for ($x = 0; $x < abs($length/3); $x++) { + $randomCode .= $lowercase{mt_rand(0, $max)}; + } + $max = strlen($uppercase) - 1; + for ($x = 0; $x < abs($length/3); $x++) { + $randomCode .= $uppercase{mt_rand(0, $max)}; + } + $max = strlen($numbers) - 1; + for ($x = 0; $x < abs($length/3); $x++) { + $randomCode .= $numbers{mt_rand(0, $max)}; + } + + $generated_password=str_shuffle($randomCode); + } + } else if (! empty($conf->global->USER_PASSWORD_GENERATED)) { $nomclass="modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED); diff --git a/htdocs/core/lib/signature.lib.php b/htdocs/core/lib/signature.lib.php new file mode 100644 index 00000000000..b11d809caf2 --- /dev/null +++ b/htdocs/core/lib/signature.lib.php @@ -0,0 +1,94 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +/** + * Return string with full Url + * + * @param string $type Type of URL ('proposal', ...) + * @param string $ref Ref of object + * @return string Url string + */ +function showOnlineSignatureUrl($type,$ref) +{ + global $conf, $langs; + + $langs->load("payment"); + $langs->load("paybox"); + $servicename='Online'; + + $out = img_picto('','object_globe.png').' '.$langs->trans("ToOfferALinkForOnlineSignature",$servicename).'
    '; + $url = getOnlineSignatureUrl(0, $type, $ref); + $out.= ''; + $out.= ajax_autoselect("onlinesignatureurl", 0); + return $out; +} + + +/** + * Return string with full Url + * + * @param int $mode 0=True url, 1=Url formated with colors + * @param string $type Type of URL ('proposal', ...) + * @param string $ref Ref of object + * @return string Url string + */ +function getOnlineSignatureUrl($mode, $type, $ref='') +{ + global $conf, $db, $langs; + + $ref=str_replace(' ','',$ref); + $out=''; + + if ($type == 'proposal') + { + $out=DOL_MAIN_URL_ROOT.'/public/onlinesign/newonlinesign.php?source=proposal&ref='.($mode?'':''); + if ($mode == 1) $out.='proposal_ref'; + if ($mode == 0) $out.=urlencode($ref); + $out.=($mode?'':''); + if ($mode == 1) $out.='&hashp=hash_of_file'; + else + { + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + $propaltmp=new Propal($db); + $res = $propaltmp->fetch(0, $ref); + if ($res <= 0) return 'FailedToGetProposal'; + + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($db); + + $ecmfile->fetch(0, '', $propaltmp->last_main_doc); + + $hashp=$ecmfile->share; + if (empty($hashp)) + { + $out = $langs->trans("FeatureOnlineSignDisabled"); + return $out; + } + else + { + $out.='&hashp='.$hashp; + } + } + } + + // For multicompany + if (! empty($out)) $out.="&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities + + return $out; +} diff --git a/htdocs/core/lib/usergroups.lib.php b/htdocs/core/lib/usergroups.lib.php index 8f73678a532..afce2644124 100644 --- a/htdocs/core/lib/usergroups.lib.php +++ b/htdocs/core/lib/usergroups.lib.php @@ -60,19 +60,19 @@ function user_prepare_head($object) $h++; } + if ($canreadperms) + { + $head[$h][0] = DOL_URL_ROOT.'/user/perms.php?id='.$object->id; + $head[$h][1] = $langs->trans("Rights"). ' '.($object->nb_rights).''; + $head[$h][2] = 'rights'; + $h++; + } + $head[$h][0] = DOL_URL_ROOT.'/user/param_ihm.php?id='.$object->id; $head[$h][1] = $langs->trans("UserGUISetup"); $head[$h][2] = 'guisetup'; $h++; - if ($canreadperms) - { - $head[$h][0] = DOL_URL_ROOT.'/user/perms.php?id='.$object->id; - $head[$h][1] = $langs->trans("UserRights"). ' '.($object->nb_rights).''; - $head[$h][2] = 'rights'; - $h++; - } - if (! empty($conf->agenda->enabled)) { if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB=5; diff --git a/htdocs/core/lib/website.lib.php b/htdocs/core/lib/website.lib.php index 806d5d7a640..1810e32868f 100644 --- a/htdocs/core/lib/website.lib.php +++ b/htdocs/core/lib/website.lib.php @@ -22,8 +22,40 @@ */ + +/** + * Convert a page content to have correct links (based on DOL_URL_ROOT) into an html content. + * Used to ouput the page on the Preview. + * + * @param Website $website Web site object + * @param string $content Content to replace + * @return boolean True if OK + */ +function dolWebsiteReplacementOfLinks($website, $content) +{ + // Replace php code. Note $content may come from database and does not contains body tags. + $content = preg_replace('/<\?php((?!\?>).)*\?>\n*/ims', '...php...', $content); + + // Replace relative link / with dolibarr URL + $content = preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep); + // Replace relative link /xxx.php with dolibarr URL + $content = preg_replace('/(href=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); + + $content = preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); + + // ]*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); + + // action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage + $content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); + + return $content; +} + + /** * Render a string of an HTML content and output it. + * Used to ouput the page when viewed from server (Dolibarr or Apache). * * @param string $content Content string * @return void @@ -43,7 +75,27 @@ function dolWebsiteOutput($content) // Note: This seems never called when page is output inside the website editor (search 'REPLACEMENT OF LINKS When page called by website editor') - if (! defined('USEDOLIBARRSERVER')) // REPLACEMENT OF LINKS When page called from virtual host + if (defined('USEDOLIBARRSERVER')) // REPLACEMENT OF LINKS When page called from Dolibarr server + { + global $website; + + // Replace relative link / with dolibarr URL: ...href="/"... + $content=preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep); + // Replace relative link /xxx.php with dolibarr URL: ...href="....php" + $content=preg_replace('/(href=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); + + // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: ...href="/document.php?modulepart=" + $content=preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); + // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: ...href="/viewimage.php?modulepart=" + $content=preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); + + // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/ + $content=preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); + + // action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage + $content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); + } + else // REPLACEMENT OF LINKS When page called from virtual host { $symlinktomediaexists=1; @@ -63,23 +115,6 @@ function dolWebsiteOutput($content) $content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1medias/\4\5', $content, -1, $nbrep); } } - else // REPLACEMENT OF LINKS When page called from dolibarr server - { - global $website; - - // Replace relative link / with dolibarr URL: ...href="/"... - $content=preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep); - // Replace relative link /xxx.php with dolibarr URL: ...href="....php" - $content=preg_replace('/(href=")\/?([^\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); - - // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: ...href="/document.php?modulepart=" - $content=preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); - // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: ...href="/viewimage.php?modulepart=" - $content=preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep); - - // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/ - $content=preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); - } dol_syslog("dolWebsiteOutput end"); @@ -87,33 +122,6 @@ function dolWebsiteOutput($content) } -/** - * Convert a page content to have correct links into a new html content. - * Used to ouput the page on the Preview. - * - * @param Website $website Web site object - * @param string $content Content to replace - * @return boolean True if OK - */ -function dolWebsiteReplacementOfLinks($website, $content) -{ - // Replace php code. Note $content may come from database and does not contains body tags. - $content = preg_replace('/<\?php[^\?]+\?>\n*/ims', '...php...', $content); - - // Replace relative link / with dolibarr URL - $content = preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/websites/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep); - // Replace relative link /xxx.php with dolibarr URL - $content = preg_replace('/(href=")\/?([^\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/websites/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep); - - $content = preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); - - // ]*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep); - - return $content; -} - - /** * Format img tags to introduce viewimage on img src. * @@ -155,7 +163,7 @@ function dolIncludeHtmlContent($contentfile) $MAXLEVEL=20; - $fullpathfile=DOL_DATA_ROOT.'/websites/'.$contentfile; + $fullpathfile=DOL_DATA_ROOT.'/website/'.$contentfile; if (empty($includehtmlcontentopened)) $includehtmlcontentopened=0; $includehtmlcontentopened++; @@ -188,29 +196,29 @@ function dolIncludeHtmlContent($contentfile) * Generate a zip with all data of web site. * * @param Website $website Object website - * @return void + * @return string Path to file with zip */ function exportWebSite($website) { global $db, $conf; - dol_mkdir($conf->websites->dir_temp); - $srcdir = $conf->websites->dir_output.'/'.$website->ref; - $destdir = $conf->websites->dir_temp.'/'.$website->ref; + dol_mkdir($conf->website->dir_temp); + $srcdir = $conf->website->dir_output.'/'.$website->ref; + $destdir = $conf->website->dir_temp.'/'.$website->ref; $arrayreplacement=array(); dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement); $srcdir = DOL_DATA_ROOT.'/medias/images/'.$website->ref; - $destdir = $conf->websites->dir_temp.'/'.$website->ref.'/medias/images/'.$website->ref; + $destdir = $conf->website->dir_temp.'/'.$website->ref.'/medias/images/'.$website->ref; dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement); // Build sql file - dol_mkdir($conf->websites->dir_temp.'/'.$website->ref.'/export'); + dol_mkdir($conf->website->dir_temp.'/'.$website->ref.'/export'); - $filesql = $conf->websites->dir_temp.'/'.$website->ref.'/export/pages.sql'; + $filesql = $conf->website->dir_temp.'/'.$website->ref.'/export/pages.sql'; $fp = fopen($filesql,"w"); $objectpages = new WebsitePage($db); @@ -267,9 +275,9 @@ function exportWebSite($website) @chmod($filesql, octdec($conf->global->MAIN_UMASK)); // Build zip file - $filedir = $conf->websites->dir_temp.'/'.$website->ref; - $fileglob = $conf->websites->dir_temp.'/'.$website->ref.'/export/'.$website->ref.'_export_*.zip'; - $filename = $conf->websites->dir_temp.'/'.$website->ref.'/export/'.$website->ref.'_export_'.dol_print_date(dol_now(),'dayhourlog').'.zip'; + $filedir = $conf->website->dir_temp.'/'.$website->ref; + $fileglob = $conf->website->dir_temp.'/'.$website->ref.'/export/website_'.$website->ref.'-*.zip'; + $filename = $conf->website->dir_temp.'/'.$website->ref.'/export/website_'.$website->ref.'-'.dol_print_date(dol_now(),'dayhourlog').'.zip'; dol_delete_file($fileglob, 0); dol_compress_file($filedir, $filename, 'zip'); @@ -278,6 +286,35 @@ function exportWebSite($website) } +/** + * Open a zip with all data of web site and load it into database. + * + * @param string $pathtofile Path of zip file + * @return int <0 if KO, >0 if OK + */ +function importWebSite($pathtofile) +{ + global $db; + + $result = 0; + + $filename = basename($pathtofile); + if (! preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) + { + $this->errors[]='Bad format for filename '.$filename.'. Must be website_XXX-VERSION.'; + return -1; + } + + $websitecode = $reg[1]; + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."website(ref, entity, description, status) values('".$websitecode."', ".$conf->entity.", 'Portal to sell your SaaS. Do not remove this entry.', 1)"; + $resql = $db->query($sql); + + + return $result; +} + + /** * Download all images found into page content $tmp. * If $modifylinks is set, links to images will be replace with a link to viewimage wrapper. diff --git a/htdocs/core/lib/xcal.lib.php b/htdocs/core/lib/xcal.lib.php index 14cda539291..b0a30697413 100644 --- a/htdocs/core/lib/xcal.lib.php +++ b/htdocs/core/lib/xcal.lib.php @@ -68,7 +68,7 @@ function build_calfile($format,$title,$desc,$events_array,$outputfile) fwrite($calfileh,"X-PUBLISHED-TTL: P".$hh."H".$mm."M".$ss."S\n"); } - foreach ($events_array as $date => $event) + foreach ($events_array as $key => $event) { $eventqualified=true; if ($eventqualified) @@ -335,7 +335,7 @@ function build_rssfile($format,$title,$desc,$events_array,$outputfile,$filter='' fwrite($fichier, $form); - foreach ($events_array as $date => $event) + foreach ($events_array as $key => $event) { $eventqualified=true; if ($filter) diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql index 33039b390fd..1ad0a76a203 100644 --- a/htdocs/core/menus/init_menu_auguria.sql +++ b/htdocs/core/menus/init_menu_auguria.sql @@ -154,11 +154,11 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled', __HANDLER__, 'left', 1400__+MAX_llx_menu__, 'commercial', 'contracts', 5__+MAX_llx_menu__, '/contrat/index.php?leftmenu=contracts', 'Contracts', 0, 'contracts', '$user->rights->contrat->lire', '', 2, 7, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled', __HANDLER__, 'left', 1401__+MAX_llx_menu__, 'commercial', '', 1400__+MAX_llx_menu__, '/contrat/card.php?&action=create&leftmenu=contracts', 'NewContract', 1, 'contracts', '$user->rights->contrat->creer', '', 2, 0, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled', __HANDLER__, 'left', 1402__+MAX_llx_menu__, 'commercial', '', 1400__+MAX_llx_menu__, '/contrat/list.php?leftmenu=contracts', 'List', 1, 'contracts', '$user->rights->contrat->lire', '', 2, 1, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled', __HANDLER__, 'left', 1403__+MAX_llx_menu__, 'commercial', '', 1400__+MAX_llx_menu__, '/contrat/services.php?leftmenu=contracts', 'MenuServices', 1, 'contracts', '$user->rights->contrat->lire', '', 2, 2, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1404__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services.php?leftmenu=contracts&mode=0', 'MenuInactiveServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 0, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1405__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services.php?leftmenu=contracts&mode=4', 'MenuRunningServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 1, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1406__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services.php?leftmenu=contracts&mode=4&filter=expired', 'MenuExpiredServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 2, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1407__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services.php?leftmenu=contracts&mode=5', 'MenuClosedServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 3, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled', __HANDLER__, 'left', 1403__+MAX_llx_menu__, 'commercial', '', 1400__+MAX_llx_menu__, '/contrat/services_list.php?leftmenu=contracts', 'MenuServices', 1, 'contracts', '$user->rights->contrat->lire', '', 2, 2, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1404__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services_list.php?leftmenu=contracts&mode=0', 'MenuInactiveServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 0, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1405__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services_list.php?leftmenu=contracts&mode=4', 'MenuRunningServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 1, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1406__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services_list.php?leftmenu=contracts&mode=4&filter=expired', 'MenuExpiredServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 2, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->contrat->enabled && $leftmenu=="contracts"', __HANDLER__, 'left', 1407__+MAX_llx_menu__, 'commercial', '', 1403__+MAX_llx_menu__, '/contrat/services_list.php?leftmenu=contracts&mode=5', 'MenuClosedServices', 2, 'contracts', '$user->rights->contrat->lire', '', 2, 3, __ENTITY__); -- Commercial - Interventions insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->ficheinter->enabled', __HANDLER__, 'left', 1500__+MAX_llx_menu__, 'commercial', 'ficheinter', 5__+MAX_llx_menu__, '/fichinter/list.php?leftmenu=ficheinter', 'Interventions', 0, 'interventions', '$user->rights->ficheinter->lire', '', 2, 8, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->ficheinter->enabled', __HANDLER__, 'left', 1501__+MAX_llx_menu__, 'commercial', '', 1500__+MAX_llx_menu__, '/fichinter/card.php?action=create&leftmenu=ficheinter', 'NewIntervention', 1, 'interventions', '$user->rights->ficheinter->creer', '', 2, 0, __ENTITY__); @@ -209,9 +209,9 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->tax->enabled && empty($conf->global->TAX_DISABLE_VAT_MENUS) && $leftmenu=="tax_vat"', __HANDLER__, 'left', 2302__+MAX_llx_menu__, 'billing', '', 2300__+MAX_llx_menu__, '/compta/tva/reglement.php?leftmenu=tax_vat', 'List', 2, 'companies', '$user->rights->tax->charges->lire', '', 0, 1, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->tax->enabled && empty($conf->global->TAX_DISABLE_VAT_MENUS) && $leftmenu=="tax_vat"', __HANDLER__, 'left', 2303__+MAX_llx_menu__, 'billing', '', 2300__+MAX_llx_menu__, '/compta/tva/clients.php?leftmenu=tax_vat', 'ReportByCustomers', 2, 'companies', '$user->rights->tax->charges->lire', '', 0, 2, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->tax->enabled && empty($conf->global->TAX_DISABLE_VAT_MENUS) && $leftmenu=="tax_vat"', __HANDLER__, 'left', 2304__+MAX_llx_menu__, 'billing', '', 2300__+MAX_llx_menu__, '/compta/tva/quadri_detail.php?leftmenu=tax_vat', 'ReportByQuarter', 2, 'companies', '$user->rights->tax->charges->lire', '', 0, 3, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled', __HANDLER__, 'left', 2350__+MAX_llx_menu__, 'billing', 'tax_various', 2200__+MAX_llx_menu__, '/bank/various_payment/index.php?leftmenu=tax_various&mainmenu=billing', 'MenuVariousPayment', 1, 'banks', '$user->rights->banque->lire', '', 0, 1, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && $leftmenu=="tax_various"', __HANDLER__, 'left', 2351__+MAX_llx_menu__, 'billing', '', 2350__+MAX_llx_menu__, '/bank/various_payment/card.php?leftmenu=tax_various&action=create', 'MenuNewVariousPayment', 2, 'various_payment', '$user->rights->banque->modifier', '', 0, 2, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && $leftmenu=="tax_various"', __HANDLER__, 'left', 2352__+MAX_llx_menu__, 'billing', '', 2350__+MAX_llx_menu__, '/bank/various_payment/index.php?leftmenu=tax_various', 'List', 2, 'various_payment', '$user->rights->banque->lire', '', 0, 3, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled', __HANDLER__, 'left', 2350__+MAX_llx_menu__, 'billing', 'tax_various', 2200__+MAX_llx_menu__, '/compta/bank/various_payment/index.php?leftmenu=tax_various&mainmenu=billing', 'MenuVariousPayment', 1, 'banks', '$user->rights->banque->lire', '', 0, 1, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && $leftmenu=="tax_various"', __HANDLER__, 'left', 2351__+MAX_llx_menu__, 'billing', '', 2350__+MAX_llx_menu__, '/compta/bank/various_payment/card.php?leftmenu=tax_various&action=create', 'MenuNewVariousPayment', 2, 'various_payment', '$user->rights->banque->modifier', '', 0, 2, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->banque->enabled && $leftmenu=="tax_various"', __HANDLER__, 'left', 2352__+MAX_llx_menu__, 'billing', '', 2350__+MAX_llx_menu__, '/compta/bank/various_payment/index.php?leftmenu=tax_various', 'List', 2, 'various_payment', '$user->rights->banque->lire', '', 0, 3, __ENTITY__); -- Accounting Expert insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', '$conf->accounting->enabled', __HANDLER__, 'left', 2400__+MAX_llx_menu__, 'accountancy', 'accountancy', 9__+MAX_llx_menu__, '/accountancy/index.php?leftmenu=accountancy', 'MenuAccountancy', 0, 'accountancy', '! empty($conf->accounting->enabled) || $user->rights->accounting->bind->write || $user->rights->accounting->bind->write || $user->rights->compta->resultat->lire', '', 0, 7, __ENTITY__); -- Setup diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 3af93cbcbf6..9e88767f473 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -182,7 +182,7 @@ function print_eldy_menu($db,$atarget,$type_user,&$tabMenu,&$menu,$noout=0,$mode else $classname = 'class="tmenu"'; $idsel='accountancy'; - $menu->add('/accountancy/index.php?mainmenu=accountancy&leftmenu=', $langs->trans("Accountancy"), 0, $showmode, $atarget, "accountancy", '', 52, $id, $idsel, $classname); + $menu->add('/accountancy/index.php?mainmenu=accountancy&leftmenu=', $langs->trans("MenuAccountancy"), 0, $showmode, $atarget, "accountancy", '', 52, $id, $idsel, $classname); } @@ -768,11 +768,11 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu $newmenu->add("/contrat/index.php?leftmenu=contracts", $langs->trans("ContractsSubscriptions"), 0, $user->rights->contrat->lire, '', $mainmenu, 'contracts', 2000); $newmenu->add("/contrat/card.php?action=create&leftmenu=contracts", $langs->trans("NewContractSubscription"), 1, $user->rights->contrat->creer); $newmenu->add("/contrat/list.php?leftmenu=contracts", $langs->trans("List"), 1, $user->rights->contrat->lire); - $newmenu->add("/contrat/services.php?leftmenu=contracts", $langs->trans("MenuServices"), 1, $user->rights->contrat->lire); - if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=0", $langs->trans("MenuInactiveServices"), 2, $user->rights->contrat->lire); - if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=4", $langs->trans("MenuRunningServices"), 2, $user->rights->contrat->lire); - if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=4&filter=expired", $langs->trans("MenuExpiredServices"), 2, $user->rights->contrat->lire); - if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services.php?leftmenu=contracts&mode=5", $langs->trans("MenuClosedServices"), 2, $user->rights->contrat->lire); + $newmenu->add("/contrat/services_list.php?leftmenu=contracts", $langs->trans("MenuServices"), 1, $user->rights->contrat->lire); + if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services_list.php?leftmenu=contracts&mode=0", $langs->trans("MenuInactiveServices"), 2, $user->rights->contrat->lire); + if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services_list.php?leftmenu=contracts&mode=4", $langs->trans("MenuRunningServices"), 2, $user->rights->contrat->lire); + if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services_list.php?leftmenu=contracts&mode=4&filter=expired", $langs->trans("MenuExpiredServices"), 2, $user->rights->contrat->lire); + if ($usemenuhider || empty($leftmenu) || $leftmenu=="contracts") $newmenu->add("/contrat/services_list.php?leftmenu=contracts&mode=5", $langs->trans("MenuClosedServices"), 2, $user->rights->contrat->lire); } // Interventions diff --git a/htdocs/core/modules/DolibarrModules.class.php b/htdocs/core/modules/DolibarrModules.class.php index c42fabcc937..32240f778d2 100644 --- a/htdocs/core/modules/DolibarrModules.class.php +++ b/htdocs/core/modules/DolibarrModules.class.php @@ -553,10 +553,10 @@ class DolibarrModules // Can not be abstract, because we need to insta global $langs; $langs->load("admin"); - if ($langs->trans("Module".$this->numero."Name") != ("Module".$this->numero."Name")) + if ($langs->transnoentitiesnoconv("Module".$this->numero."Name") != ("Module".$this->numero."Name")) { // If module name translation exists - return $langs->trans("Module".$this->numero."Name"); + return $langs->transnoentitiesnoconv("Module".$this->numero."Name"); } else { @@ -572,11 +572,11 @@ class DolibarrModules // Can not be abstract, because we need to insta if ($langs->trans("Module".$this->name."Name") != ("Module".$this->name."Name")) { // If module name translation exists - return $langs->trans("Module".$this->name."Name"); + return $langs->transnoentitiesnoconv("Module".$this->name."Name"); } - // Last change with simple product label - return $langs->trans($this->name); + // Last chance with simple label + return $langs->transnoentitiesnoconv($this->name); } } @@ -591,10 +591,10 @@ class DolibarrModules // Can not be abstract, because we need to insta global $langs; $langs->load("admin"); - if ($langs->trans("Module".$this->numero."Desc") != ("Module".$this->numero."Desc")) + if ($langs->transnoentitiesnoconv("Module".$this->numero."Desc") != ("Module".$this->numero."Desc")) { // If module description translation exists - return $langs->trans("Module".$this->numero."Desc"); + return $langs->transnoentitiesnoconv("Module".$this->numero."Desc"); } else { @@ -606,6 +606,14 @@ class DolibarrModules // Can not be abstract, because we need to insta if ($val) $langs->load($val); } } + + if ($langs->transnoentitiesnoconv("Module".$this->name."Desc") != ("Module".$this->name."Desc")) + { + // If module name translation exists + return $langs->trans("Module".$this->name."Desc"); + } + + // Last chance with simple label return $langs->trans($this->description); } } @@ -657,7 +665,7 @@ class DolibarrModules // Can not be abstract, because we need to insta } } - $content = $langs->trans($this->descriptionlong); + $content = $langs->transnoentitiesnoconv($this->descriptionlong); } } @@ -671,16 +679,27 @@ class DolibarrModules // Can not be abstract, because we need to insta */ function getDescLongReadmeFound() { + global $langs; + $filefound= false; // Define path to file README.md. - // First check README-la_LA.md then README.md + // First check README-la_LA.md then README-la.md then README.md $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$langs->defaultlang.'.md', 0); if (dol_is_file($pathoffile)) { $filefound = true; } if (! $filefound) + { + $tmp=explode('_', $langs->defaultlang); + $pathoffile = dol_buildpath(strtolower($this->name).'/README-'.$tmp[0].'.md', 0); + if (dol_is_file($pathoffile)) + { + $filefound = true; + } + } + if (! $filefound) { $pathoffile = dol_buildpath(strtolower($this->name).'/README.md', 0); if (dol_is_file($pathoffile)) @@ -778,13 +797,13 @@ class DolibarrModules // Can not be abstract, because we need to insta $ret=''; $newversion=preg_replace('/_deprecated/','',$this->version); - if ($newversion == 'experimental') $ret=($translated?$langs->trans("VersionExperimental"):$newversion); - elseif ($newversion == 'development') $ret=($translated?$langs->trans("VersionDevelopment"):$newversion); + if ($newversion == 'experimental') $ret=($translated?$langs->transnoentitiesnoconv("VersionExperimental"):$newversion); + elseif ($newversion == 'development') $ret=($translated?$langs->transnoentitiesnoconv("VersionDevelopment"):$newversion); elseif ($newversion == 'dolibarr') $ret=DOL_VERSION; elseif ($newversion) $ret=$newversion; - else $ret=($translated?$langs->trans("VersionUnknown"):'unknown'); + else $ret=($translated?$langs->transnoentitiesnoconv("VersionUnknown"):'unknown'); - if (preg_match('/_deprecated/',$this->version)) $ret.=($translated?' ('.$langs->trans("Deprecated").')':$this->version); + if (preg_match('/_deprecated/',$this->version)) $ret.=($translated?' ('.$langs->transnoentitiesnoconv("Deprecated").')':$this->version); return $ret; } @@ -855,12 +874,12 @@ class DolibarrModules // Can not be abstract, because we need to insta if ($langs->trans($langstring) == $langstring) { // Translation not found - return $langs->trans($this->import_label[$r]); + return $langs->transnoentitiesnoconv($this->import_label[$r]); } else { // Translation found - return $langs->trans($langstring); + return $langs->transnoentitiesnoconv($langstring); } } @@ -1843,7 +1862,7 @@ class DolibarrModules // Can not be abstract, because we need to insta $menu->langs=$this->menu[$key]['langs']; $menu->position=$this->menu[$key]['position']; $menu->perms=$this->menu[$key]['perms']; - $menu->target=$this->menu[$key]['target']; + $menu->target=isset($this->menu[$key]['target'])?$this->menu[$key]['target']:''; $menu->user=$this->menu[$key]['user']; $menu->enabled=isset($this->menu[$key]['enabled'])?$this->menu[$key]['enabled']:0; $menu->position=$this->menu[$key]['position']; diff --git a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php index f5ab606f404..45568f5eadf 100644 --- a/htdocs/core/modules/commande/doc/pdf_einstein.modules.php +++ b/htdocs/core/modules/commande/doc/pdf_einstein.modules.php @@ -56,6 +56,11 @@ class pdf_einstein extends ModelePDFCommandes */ public $description; + /** + * @var int Save the name of generated file as the main doc when generating a doc with this template + */ + public $update_main_doc_field; + /** * @var string document type */ @@ -100,8 +105,9 @@ class pdf_einstein extends ModelePDFCommandes $this->db = $db; $this->name = "einstein"; $this->description = $langs->trans('PDFEinsteinDescription'); + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template - // Dimension page pour format A4 + // Dimension page $this->type = 'pdf'; $formatarray=pdf_getFormat(); $this->page_largeur = $formatarray['width']; @@ -599,7 +605,7 @@ class pdf_einstein extends ModelePDFCommandes @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - + return 1; // Pas d'erreur } else diff --git a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php index 2d5a27bb3df..f5d6ec70f04 100644 --- a/htdocs/core/modules/facture/doc/pdf_crabe.modules.php +++ b/htdocs/core/modules/facture/doc/pdf_crabe.modules.php @@ -45,6 +45,7 @@ class pdf_crabe extends ModelePDFFactures var $db; var $name; var $description; + var $update_main_doc_field; // Save the name of generated file as the main doc when generating a doc with this template var $type; var $phpmin = array(4,3,0); // Minimum version of PHP required by module @@ -86,7 +87,9 @@ class pdf_crabe extends ModelePDFFactures $this->db = $db; $this->name = "crabe"; $this->description = $langs->trans('PDFCrabeDescription'); + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template + // Dimensiont page $this->type = 'pdf'; $formatarray=pdf_getFormat(); $this->page_largeur = $formatarray['width']; @@ -702,7 +705,7 @@ class pdf_crabe extends ModelePDFFactures @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - + return 1; // No error } else diff --git a/htdocs/core/modules/modExpenseReport.class.php b/htdocs/core/modules/modExpenseReport.class.php index 087828b6cc4..4d84c0a6d05 100644 --- a/htdocs/core/modules/modExpenseReport.class.php +++ b/htdocs/core/modules/modExpenseReport.class.php @@ -102,7 +102,7 @@ class modExpenseReport extends DolibarrModules $r++; // Array to add new pages in new tabs - $this->tabs = array(); + $this->tabs[] = array('data'=>'user:+expensereport:ExpenseReport:expensereport:$user->rights->expensereport->lire:/expensereport/list.php?mainmenu=hrm&id=__ID__'); // To add a new tab identified by code tabname1 // Boxes $this->boxes = array(); // List of boxes diff --git a/htdocs/core/modules/modHoliday.class.php b/htdocs/core/modules/modHoliday.class.php index d57800872fd..75bb6a04a07 100644 --- a/htdocs/core/modules/modHoliday.class.php +++ b/htdocs/core/modules/modHoliday.class.php @@ -91,26 +91,7 @@ class modHoliday extends DolibarrModules $this->const = array(); // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 0 or 'allentities') // Array to add new pages in new tabs - // Example: $this->tabs = array('objecttype:+tabname1:Title1:@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__', // To add a new tab identified by code tabname1 - // 'objecttype:+tabname2:Title2:@mymodule:$user->rights->othermodule->read:/mymodule/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2 - // 'objecttype:-tabname'); // To remove an existing tab identified by code tabname - // where objecttype can be - // 'thirdparty' to add a tab in third party view - // 'intervention' to add a tab in intervention view - // 'order_supplier' to add a tab in supplier order view - // 'invoice_supplier' to add a tab in supplier invoice view - // 'invoice' to add a tab in customer invoice view - // 'order' to add a tab in customer order view - // 'product' to add a tab in product view - // 'stock' to add a tab in stock view - // 'propal' to add a tab in propal view - // 'member' to add a tab in fundation member view - // 'contract' to add a tab in contract view - // 'user' to add a tab in user view - // 'group' to add a tab in group view - // 'contact' to add a tab in contact view - // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) - $this->tabs = array('user:+paidholidays:CPTitreMenu:holiday:$user->rights->holiday->read:/holiday/list.php?mainmenu=hrm&id=__ID__'); + $this->tabs[] = array('data'=>'user:+paidholidays:CPTitreMenu:holiday:$user->rights->holiday->read:/holiday/list.php?mainmenu=hrm&id=__ID__'); // To add a new tab identified by code tabname1 // Boxes $this->boxes = array(); // List of boxes diff --git a/htdocs/core/modules/modResource.class.php b/htdocs/core/modules/modResource.class.php index 7ab7afc1e4b..dd09b148453 100644 --- a/htdocs/core/modules/modResource.class.php +++ b/htdocs/core/modules/modResource.class.php @@ -226,7 +226,7 @@ class modResource extends DolibarrModules 'type'=> 'left', // Toujours un menu gauche 'titre'=> 'MenuResourceAdd', 'mainmenu'=> 'tools', - 'leftmenu'=> '', // On n'indique rien ici car on ne souhaite pas intégrer de sous-menus à ce menu + 'leftmenu'=> 'resource_add', 'url'=> '/resource/add.php', 'langs'=> 'resource', 'position'=> 101, @@ -241,7 +241,7 @@ class modResource extends DolibarrModules 'type'=> 'left', // Toujours un menu gauche 'titre'=> 'List', 'mainmenu'=> 'tools', - 'leftmenu'=> '', // On n'indique rien ici car on ne souhaite pas intégrer de sous-menus à ce menu + 'leftmenu'=> 'resource_list', 'url'=> '/resource/list.php', 'langs'=> 'resource', 'position'=> 102, @@ -255,7 +255,7 @@ class modResource extends DolibarrModules // Exports //-------- $r=0; - + $r++; $this->export_code[$r]=$this->rights_class.'_'.$r; $this->export_label[$r]="ResourceSingular"; // Translation key (used only if key ExportDataset_xxx_z not found) @@ -265,19 +265,19 @@ class modResource extends DolibarrModules $this->export_entities_array[$r]=array('r.rowid'=>'resource','r.ref'=>'resource','c.code'=>'resource','c.label'=>'resource','r.description'=>'resource','r.note_private'=>"resource",'r.resource'=>"resource",'r.asset_number'=>'resource','r.datec'=>"resource",'r.tms'=>"resource"); $keyforselect='resource'; $keyforelement='resource'; $keyforaliasextra='extra'; include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; - + $this->export_dependencies_array[$r]=array('resource'=>array('r.rowid')); // We must keep this until the aggregate_array is used. To add unique key if we ask a field of a child to avoid the DISTINCT to discard them. $this->export_sql_start[$r]='SELECT DISTINCT '; $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'resource as r '; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_resource as c ON c.rowid=r.fk_code_type_resource'; $this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'resource_extrafields as extra ON extra.fk_object = c.rowid'; $this->export_sql_end[$r] .=' AND r.entity IN ('.getEntity('resource').')'; - + // Imports //-------- $r=0; - + // Import list of third parties and attributes $r++; $this->import_code[$r]=$this->rights_class.'_'.$r; @@ -307,7 +307,7 @@ class modResource extends DolibarrModules $this->import_regex_array[$r]=array('s.datec'=>'^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]( [0-9][0-9]:[0-9][0-9]:[0-9][0-9])?$'); $this->import_examplevalues_array[$r]=array('r.ref'=>"REF1",'r.fk_code_type_resource'=>"Code from dictionary resource type",'r.datec'=>"2017-01-01 or 2017-01-01 12:30:00"); $this->import_updatekeys_array[$r]=array('r.rf'=>'ResourceFormLabel_ref'); - + } /** diff --git a/htdocs/core/modules/modStock.class.php b/htdocs/core/modules/modStock.class.php index 8362343f8cb..e31b15d81dd 100644 --- a/htdocs/core/modules/modStock.class.php +++ b/htdocs/core/modules/modStock.class.php @@ -118,59 +118,59 @@ class modStock extends DolibarrModules $this->rights[4][5] = 'creer'; if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - + $this->rights[5][0] = 1011; $this->rights[5][1] = 'inventoryReadPermission'; // Permission label $this->rights[5][3] = 0; // Permission by default for new user (0/1) $this->rights[5][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) $this->rights[5][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - + $this->rights[6][0] = 1012; $this->rights[6][1] = 'inventoryCreatePermission'; // Permission label $this->rights[6][3] = 0; // Permission by default for new user (0/1) $this->rights[6][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) $this->rights[6][5] = 'create'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - + $this->rights[7][0] = 1013; $this->rights[7][1] = 'inventoryWritePermission'; // Permission label $this->rights[7][3] = 0; // Permission by default for new user (0/1) $this->rights[7][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) $this->rights[7][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - + $this->rights[8][0] = 1014; $this->rights[8][1] = 'inventoryValidatePermission'; // Permission label $this->rights[8][3] = 0; // Permission by default for new user (0/1) $this->rights[8][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) $this->rights[8][5] = 'validate'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - + $this->rights[9][0] = 1015; $this->rights[9][1] = 'inventoryChangePMPPermission'; // Permission label $this->rights[9][3] = 0; // Permission by default for new user (0/1) $this->rights[9][4] = 'advance_inventory'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) $this->rights[9][5] = 'changePMP'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) - + } - + // Main menu entries $this->menu = array(); // List of menus to add $r=0; - + // Menus //------- $this->menu = 1; // This module add menu entries. They are coded into menu manager. - - + + // Exports //-------- $r=0; $r++; - $this->export_code[$r]=$this->rights_class.'_'.$r; + $this->export_code[$r]=$this->rights_class; $this->export_label[$r]="WarehousesAndProducts"; // Translation key (used only if key ExportDataset_xxx_z not found) $this->export_permission[$r]=array(array("stock","lire")); - $this->export_fields_array[$r]=array('e.rowid'=>'IdWarehouse','e.label'=>'LocationSummary','e.description'=>'DescWareHouse','e.lieu'=>'LieuWareHouse','e.address'=>'Address','e.zip'=>'Zip','e.town'=>'Town','p.rowid'=>"ProductId",'p.ref'=>"Ref",'p.fk_product_type'=>"Type",'p.label'=>"Label",'p.description'=>"Description",'p.note'=>"Note",'p.price'=>"Price",'p.tva_tx'=>'VAT','p.tosell'=>"OnSell",'p.duration'=>"Duration",'p.datec'=>'DateCreation','p.tms'=>'DateModification','ps.reel'=>'Stock'); - $this->export_TypeFields_array[$r]=array('e.rowid'=>'List:entrepot:label','e.label'=>'Text','e.lieu'=>'Text','e.address'=>'Text','e.zip'=>'Text','e.town'=>'Text','p.rowid'=>"List:product:label",'p.ref'=>"Text",'p.fk_product_type'=>"Text",'p.label'=>"Text",'p.description'=>"Text",'p.note'=>"Text",'p.price'=>"Numeric",'p.tva_tx'=>'Numeric','p.tosell'=>"Boolean",'p.duration'=>"Duree",'p.datec'=>'Date','p.tms'=>'Date','ps.reel'=>'Numeric'); - $this->export_entities_array[$r]=array('e.rowid'=>'warehouse','e.label'=>'warehouse','e.description'=>'warehouse','e.lieu'=>'warehouse','e.address'=>'warehouse','e.zip'=>'warehouse','e.town'=>'warehouse','p.rowid'=>"product",'p.ref'=>"product",'p.fk_product_type'=>"product",'p.label'=>"product",'p.description'=>"product",'p.note'=>"product",'p.price'=>"product",'p.tva_tx'=>'product','p.tosell'=>"product",'p.duration'=>"product",'p.datec'=>'product','p.tms'=>'product','ps.reel'=>'stock'); + $this->export_fields_array[$r]=array('e.rowid'=>'IdWarehouse','e.label'=>'LocationSummary','e.description'=>'DescWareHouse','e.lieu'=>'LieuWareHouse','e.address'=>'Address','e.zip'=>'Zip','e.town'=>'Town','p.rowid'=>"ProductId",'p.ref'=>"Ref",'p.fk_product_type'=>"Type",'p.label'=>"Label",'p.description'=>"Description",'p.note'=>"Note",'p.price'=>"Price",'p.tva_tx'=>'VAT','p.tosell'=>"OnSell",'p.tobuy'=>'OnBuy','p.duration'=>"Duration",'p.datec'=>'DateCreation','p.tms'=>'DateModification','ps.reel'=>'Stock'); + $this->export_TypeFields_array[$r]=array('e.rowid'=>'List:entrepot:label','e.label'=>'Text','e.lieu'=>'Text','e.address'=>'Text','e.zip'=>'Text','e.town'=>'Text','p.rowid'=>"List:product:label",'p.ref'=>"Text",'p.fk_product_type'=>"Text",'p.label'=>"Text",'p.description'=>"Text",'p.note'=>"Text",'p.price'=>"Numeric",'p.tva_tx'=>'Numeric','p.tosell'=>"Boolean",'p.tobuy'=>"Boolean",'p.duration'=>"Duree",'p.datec'=>'Date','p.tms'=>'Date','ps.reel'=>'Numeric'); + $this->export_entities_array[$r]=array('e.rowid'=>'warehouse','e.label'=>'warehouse','e.description'=>'warehouse','e.lieu'=>'warehouse','e.address'=>'warehouse','e.zip'=>'warehouse','e.town'=>'warehouse','p.rowid'=>"product",'p.ref'=>"product",'p.fk_product_type'=>"product",'p.label'=>"product",'p.description'=>"product",'p.note'=>"product",'p.price'=>"product",'p.tva_tx'=>'product','p.tosell'=>"product",'p.tobuy'=>"product",'p.duration'=>"product",'p.datec'=>'product','p.tms'=>'product','ps.reel'=>'stock'); $this->export_aggregate_array[$r]=array('ps.reel'=>'SUM'); // TODO Not used yet $this->export_dependencies_array[$r]=array('stock'=>array('p.rowid','e.rowid')); // We must keep this until the aggregate_array is used. To add unique key if we ask a field of a child to avoid the DISTINCT to discard them. $this->export_sql_start[$r]='SELECT DISTINCT '; @@ -185,12 +185,12 @@ class modStock extends DolibarrModules // This request is same than previous but without field ps.stock (real stock in warehouse) and with link to subtable productbatch $r++; - $this->export_code[$r]=$this->rights_class.'_'.$r; + $this->export_code[$r]=$this->rights_class.'_lot'; $this->export_label[$r]="WarehousesAndProductsBatchDetail"; // Translation key (used only if key ExportDataset_xxx_z not found) $this->export_permission[$r]=array(array("stock","lire")); - $this->export_fields_array[$r]=array('e.rowid'=>'IdWarehouse','e.label'=>'LocationSummary','e.description'=>'DescWareHouse','e.lieu'=>'LieuWareHouse','e.address'=>'Address','e.zip'=>'Zip','e.town'=>'Town','p.rowid'=>"ProductId",'p.ref'=>"Ref",'p.fk_product_type'=>"Type",'p.label'=>"Label",'p.description'=>"Description",'p.note'=>"Note",'p.price'=>"Price",'p.tva_tx'=>'VAT','p.tosell'=>"OnSell",'p.duration'=>"Duration",'p.datec'=>'DateCreation','p.tms'=>'DateModification','pb.rowid'=>'Id','pb.batch'=>'Batch','pb.eatby'=>'EatByDate','pb.sellby'=>'SellByDate','pb.qty'=>'Qty'); - $this->export_TypeFields_array[$r]=array('e.rowid'=>'List:entrepot:label','e.label'=>'Text','e.lieu'=>'Text','e.address'=>'Text','e.zip'=>'Text','e.town'=>'Text','p.rowid'=>"List:product:label",'p.ref'=>"Text",'p.fk_product_type'=>"Text",'p.label'=>"Text",'p.description'=>"Text",'p.note'=>"Text",'p.price'=>"Numeric",'p.tva_tx'=>'Numeric','p.tosell'=>"Boolean",'p.duration'=>"Duree",'p.datec'=>'Date','p.tms'=>'Date','pb.batch'=>'Text','pb.eatby'=>'Date','pb.sellby'=>'Date','pb.qty'=>'Numeric'); - $this->export_entities_array[$r]=array('e.rowid'=>'warehouse','e.label'=>'warehouse','e.description'=>'warehouse','e.lieu'=>'warehouse','e.address'=>'warehouse','e.zip'=>'warehouse','e.town'=>'warehouse','p.rowid'=>"product",'p.ref'=>"product",'p.fk_product_type'=>"product",'p.label'=>"product",'p.description'=>"product",'p.note'=>"product",'p.price'=>"product",'p.tva_tx'=>'product','p.tosell'=>"product",'p.duration'=>"product",'p.datec'=>'product','p.tms'=>'product','pb.rowid'=>'batch','pb.batch'=>'batch','pb.eatby'=>'batch','pb.sellby'=>'batch','pb.qty'=>'batch'); + $this->export_fields_array[$r]=array('e.rowid'=>'IdWarehouse','e.label'=>'LocationSummary','e.description'=>'DescWareHouse','e.lieu'=>'LieuWareHouse','e.address'=>'Address','e.zip'=>'Zip','e.town'=>'Town','p.rowid'=>"ProductId",'p.ref'=>"Ref",'p.fk_product_type'=>"Type",'p.label'=>"Label",'p.description'=>"Description",'p.note'=>"Note",'p.price'=>"Price",'p.tva_tx'=>'VAT','p.tosell'=>"OnSell",'p.tobuy'=>'OnBuy','p.duration'=>"Duration",'p.datec'=>'DateCreation','p.tms'=>'DateModification','pb.rowid'=>'Id','pb.batch'=>'Batch','pb.eatby'=>'EatByDate','pb.sellby'=>'SellByDate','pb.qty'=>'Qty'); + $this->export_TypeFields_array[$r]=array('e.rowid'=>'List:entrepot:label','e.label'=>'Text','e.lieu'=>'Text','e.address'=>'Text','e.zip'=>'Text','e.town'=>'Text','p.rowid'=>"List:product:label",'p.ref'=>"Text",'p.fk_product_type'=>"Text",'p.label'=>"Text",'p.description'=>"Text",'p.note'=>"Text",'p.price'=>"Numeric",'p.tva_tx'=>'Numeric','p.tosell'=>"Boolean",'p.tobuy'=>"Boolean",'p.duration'=>"Duree",'p.datec'=>'Date','p.tms'=>'Date','pb.batch'=>'Text','pb.eatby'=>'Date','pb.sellby'=>'Date','pb.qty'=>'Numeric'); + $this->export_entities_array[$r]=array('e.rowid'=>'warehouse','e.label'=>'warehouse','e.description'=>'warehouse','e.lieu'=>'warehouse','e.address'=>'warehouse','e.zip'=>'warehouse','e.town'=>'warehouse','p.rowid'=>"product",'p.ref'=>"product",'p.fk_product_type'=>"product",'p.label'=>"product",'p.description'=>"product",'p.note'=>"product",'p.price'=>"product",'p.tva_tx'=>'product','p.tosell'=>"product",'p.tobuy'=>"product",'p.duration'=>"product",'p.datec'=>'product','p.tms'=>'product','pb.rowid'=>'batch','pb.batch'=>'batch','pb.eatby'=>'batch','pb.sellby'=>'batch','pb.qty'=>'batch'); $this->export_aggregate_array[$r]=array('ps.reel'=>'SUM'); // TODO Not used yet $this->export_dependencies_array[$r]=array('batch'=>array('pb.rowid')); // We must keep this until the aggregate_array is used. To add unique key if we ask a field of a child to avoid the DISTINCT to discard them. $this->export_sql_start[$r]='SELECT DISTINCT '; @@ -199,6 +199,26 @@ class modStock extends DolibarrModules $this->export_sql_end[$r] .=' AND e.entity IN ('.getEntity('stock').')'; } + $r++; + $this->export_code[$r]=$this->rights_class.'_movement'; + $this->export_label[$r]="StockMovements"; // Translation key (used only if key ExportDataset_xxx_z not found) + $this->export_permission[$r]=array(array("stock","lire")); + $this->export_fields_array[$r]=array('e.rowid'=>'IdWarehouse','e.label'=>'LocationSummary','e.description'=>'DescWareHouse','e.lieu'=>'LieuWareHouse','e.address'=>'Address','e.zip'=>'Zip','e.town'=>'Town','p.rowid'=>"ProductId",'p.ref'=>"Ref",'p.fk_product_type'=>"Type",'p.label'=>"Label",'p.description'=>"Description",'p.note'=>"Note",'p.price'=>"Price",'p.tva_tx'=>'VAT','p.tosell'=>"OnSell",'p.tobuy'=>'OnBuy','p.duration'=>"Duration",'p.datec'=>'DateCreation','p.tms'=>'DateModification','sm.rowid'=>'MovementId','sm.value'=>'Qty','sm.datem'=>'DateMovement','sm.label'=>'LabelMovement','sm.inventorycode'=>'InventoryCode'); + $this->export_TypeFields_array[$r]=array('e.rowid'=>'List:entrepot:label','e.label'=>'Text','e.lieu'=>'Text','e.address'=>'Text','e.zip'=>'Text','e.town'=>'Text','p.rowid'=>"List:product:label",'p.ref'=>"Text",'p.fk_product_type'=>"Text",'p.label'=>"Text",'p.description'=>"Text",'p.note'=>"Text",'p.price'=>"Numeric",'p.tva_tx'=>'Numeric','p.tosell'=>"Boolean",'p.tobuy'=>"Boolean",'p.duration'=>"Duree",'p.datec'=>'Date','p.tms'=>'Date','sm.rowid'=>'Numeric','sm.value'=>'Numeric','sm.datem'=>'Date','sm.batch'=>'Text','sm.label'=>'Text','sm.inventorycode'=>'Text'); + $this->export_entities_array[$r]=array('e.rowid'=>'warehouse','e.label'=>'warehouse','e.description'=>'warehouse','e.lieu'=>'warehouse','e.address'=>'warehouse','e.zip'=>'warehouse','e.town'=>'warehouse','p.rowid'=>"product",'p.ref'=>"product",'p.fk_product_type'=>"product",'p.label'=>"product",'p.description'=>"product",'p.note'=>"product",'p.price'=>"product",'p.tva_tx'=>'product','p.tosell'=>"product",'p.tobuy'=>"product",'p.duration'=>"product",'p.datec'=>'product','p.tms'=>'product','sm.rowid'=>'movement','sm.value'=>'movement','sm.datem'=>'movement','sm.label'=>'movement','sm.inventorycode'=>'movement'); + if ($conf->productbatch->enabled) + { + $this->export_fields_array[$r]['sm.batch']='Batch'; + $this->export_TypeFields_array[$r]['sm.batch']='Text'; + $this->export_entities_array[$r]['sm.batch']='movement'; + } + $this->export_aggregate_array[$r]=array('sm.value'=>'SUM'); // TODO Not used yet + $this->export_dependencies_array[$r]=array('movement'=>array('sm.rowid')); // We must keep this until the aggregate_array is used. To add unique key if we ask a field of a child to avoid the DISTINCT to discard them. + $this->export_sql_start[$r]='SELECT DISTINCT '; + $this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'product as p, '.MAIN_DB_PREFIX.'stock_mouvement as sm, '.MAIN_DB_PREFIX.'entrepot as e'; + $this->export_sql_end[$r] .=' WHERE p.rowid = sm.fk_product AND sm.fk_entrepot = e.rowid'; + $this->export_sql_end[$r] .=' AND e.entity IN ('.getEntity('stock').')'; + // Imports //-------- diff --git a/htdocs/core/modules/modWebsites.class.php b/htdocs/core/modules/modWebsite.class.php similarity index 80% rename from htdocs/core/modules/modWebsites.class.php rename to htdocs/core/modules/modWebsite.class.php index d6d984193d9..47d44d66164 100644 --- a/htdocs/core/modules/modWebsites.class.php +++ b/htdocs/core/modules/modWebsite.class.php @@ -16,11 +16,11 @@ */ /** - * \defgroup websites Module websites - * \brief Websites module descriptor. - * \file htdocs/core/modules/modWebsites.class.php + * \defgroup website Module website + * \brief website module descriptor. + * \file htdocs/core/modules/modWebsite.class.php * \ingroup websites - * \brief Description and activation file for module Websites + * \brief Description and activation file for module Website */ include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; @@ -28,7 +28,7 @@ include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php'; /** * Class to describe Websites module */ -class modWebsites extends DolibarrModules +class modWebsite extends DolibarrModules { /** @@ -49,7 +49,7 @@ class modWebsites extends DolibarrModules $this->module_position = 50; // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module) $this->name = preg_replace('/^mod/i','',get_class($this)); - $this->description = "Enable to build and serve public websites with CMS features"; + $this->description = "Enable to build and serve public web sites with CMS features"; // Possible values for version are: 'development', 'experimental', 'dolibarr' or version $this->version = 'experimental'; // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) @@ -60,11 +60,11 @@ class modWebsites extends DolibarrModules $this->picto='globe'; // Data directories to create when module is enabled - $this->dirs = array("/websites/temp"); + $this->dirs = array("/website/temp"); // Config pages //------------- - $this->config_page_url = array('websites.php'); + $this->config_page_url = array('website.php'); // Dependancies //------------- @@ -80,7 +80,7 @@ class modWebsites extends DolibarrModules // New pages on tabs // ----------------- - $this->tabs = array(); + //$this->tabs[] = array('data'=>'thirdparty:+website:WebSites:website:($conf->societe->enabled && $user->rights->societe->lire):/societe/website.php?mainmenu=home&id=__ID__'); // To add a new tab identified by code tabname1 // Boxes //------ @@ -88,7 +88,7 @@ class modWebsites extends DolibarrModules // Permissions $this->rights = array(); // Permission array used by this module - $this->rights_class = 'websites'; + $this->rights_class = 'website'; $r=0; $this->rights[$r][0] = 10001; @@ -114,12 +114,12 @@ class modWebsites extends DolibarrModules $this->menu[$r]=array( 'fk_menu'=>'0', // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode 'type'=>'top', // This is a Left menu entry 'titre'=>'Websites', - 'mainmenu'=>'websites', - 'url'=>'/websites/index.php', - 'langs'=>'websites', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'mainmenu'=>'website', + 'url'=>'/website/index.php', + 'langs'=>'website', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. 'position'=>100, - 'enabled'=>'$conf->websites->enabled', // Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. - 'perms'=>'$user->rights->websites->read', // Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules + 'enabled'=>'$conf->website->enabled', // Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'perms'=>'$user->rights->website->read', // Use 'perms'=>'$user->rights->mymodule->level1->level2' if you want your menu with a permission rules 'target'=>'', 'user'=>2); // 0=Menu for internal users, 1=external users, 2=both $r++; @@ -130,7 +130,7 @@ class modWebsites extends DolibarrModules $this->export_code[$r]=$this->rights_class.'_'.$r; $this->export_label[$r]='MyWebsitePages'; // Translation key (used only if key ExportDataset_xxx_z not found) $this->export_icon[$r]='globe'; - $keyforclass = 'WebsitePage'; $keyforclassfile='/websites/class/websitepage.class.php'; $keyforelement='Website'; + $keyforclass = 'WebsitePage'; $keyforclassfile='/website/class/websitepage.class.php'; $keyforelement='Website'; include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php'; //$keyforselect='myobject'; $keyforelement='myobject'; $keyforaliasextra='extra'; //include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php'; diff --git a/htdocs/core/modules/propale/doc/pdf_azur.modules.php b/htdocs/core/modules/propale/doc/pdf_azur.modules.php index 0c9a39a3fea..3e7a0130a04 100644 --- a/htdocs/core/modules/propale/doc/pdf_azur.modules.php +++ b/htdocs/core/modules/propale/doc/pdf_azur.modules.php @@ -43,6 +43,7 @@ class pdf_azur extends ModelePDFPropales var $db; var $name; var $description; + var $update_main_doc_field; // Save the name of generated file as the main doc when generating a doc with this template var $type; var $phpmin = array(4,3,0); // Minimum version of PHP required by module @@ -74,8 +75,9 @@ class pdf_azur extends ModelePDFPropales $this->db = $db; $this->name = "azur"; $this->description = $langs->trans('DocModelAzurDescription'); + $this->update_main_doc_field = 1; // Save the name of generated file as the main doc when generating a doc with this template - // Dimension page pour format A4 + // Dimension page $this->type = 'pdf'; $formatarray=pdf_getFormat(); $this->page_largeur = $formatarray['width']; @@ -760,7 +762,7 @@ class pdf_azur extends ModelePDFPropales @chmod($file, octdec($conf->global->MAIN_UMASK)); $this->result = array('fullpath'=>$file); - + return 1; // Pas d'erreur } else diff --git a/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php b/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php index 539d5df8c2a..4bdc083228e 100644 --- a/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php +++ b/htdocs/core/modules/societe/doc/doc_generic_odt.modules.php @@ -150,7 +150,7 @@ class doc_generic_odt extends ModeleThirdPartyDoc } $texte.='
    '; } - + $texte.= '
    '; @@ -272,53 +272,6 @@ class doc_generic_odt extends ModeleThirdPartyDoc } //print $odfHandler->__toString()."\n"; - // Make substitutions into odt of user info - $tmparray=$this->get_substitutionarray_user($user,$outputlangs); - //var_dump($tmparray); exit; - foreach($tmparray as $key=>$value) - { - try { - if (preg_match('/logo$/',$key)) // Image - { - //var_dump($value);exit; - if (file_exists($value)) $odfHandler->setImage($key, $value); - else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); - } - else // Text - { - //print $key.' '.$value;exit; - $odfHandler->setVars($key, $value, true, 'UTF-8'); - } - } - catch(OdfException $e) - { - // setVars failed, probably because key not found - } - } - // Make substitutions into odt of mysoc info - $tmparray=$this->get_substitutionarray_mysoc($mysoc,$outputlangs); - //var_dump($tmparray); exit; - foreach($tmparray as $key=>$value) - { - try { - if (preg_match('/logo$/',$key)) // Image - { - //var_dump($value);exit; - if (file_exists($value)) $odfHandler->setImage($key, $value); - else $odfHandler->setVars($key, 'ErrorFileNotFound', true, 'UTF-8'); - } - else // Text - { - $odfHandler->setVars($key, $value, true, 'UTF-8'); - } - } - catch(OdfException $e) - { - // setVars failed, probably because key not found - } - } - - // Replace tags of lines for contacts $contact_arrray=array(); @@ -333,7 +286,7 @@ class doc_generic_odt extends ModeleThirdPartyDoc if ($num) { require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - + $i=0; $contactstatic = new Contact($this->db); @@ -380,13 +333,18 @@ class doc_generic_odt extends ModeleThirdPartyDoc } } - // Make substitutions into odt of thirdparty + external modules - $tmparray=$this->get_substitutionarray_thirdparty($object,$outputlangs); + // Make substitutions into odt + $array_user=$this->get_substitutionarray_user($user,$outputlangs); + $array_soc=$this->get_substitutionarray_mysoc($mysoc,$outputlangs); + $array_thirdparty=$this->get_substitutionarray_thirdparty($object,$outputlangs); + $array_other=$this->get_substitutionarray_other($outputlangs); + + $tmparray = array_merge($array_user,$array_soc,$array_thirdparty,$array_other); complete_substitutions_array($tmparray, $outputlangs, $object); // Call the ODTSubstitution hook $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray); - $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + $reshook=$hookmanager->executeHooks('ODTSubstitution',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks // Replace variables into document foreach($tmparray as $key=>$value) @@ -438,13 +396,13 @@ class doc_generic_odt extends ModeleThirdPartyDoc $odfHandler->creator = $user->getFullName($outputlangs); $odfHandler->title = $object->builddoc_filename; $odfHandler->subject = $object->builddoc_filename; - + if (! empty($conf->global->ODT_ADD_DOLIBARR_ID)) { $odfHandler->userdefined['dol_id'] = $object->id; $odfHandler->userdefined['dol_element'] = $object->element; } - + $odfHandler->saveToDisk($file); }catch (Exception $e){ $this->error=$e->getMessage(); @@ -453,7 +411,7 @@ class doc_generic_odt extends ModeleThirdPartyDoc } $parameters=array('odfHandler'=>&$odfHandler,'file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs,'substitutionarray'=>&$tmparray); $reshook=$hookmanager->executeHooks('afterODTCreation',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - + if (! empty($conf->global->MAIN_UMASK)) @chmod($file, octdec($conf->global->MAIN_UMASK)); diff --git a/htdocs/core/search_page.php b/htdocs/core/search_page.php index 61d39af045e..eb873d0e8f9 100644 --- a/htdocs/core/search_page.php +++ b/htdocs/core/search_page.php @@ -77,9 +77,6 @@ if ($conf->use_javascript_ajax && 1 == 2) // select2 is ko with jmobile } else { - $conf->global->MAIN_HTML5_PLACEHOLDER = 1; - - $usedbyinclude = 1; // Used into next include include DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; diff --git a/htdocs/core/tools.php b/htdocs/core/tools.php index 8010f726c4f..25e2eb3f903 100644 --- a/htdocs/core/tools.php +++ b/htdocs/core/tools.php @@ -46,7 +46,7 @@ $text=$langs->trans("Tools"); print load_fiche_titre($text); // Show description of content -print $langs->trans("ToolsDesc").'

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


    '; // Show logo diff --git a/htdocs/core/tpl/admin_extrafields_add.tpl.php b/htdocs/core/tpl/admin_extrafields_add.tpl.php index e04f4e0cb92..ec25a82b7f1 100644 --- a/htdocs/core/tpl/admin_extrafields_add.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_add.tpl.php @@ -35,9 +35,10 @@ $langs->load("modulebuilder"); jQuery(document).ready(function() { function init_typeoffields(type) { - console.log("selected type is "+type); - var size = jQuery("#size"); + console.log("We select a new type = "+type); + var size = jQuery("#size"); var computed_value = jQuery("#computed_value"); + var langfile = jQuery("#langfile"); var default_value = jQuery("#default_value"); var unique = jQuery("#unique"); var required = jQuery("#required"); @@ -51,7 +52,7 @@ $langs->load("modulebuilder"); if (GETPOST('type','alpha') == "separate") { - print "jQuery('#size, #default_value').val('').prop('disabled', true);"; + print "jQuery('#size, #default_value, #langfile').val('').prop('disabled', true);"; print 'jQuery("#value_choice").hide();'; } ?> @@ -67,15 +68,15 @@ $langs->load("modulebuilder"); { console.log("We enter a computed formula"); jQuery("#default_value").val(''); - /* jQuery("#unique, #required, #alwayseditable, #ishidden, #list").removeAttr('checked'); */ - jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', true); - jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").hide(); + /* jQuery("#unique, #required, #alwayseditable, #list").removeAttr('checked'); */ + jQuery("#default_value, #unique, #required, #alwayseditable, #list").attr('disabled', true); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_list").hide(); } else { console.log("No computed formula"); - jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', false); - jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").show(); + jQuery("#default_value, #unique, #required, #alwayseditable, #list").attr('disabled', false); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_list").show(); } if (type == 'date') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").hide();jQuery("#helpchkbxlst").hide(); } @@ -93,7 +94,7 @@ $langs->load("modulebuilder"); else if (type == 'chkbxlst') { size.val('').prop('disabled', true); unique.removeAttr('checked').prop('disabled', true); jQuery("#value_choice").show();jQuery("#helpselect").hide();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").show();jQuery("#helplink").hide();} else if (type == 'link') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").show();jQuery("#helpselect").hide();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").hide();jQuery("#helplink").show();} else if (type == 'separate') { - size.val('').prop('disabled', true); unique.removeAttr('checked').prop('disabled', true); required.val('').prop('disabled', true); + langfile.val('').prop('disabled',true);size.val('').prop('disabled', true); unique.removeAttr('checked').prop('disabled', true); required.val('').prop('disabled', true); jQuery("#value_choice").hide();jQuery("#helpselect").hide();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").hide();jQuery("#helplink").hide(); } else { // type = string @@ -104,12 +105,13 @@ $langs->load("modulebuilder"); if (type == 'separate') { required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.removeAttr('checked').prop('disabled', true); - jQuery('#size, #default_value').val('').prop('disabled', true); + jQuery('#size, #default_value, #langfile').val('').prop('disabled', true); + jQuery('#list').val(3); } else { default_value.removeAttr('disabled'); - required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.removeAttr('disabled'); + langfile.removeAttr('disabled');required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.removeAttr('disabled'); } } init_typeoffields(''); @@ -151,10 +153,10 @@ $langs->load("modulebuilder");
    - textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"),1,0)?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"),1,0)?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"),1,0)?> - textwithpicto('', $langs->trans("ExtrafieldParamHelplink"),1,0)?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"),1,0,'', 0, 2, 'helpvalue1')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"),1,0,'', 0, 2, 'helpvalue2')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"),1,0,'', 0, 2, 'helpvalue3')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelplink"),1,0,'', 0, 2, 'helpvalue4')?>
    @@ -162,7 +164,7 @@ $langs->load("modulebuilder"); trans("Position"); ?> -trans("LanguageFile"); ?> +trans("LanguageFile"); ?> textwithpicto($langs->trans("ComputedFormula"), $langs->trans("ComputedFormulaDesc"), 1, 'help', '', 0, 2, 'tooltipcompute'); ?> @@ -173,15 +175,11 @@ $langs->load("modulebuilder"); trans("Required"); ?>> trans("AlwaysEditable"); ?>> - -global->MAIN_CAN_HIDE_EXTRAFIELDS)) { ?> -trans("Hidden"); ?>> - multicompany->enabled) { ?> trans("AllEntities"); ?>> - -textwithpicto($langs->trans("ByDefaultInList"), $langs->trans("VisibleDesc")); ?> + +textwithpicto($langs->trans("Visibility"), $langs->trans("VisibleDesc")); ?> diff --git a/htdocs/core/tpl/admin_extrafields_edit.tpl.php b/htdocs/core/tpl/admin_extrafields_edit.tpl.php index def07fa432f..2d10df38cb1 100644 --- a/htdocs/core/tpl/admin_extrafields_edit.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_edit.tpl.php @@ -37,6 +37,7 @@ $langs->load("modulebuilder"); console.log("select new type "+type); var size = jQuery("#size"); var computed_value = jQuery("#computed_value"); + var langfile = jQuery("#langfile"); var default_value = jQuery("#default_value"); var unique = jQuery("#unique"); var required = jQuery("#required"); @@ -50,7 +51,7 @@ $langs->load("modulebuilder"); if (GETPOST('type','alpha') == "separate") { - print "jQuery('#size, #default_value').val('').prop('disabled', true);"; + print "jQuery('#size, #default_value, #langfile').val('').prop('disabled', true);"; print 'jQuery("#value_choice").hide();'; } ?> @@ -65,15 +66,15 @@ $langs->load("modulebuilder"); { console.log("We enter a computed formula"); jQuery("#default_value").val(''); - /* jQuery("#unique, #required, #alwayseditable, #ishidden, #list").removeAttr('checked'); */ - jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', true); - jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").hide(); + /* jQuery("#unique, #required, #alwayseditable, #list").removeAttr('checked'); */ + jQuery("#default_value, #unique, #required, #alwayseditable, #list").attr('disabled', true); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_list").hide(); } else { console.log("No computed formula"); - jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', false); - jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").show(); + jQuery("#default_value, #unique, #required, #alwayseditable, #list").attr('disabled', false); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_list").show(); } if (type == 'date') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").hide();jQuery("#helpchkbxlst").hide(); } @@ -99,7 +100,8 @@ $langs->load("modulebuilder"); if (type == 'separate') { required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.removeAttr('checked').prop('disabled', true); - jQuery('#size, #default_value').val('').prop('disabled', true); + jQuery('#size, #default_value, #langfile').val('').prop('disabled', true); + jQuery('#list').val(3); } else { @@ -143,7 +145,6 @@ $param=$extrafields->attributes[$elementtype]['param'][$attrname]; $perms=$extrafields->attributes[$elementtype]['perms'][$attrname]; $langfile=$extrafields->attributes[$elementtype]['langfile'][$attrname]; $list=$extrafields->attributes[$elementtype]['list'][$attrname]; -$ishidden=$extrafields->attributes[$elementtype]['hidden'][$attrname]; $entitycurrentorall=$extrafields->attributes[$elementtype]['entityid'][$attrname]; if((($type == 'select') || ($type == 'checkbox') || ($type == 'radio')) && is_array($param)) @@ -210,10 +211,10 @@ else - textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"),1,0)?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"),1,0)?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"),1,0)?> - textwithpicto('', $langs->trans("ExtrafieldParamHelplink"),1,0)?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"),1,0,'', 0, 2, 'helpvalue1')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"),1,0,'', 0, 2, 'helpvalue2')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"),1,0,'', 0, 2, 'helpvalue3')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelplink"),1,0,'', 0, 2, 'helpvalue4')?> @@ -232,15 +233,11 @@ else trans("Required"); ?>> trans("AlwaysEditable"); ?>> - -global->MAIN_CAN_HIDE_EXTRAFIELDS)) { ?> - trans("Hidden"); ?>> - multicompany->enabled) { ?> trans("AllEntities"); ?>> - -textwithpicto($langs->trans("ByDefaultInList"), $langs->trans("VisibleDesc")); ?> + +textwithpicto($langs->trans("Visibility"), $langs->trans("VisibleDesc")); ?> diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php index 95a9ea250a1..e9f880e2696 100644 --- a/htdocs/core/tpl/admin_extrafields_view.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php @@ -60,30 +60,29 @@ if ($conf->multicompany->enabled) { print ' '; print "\n"; -if (count($extrafields->attribute_type)) +if (count($extrafields->attributes[$elementtype]['type'])) { - foreach($extrafields->attribute_type as $key => $value) + foreach($extrafields->attributes[$elementtype]['type'] as $key => $value) { // Load language if required - if (! empty($extrafields->attribute_langfile[$key])) { - $langs->load($extrafields->attribute_langfile[$key]); + if (! empty($extrafields->attributes[$elementtype]['langfile'][$key])) { + $langs->load($extrafields->attributes[$elementtype]['langfile'][$key]); } print ''; - print "".$extrafields->attribute_pos[$key]."\n"; - print "".$extrafields->attribute_label[$key]."\n"; // We don't translate here, we want admin to know what is the key not translated value - print "".$langs->trans($extrafields->attribute_label[$key])."\n"; + print "".$extrafields->attributes[$elementtype]['pos'][$key]."\n"; + print "".$extrafields->attributes[$elementtype]['label'][$key]."\n"; // We don't translate here, we want admin to know what is the key not translated value + print "".$langs->trans($extrafields->attributes[$elementtype]['label'][$key])."\n"; print "".$key."\n"; - print "".$type2label[$extrafields->attribute_type[$key]]."\n"; - print ''.$extrafields->attribute_size[$key]."\n"; - print ''.yn($extrafields->attribute_unique[$key])."\n"; - print ''.dol_trunc($extrafields->attribute_computed[$key], 20)."\n"; - print ''.yn($extrafields->attribute_required[$key])."\n"; - print ''.yn($extrafields->attribute_alwayseditable[$key])."\n"; - print ''.$extrafields->attribute_list[$key]."\n"; - if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ''.yn($extrafields->attribute_hidden[$key])."\n"; // Add hidden option on not working feature. Why hide if user can't see it. + print "".$type2label[$extrafields->attributes[$elementtype]['type'][$key]]."\n"; + print ''.$extrafields->attributes[$elementtype]['size'][$key]."\n"; + print ''.yn($extrafields->attributes[$elementtype]['unique'][$key])."\n"; + print ''.dol_trunc($extrafields->attributes[$elementtype]['computed'][$key], 20)."\n"; + print ''.yn($extrafields->attributes[$elementtype]['required'][$key])."\n"; + print ''.yn($extrafields->attributes[$elementtype]['alwayseditable'][$key])."\n"; + print ''.$extrafields->attributes[$elementtype]['list'][$key]."\n"; if (! empty($conf->multicompany->enabled)) { - print ''.($extrafields->attribute_entityid[$key]==0?$langs->trans("All"):$extrafields->attribute_entitylabel[$key]).''; + print ''.($extrafields->attributes[$elementtype]['entityid'][$key]==0?$langs->trans("All"):$extrafields->attributes[$elementtype]['entitylabel'][$key]).''; } print ''.img_edit().''; print "  ".img_delete()."\n"; diff --git a/htdocs/core/tpl/card_presend.tpl.php b/htdocs/core/tpl/card_presend.tpl.php index 6e653372148..c5e8e68901b 100644 --- a/htdocs/core/tpl/card_presend.tpl.php +++ b/htdocs/core/tpl/card_presend.tpl.php @@ -34,8 +34,10 @@ if ($action == 'presend') $object->fetch_projet(); - if (! in_array($object->element, array('societe', 'user'))) + if (! in_array($object->element, array('societe', 'user', 'member'))) { + // TODO get also the main_lastdoc field of $object. If not found, try to guess with following code + $ref = dol_sanitizeFileName($object->ref); include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $fileparams = dol_most_recent_file($diroutput . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); @@ -75,19 +77,17 @@ if ($action == 'presend') } // Build document if it not exists - if (! in_array($object->element, array('societe', 'user'))) + if (! in_array($object->element, array('societe', 'user', 'member'))) { - if (! $file || ! is_readable($file)) { - if ($object->element != 'member') - { - $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) { - dol_print_error($db, $object->error, $object->errors); - exit(); - } - $fileparams = dol_most_recent_file($diroutput . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file = $fileparams['fullname']; + if ((! $file || ! is_readable($file)) && method_exists($object, 'generateDocument')) + { + $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result <= 0) { + dol_print_error($db, $object->error, $object->errors); + exit(); } + $fileparams = dol_most_recent_file($diroutput . '/' . $ref, preg_quote($ref, '/').'[^\-]+'); + $file = $fileparams['fullname']; } } @@ -116,12 +116,13 @@ if ($action == 'presend') } $formmail->withfrom = 1; + // Fill list of recipient with email inside <>. $liste = array(); if ($object->element == 'expensereport') { $fuser = new User($db); $fuser->fetch($object->fk_user_author); - $liste['thirdparty'] = $fuser->getFullName($langs)." <".$fuser->email.">"; + $liste['thirdparty'] = $fuser->getFullName($langs)." <".$fuser->email.">"; } elseif ($object->element == 'societe') { @@ -131,7 +132,7 @@ if ($action == 'presend') } elseif ($object->element == 'user' || $object->element == 'member') { - $liste['thirdparty'] = $object->getFullName($langs)." <".$object->email.">"; + $liste['thirdparty'] = $object->getFullName($langs)." <".$object->email.">"; } else { diff --git a/htdocs/core/tpl/commonfields_add.tpl.php b/htdocs/core/tpl/commonfields_add.tpl.php new file mode 100644 index 00000000000..f6aebd6357c --- /dev/null +++ b/htdocs/core/tpl/commonfields_add.tpl.php @@ -0,0 +1,53 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $action + * $conf + * $langs + */ +?> + +fields as $key => $val) +{ + // Discard if extrafield is a hidden field on form + if (abs($val['visible']) != 1) continue; + + if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled']) continue; // We don't want this field + + print ''; + print ''; + print $langs->trans($val['label']); + print ''; + print ''; + if (in_array($val['type'], array('int', 'integer'))) $value = GETPOST($key, 'int'); + elseif ($val['type'] == 'text') $value = GETPOST($key, 'none'); + else $value = GETPOST($key, 'alpha'); + print $object->showInputField($val, $key, $value, '', '', '', 0); + print ''; + print ''; +} + +?> + \ No newline at end of file diff --git a/htdocs/core/tpl/commonfields_edit.tpl.php b/htdocs/core/tpl/commonfields_edit.tpl.php new file mode 100644 index 00000000000..248cd4b4086 --- /dev/null +++ b/htdocs/core/tpl/commonfields_edit.tpl.php @@ -0,0 +1,50 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $action + * $conf + * $langs + */ +?> + +fields as $key => $val) +{ + // Discard if extrafield is a hidden field on form + if (abs($val['visible']) != 1) continue; + + if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled']) continue; // We don't want this field + + print ''.$langs->trans($val['label']).''; + print ''; + if (in_array($val['type'], array('int', 'integer'))) $value = GETPOSTISSET($key)?GETPOST($key, 'int'):$object->$key; + elseif ($val['type'] == 'text') $value = GETPOSTISSET($key)?GETPOST($key,'none'):$object->$key; + else $value = GETPOSTISSET($key)?GETPOST($key, 'alpha'):$object->$key; + print $object->showInputField($val, $key, $value, '', '', '', 0); + print ''; + print ''; +} + +?> + \ No newline at end of file diff --git a/htdocs/core/tpl/commonfields_view.tpl.php b/htdocs/core/tpl/commonfields_view.tpl.php new file mode 100644 index 00000000000..ded3247f1dd --- /dev/null +++ b/htdocs/core/tpl/commonfields_view.tpl.php @@ -0,0 +1,86 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Need to have following variables defined: + * $object (invoice, order, ...) + * $action + * $conf + * $langs + */ +?> + +fields as $key => $val) +{ + // Discard if extrafield is a hidden field on form + if (abs($val['visible']) != 1) continue; + + if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled']) continue; // We don't want this field + if ($key == 'status') continue; // Status is already in dol_banner + + $value=$object->$key; + + print ''.$langs->trans($val['label']).''; + print ''; + print $object->showOutputField($val, $key, $value, '', '', '', 0); + //print dol_escape_htmltag($object->$key, 1, 1); + print ''; + print ''; + + //if ($key == 'targetsrcfile3') break; // key used for break on second column +} + +print ''; +print '
    '; +print '
    '; +print '
    '; +print '
    '; +print ''; + +$alreadyoutput = 1; +foreach($object->fields as $key => $val) +{ + if ($alreadyoutput) + { + //if ($key == 'targetsrcfile3') $alreadyoutput = 0; // key used for break on second column + continue; + } + + if (abs($val['visible']) != 1) continue; // Discard such field from form + if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled']) continue; // We don't want this field + if ($key == 'status') continue; // Status is alreadt in dol_banner + + $value=$object->$key; + + print ''.$langs->trans($val['label']).''; + print ''; + print ''; +} + +?> + \ No newline at end of file diff --git a/htdocs/core/tpl/extrafields_add.tpl.php b/htdocs/core/tpl/extrafields_add.tpl.php index a608cb2da6b..f8be788ae2f 100644 --- a/htdocs/core/tpl/extrafields_add.tpl.php +++ b/htdocs/core/tpl/extrafields_add.tpl.php @@ -32,7 +32,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (empty($reshook) && ! empty($extrafields->attribute_label)) { +if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element]['label'])) { print $object->showOptionals($extrafields, 'edit'); } diff --git a/htdocs/core/tpl/extrafields_edit.tpl.php b/htdocs/core/tpl/extrafields_edit.tpl.php index aa0e30473f1..a2c3bf5771f 100644 --- a/htdocs/core/tpl/extrafields_edit.tpl.php +++ b/htdocs/core/tpl/extrafields_edit.tpl.php @@ -32,7 +32,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (empty($reshook) && ! empty($extrafields->attribute_label)) { +if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element]['label'])) { print $object->showOptionals($extrafields, 'edit'); } diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index 56eb8652d2b..b57025e3dd6 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -42,6 +42,9 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ { foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) { + // Discard if extrafield is a hidden field on form + if (abs($extrafields->attributes[$object->table_element]['list'][$key]) != 1) continue; + // Load language if required if (! empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); @@ -59,8 +62,7 @@ if (empty($reshook) && ! empty($extrafields->attributes[$object->table_element][ } else { - if (! empty($extrafields->attributes[$object->table_element]['ishidden'][$key])) print ''; print ''; - if ($object->statut <= 1) + if ($origin && $origin_id > 0) { - print ''; + print ''; + } + if ($action == 'editline') + { + $editColspan = 3; + if (empty($conf->stock->enabled)) $editColspan--; + if (empty($conf->productbatch->enabled)) $editColspan--; + print ''; } else { - print ''; - } + if ($object->statut <= 1) + { + print ''; + } + else + { + print ''; + } + if (! empty($conf->stock->enabled)) + { + print ''; + } - if ($origin && $origin_id > 0) - { - print ''; + if (! empty($conf->productbatch->enabled)) + { + print ''; + } } - print ''; print ''; //print ''; - - if (! empty($conf->stock->enabled)) + if ($object->statut == 0) { - print ''; + print ''; + print ''; } - - if (! empty($conf->productbatch->enabled)) - { - print ''; - } - print "\n"; $var=false; @@ -1892,9 +2212,6 @@ else if ($id || $ref) // Qty ordered print ''; - // Qty to ship or shipped - print ''; - // Qty in other shipments (with shipment and warehouse used) if ($origin && $origin_id > 0) { @@ -1926,6 +2243,123 @@ else if ($id || $ref) } print ''; + if ($action == 'editline' && $lines[$i]->id == $line_id) + { + // edit mode + print ''; + } + else + { + // Qty to ship or shipped + print ''; + + // Warehouse source + if (! empty($conf->stock->enabled)) + { + print ''; + } + + // Batch number managment + if (! empty($conf->productbatch->enabled)) + { + if (isset($lines[$i]->detail_batch)) + { + print ''; + } else { + print ''; + } + } + } + // Weight print ''; - // Warehouse source - if (! empty($conf->stock->enabled)) + if ($action == 'editline' && $lines[$i]->id == $line_id) { - print ''; + print ''; + print ''; + + // Display lines extrafields + if (! empty($rowExtrafieldsStart)) { - print ''; - } else { - print ''; + print $rowExtrafieldsStart; + print $rowExtrafieldsView; + print $rowEnd; } } print ""; @@ -2000,11 +2407,16 @@ else if ($id || $ref) $line = new ExpeditionLigne($db); $line->fetch_optionals($lines[$i]->id,$extralabelslines); print ''; - print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bc[$var], 'colspan'=>$colspan),$indiceAsked); + if ($action == 'editline' && $lines[$i]->id == $line_id) + { + print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bc[$var], 'colspan'=>$colspan),$indiceAsked); + } + else + { + print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bc[$var], 'colspan'=>$colspan),$indiceAsked); + } print ''; } - - } // TODO Show also lines ordered but not delivered @@ -2112,7 +2524,7 @@ else if ($id || $ref) * Documents generated */ - if ($action != 'presend') + if ($action != 'presend' && $action != 'editline') { print '
    '; @@ -2122,7 +2534,7 @@ else if ($id || $ref) $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed=$user->rights->expedition->lire; - $delallowed=$user->rights->expedition->supprimer; + $delallowed=$user->rights->expedition->creer; print $formfile->showdocuments('expedition',$objectref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,28,0,'','','',$soc->default_lang); @@ -2159,136 +2571,6 @@ else if ($id || $ref) $trackid = 'shi'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - - /* - if ($action == 'presend') - { - $ref = dol_sanitizeFileName($object->ref); - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $fileparams = dol_most_recent_file($conf->expedition->dir_output . '/sending/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file=$fileparams['fullname']; - - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->thirdparty->default_lang; - - if (!empty($newlang)) - { - $outputlangs = new Translate('', $conf); - $outputlangs->setDefaultLang($newlang); - $outputlangs->load('sendings'); - } - - // Build document if it not exists - if (! $file || ! is_readable($file)) - { - $result = $object->generateDocument(GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db,$object->error,$object->errors); - exit; - } - $fileparams = dol_most_recent_file($conf->expedition->dir_output . '/sending/' . $ref, preg_quote($ref, '/').'[^\-]+'); - $file=$fileparams['fullname']; - } - - print '
    '; - print '
    '; - print '
    '; - print load_fiche_titre($langs->trans('SendShippingByEMail')); - - dol_fiche_head(''); - - // Cree l'objet formulaire mail - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); - $formmail->fromtype = (GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); - - if($formmail->fromtype === 'user'){ - $formmail->fromid = $user->id; - - } - $formmail->trackid='shi'.$object->id; - if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { - include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - $formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'shi'.$object->id); - } - $formmail->withfrom=1; - $liste=array(); - foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key=>$value) $liste[$key]=$value; - $formmail->withto=GETPOST("sendto")?GETPOST("sendto"):$liste; - $formmail->withtocc=$liste; - $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$outputlangs->trans('SendShippingRef','__SHIPPINGREF__'); - $formmail->withfile=2; - $formmail->withbody=1; - $formmail->withdeliveryreceipt=1; - $formmail->withcancel=1; - // Tableau des substitutions - $formmail->setSubstitFromObject($object, $outputlangs); - $formmail->substit['__SHIPPINGREF__']=$object->ref; - $formmail->substit['__SHIPPINGTRACKNUM__']=$object->tracking_number; - $formmail->substit['__SHIPPINGTRACKNUMURL__']=$object->tracking_url; - - //Find the good contact adress - if ($typeobject == 'commande' && $object->$typeobject->id && ! empty($conf->commande->enabled)) { - $objectsrc=new Commande($db); - $objectsrc->fetch($object->$typeobject->id); - } - if ($typeobject == 'propal' && $object->$typeobject->id && ! empty($conf->propal->enabled)) { - $objectsrc=new Propal($db); - $objectsrc->fetch($object->$typeobject->id); - } - $custcontact=''; - $contactarr=array(); - if (is_object($objectsrc)) // For the case the shipment was created without orders - { - $contactarr=$objectsrc->liste_contact(-1,'external'); - } - - if (is_array($contactarr) && count($contactarr)>0) { - foreach($contactarr as $contact) { - - if ($contact['libelle']==$langs->trans('TypeContact_commande_external_CUSTOMER')) { - - require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; - - $contactstatic=new Contact($db); - $contactstatic->fetch($contact['id']); - $custcontact=$contactstatic->getFullName($langs,1); - } - } - - if (!empty($custcontact)) { - $formmail->substit['__CONTACTCIVNAME__']=$custcontact; - } - } - - // Tableau des parametres complementaires - $formmail->param['action']='send'; - $formmail->param['models']='shipping_send'; - $formmail->param['models_id']=GETPOST('modelmailselected','int'); - $formmail->param['shippingid']=$object->id; - $formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id; - - // Init list of files - if (GETPOST("mode")=='init') - { - $formmail->clear_attached_files(); - $formmail->add_attached_files($file,basename($file),dol_mimetype($file)); - } - - // Show form - print $formmail->get_form(); - - dol_fiche_end(); - }*/ } diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index cf1c7afad9c..0cdbb9665c6 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -3,11 +3,11 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke * Copyright (C) 2006-2012 Laurent Destailleur - * Copyright (C) 2011-2016 Juanjo Menent + * Copyright (C) 2011-2017 Juanjo Menent * Copyright (C) 2013 Florian Henry * Copyright (C) 2014 Cedric GROSS * Copyright (C) 2014-2015 Marcos García - * Copyright (C) 2014-2015 Francis Appels + * Copyright (C) 2014-2017 Francis Appels * Copyright (C) 2015 Claudio Aschieri * Copyright (C) 2016 Ferran Marcet * @@ -47,7 +47,7 @@ class Expedition extends CommonObject public $fk_element="fk_expedition"; public $table_element="expedition"; public $table_element_line="expeditiondet"; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'sending'; var $socid; @@ -373,48 +373,18 @@ class Expedition extends CommonObject */ function create_line($entrepot_id, $origin_line_id, $qty,$array_options=0) { - global $conf; - $error = 0; - $line_id = 0; + $expeditionline = new ExpeditionLigne($this->db); + $expeditionline->fk_expedition = $this->id; + $expeditionline->entrepot_id = $entrepot_id; + $expeditionline->fk_origin_line = $origin_line_id; + $expeditionline->qty = $qty; + $expeditionline->array_options = $array_options; - $sql = "INSERT INTO ".MAIN_DB_PREFIX."expeditiondet ("; - $sql.= "fk_expedition"; - $sql.= ", fk_entrepot"; - $sql.= ", fk_origin_line"; - $sql.= ", qty"; - $sql.= ") VALUES ("; - $sql.= $this->id; - $sql.= ", ".($entrepot_id?$entrepot_id:'null'); - $sql.= ", ".$origin_line_id; - $sql.= ", ".$qty; - $sql.= ")"; - - dol_syslog(get_class($this)."::create_line", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) + if (($lineId = $expeditionline->insert()) < 0) { - $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet"); + $this->error[]=$expeditionline->error; } - else - { - $error++; - } - - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used - { - $expeditionline = new ExpeditionLigne($this->db); - $expeditionline->array_options=$array_options; - $expeditionline->id= $this->db->last_insert_id(MAIN_DB_PREFIX.$expeditionline->table_element); - $result=$expeditionline->insertExtraFields(); - if ($result < 0) - { - $this->error[]=$expeditionline->error; - $error++; - } - } - - if (! $error) return $line_id; - else return -1; + return $lineId; } @@ -1366,6 +1336,7 @@ class Expedition extends CommonObject $detail_entrepot = new stdClass; $detail_entrepot->entrepot_id = $obj->fk_entrepot; $detail_entrepot->qty_shipped = $obj->qty_shipped; + $detail_entrepot->line_id = $obj->line_id; $line->details_entrepot[] = $detail_entrepot; $line->line_id = $obj->line_id; @@ -1400,10 +1371,13 @@ class Expedition extends CommonObject $line->pa_ht = $obj->pa_ht; + // Local taxes $localtax_array=array(0=>$obj->localtax1_type, 1=>$obj->localtax1_tx, 2=>$obj->localtax2_type, 3=>$obj->localtax2_tx); + $localtax1_tx = get_localtax($obj->tva_tx, 1, $this->thirdparty); + $localtax2_tx = get_localtax($obj->tva_tx, 2, $this->thirdparty); // For invoicing - $tabprice = calcul_price_total($obj->qty_shipped, $obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->fk_product_type, $mysoc, $localtax_array); // We force type to 0 + $tabprice = calcul_price_total($obj->qty_shipped, $obj->subprice, $obj->remise_percent, $obj->tva_tx, $localtax1_tx, $localtax2_tx, 0, 'HT', $obj->info_bits, $obj->fk_product_type, $mysoc, $localtax_array); // We force type to 0 $line->desc = $obj->description; // We need ->desc because some code into CommonObject use desc (property defined for other elements) $line->qty = $line->qty_shipped; $line->total_ht = $tabprice[0]; @@ -1530,11 +1504,11 @@ class Expedition extends CommonObject $linkstart = ''; $linkend=''; - $picto='sending'; + $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 ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$linkstart.$this->ref.$linkend; return $result; } @@ -2235,6 +2209,17 @@ class Expedition extends CommonObject */ class ExpeditionLigne extends CommonObjectLine { + public $element='expeditiondet'; + public $table_element='expeditiondet'; + + public $fk_origin_line; + + /** + * Id of shipment + * @var int + */ + public $fk_expedition; + var $db; // From llx_expeditiondet @@ -2242,6 +2227,12 @@ class ExpeditionLigne extends CommonObjectLine var $qty_shipped; var $fk_product; var $detail_batch; + /** + * Id of warehouse + * @var int + */ + public $entrepot_id; + // From llx_commandedet or llx_propaldet var $qty_asked; @@ -2258,10 +2249,7 @@ class ExpeditionLigne extends CommonObjectLine var $total_localtax1; // Total Local tax 1 var $total_localtax2; // Total Local tax 2 - public $element='expeditiondet'; - public $table_element='expeditiondet'; - public $fk_origin_line; // Deprecated /** @@ -2280,15 +2268,403 @@ class ExpeditionLigne extends CommonObjectLine */ var $libelle; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ + /** + * Constructor + * + * @param DoliDB $db Database handler + */ function __construct($db) { $this->db=$db; } + /** + * Load line expedition + * + * @param int $rowid Id line order + * @return int <0 if KO, >0 if OK + */ + function fetch($rowid) + { + $sql = 'SELECT ed.rowid, ed.fk_expedition, ed.fk_entrepot, ed.fk_origin_line, ed.qty, ed.rang'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as ed'; + $sql.= ' WHERE ed.rowid = '.$rowid; + $result = $this->db->query($sql); + if ($result) + { + $objp = $this->db->fetch_object($result); + $this->id = $objp->rowid; + $this->fk_expedition = $objp->fk_expedition; + $this->entrepot_id = $objp->fk_entrepot; + $this->fk_origin_line = $objp->fk_origin_line; + $this->qty = $objp->qty; + $this->rang = $objp->rang; + + $this->db->free($result); + + return 1; + } + else + { + $this->errors[] = $this->db->lasterror(); + $this->error = $this->db->lasterror(); + return -1; + } + } + + /** + * Insert line into database + * + * @param User $user User that modify + * @param int $notrigger 1 = disable triggers + * @return int <0 if KO, line id >0 if OK + */ + function insert($user=null, $notrigger=0) + { + global $langs, $conf; + + $error=0; + + // Check parameters + if (empty($this->fk_expedition) || empty($this->fk_origin_line) || empty($this->qty)) + { + $this->errors[] = 'ErrorMandatoryParametersNotProvided'; + return -1; + } + // Clean parameters + if (empty($this->entrepot_id)) $this->entrepot_id='null'; + + $this->db->begin(); + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."expeditiondet ("; + $sql.= "fk_expedition"; + $sql.= ", fk_entrepot"; + $sql.= ", fk_origin_line"; + $sql.= ", qty"; + $sql.= ") VALUES ("; + $sql.= $this->fk_expedition; + $sql.= ", ".$this->entrepot_id; + $sql.= ", ".$this->fk_origin_line; + $sql.= ", ".$this->qty; + $sql.= ")"; + + dol_syslog(get_class($this)."::insert", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet"); + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINESHIPPING_INSERT',$user); + if ($result < 0) + { + $this->errors[]=$this->error; + $error++; + } + // End call triggers + } + + if (! $error) { + $this->db->commit(); + return $this->id; + } + + 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 + { + $error++; + } + } + + /** + * Delete shipment line. + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int >0 if OK, <0 if KO + */ + function delete($user = null, $notrigger = 0) + { + global $conf; + + $error=0; + + $this->db->begin(); + + // delete batch expedition line + if ($conf->productbatch->enabled) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch"; + $sql.= " WHERE fk_expeditiondet = ".$this->id; + + if (!$this->db->query($sql)) + { + $this->errors[]=$this->db->lasterror()." - sql=$sql"; + $error++; + } + } + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet"; + $sql.= " WHERE rowid = ".$this->id; + + if (! $error && $this->db->query($sql)) + { + // Remove extrafields + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $this->errors[]=$this->error; + $error++; + } + } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINESHIPPING_DELETE',$user); + if ($result < 0) + { + $this->errors[]=$this->error; + $error++; + } + // End call triggers + } + } + else + { + $this->errors[]=$this->db->lasterror()." - sql=$sql"; + $error++; + } + + if (! $error) { + $this->db->commit(); + return 1; + } + else + { + 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; + } + } + + /** + * Update a line in database + * + * @param User $user User that modify + * @param int $notrigger 1 = disable triggers + * @return int < 0 if KO, > 0 if OK + */ + function update($user = null, $notrigger = 0) + { + global $conf; + + $error=0; + + dol_syslog(get_class($this)."::update id=$this->id, entrepot_id=$this->entrepot_id, product_id=$this->fk_product, qty=$this->qty"); + + $this->db->begin(); + + // Clean parameters + if (empty($this->qty)) $this->qty=0; + $qty=price2num($this->qty); + $remainingQty = 0; + $batch = null; + $batch_id = null; + $expedition_batch_id = null; + if (is_array($this->detail_batch)) // array of ExpeditionLineBatch + { + if (count($this->detail_batch) > 1) + { + dol_syslog(get_class($this).'::update only possible for one batch', LOG_ERR); + $this->errors[]='ErrorBadParameters'; + $error++; + } + else + { + $batch = $this->detail_batch[0]->batch; + $batch_id = $this->detail_batch[0]->fk_origin_stock; + $expedition_batch_id = $this->detail_batch[0]->id; + if ($this->entrepot_id != $this->detail_batch[0]->entrepot_id) + { + dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR); + $this->errors[]='ErrorBadParameters'; + $error++; + } + $qty = price2num($this->detail_batch[0]->dluo_qty); + } + } + else if (! empty($this->detail_batch)) + { + $batch = $this->detail_batch->batch; + $batch_id = $this->detail_batch->fk_origin_stock; + $expedition_batch_id = $this->detail_batch->id; + if ($this->entrepot_id != $this->detail_batch->entrepot_id) + { + dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR); + $this->errors[]='ErrorBadParameters'; + $error++; + } + $qty = price2num($this->detail_batch->dluo_qty); + } + + // check parameters + if (! isset($this->id) || ! isset($this->entrepot_id)) + { + dol_syslog(get_class($this).'::update missing line id and/or warehouse id', LOG_ERR); + $this->errors[]='ErrorMandatoryParametersNotProvided'; + $error++; + return -1; + } + + // update lot + + if (! empty($batch) && $conf->productbatch->enabled) + { + dol_syslog(get_class($this)."::update expedition batch id=$expedition_batch_id, batch_id=$batch_id, batch=$batch"); + + if (empty($batch_id) || empty($this->fk_product)) { + dol_syslog(get_class($this).'::update missing fk_origin_stock (batch_id) and/or fk_product', LOG_ERR); + $this->errors[]='ErrorMandatoryParametersNotProvided'; + $error++; + } + + // fetch remaining lot qty + require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; + if (! $error && ($lotArray = ExpeditionLineBatch::fetchAll($this->db, $this->id)) < 0) + { + $this->errors[]=$this->db->lasterror()." - ExpeditionLineBatch::fetchAll"; + $error++; + } + else + { + // caculate new total line qty + foreach ($lotArray as $lot) + { + if ($expedition_batch_id != $lot->id) + { + $remainingQty += $lot->dluo_qty; + } + } + $qty += $remainingQty; + + //fetch lot details + + // fetch from product_lot + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; + $lot = new Productlot($this->db); + if ($lot->fetch(0,$this->fk_product,$batch) < 0) + { + $this->errors[] = $lot->errors; + $error++; + } + if (! $error && ! empty($expedition_batch_id)) + { + // delete lot expedition line + $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch"; + $sql.= " WHERE fk_expeditiondet = ".$this->id; + $sql.= " AND rowid = ".$expedition_batch_id; + + if (!$this->db->query($sql)) + { + $this->errors[]=$this->db->lasterror()." - sql=$sql"; + $error++; + } + } + if (! $error && $this->detail_batch->dluo_qty > 0) + { + // create lot expedition line + if (isset($lot->id)) + { + $shipmentLot = new ExpeditionLineBatch($this->db); + $shipmentLot->batch = $lot->batch; + $shipmentLot->eatby = $lot->eatby; + $shipmentLot->sellby = $lot->sellby; + $shipmentLot->entrepot_id = $this->detail_batch->entrepot_id; + $shipmentLot->dluo_qty = $this->detail_batch->dluo_qty; + $shipmentLot->fk_origin_stock = $batch_id; + if ($shipmentLot->create($this->id) < 0) + { + $this->errors[]=$shipmentLot->errors; + $error++; + } + } + } + } + } + if (! $error) + { + // update line + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; + $sql.= " fk_entrepot = ".$this->entrepot_id; + $sql.= " , qty = ".$qty; + $sql.= " WHERE rowid = ".$this->id; + + if (!$this->db->query($sql)) + { + $this->errors[]=$this->db->lasterror()." - sql=$sql"; + $error++; + } + else + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $this->errors[]=$this->error; + $error++; + } + } + } + } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINESHIPPING_UPDATE',$user); + if ($result < 0) + { + $this->errors[]=$this->error; + $error++; + } + // End call triggers + } + if (!$error) { + $this->db->commit(); + return 1; + } + else + { + 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; + } + } } diff --git a/htdocs/expedition/list.php b/htdocs/expedition/list.php index 009e163eeb0..6cada0b16a9 100644 --- a/htdocs/expedition/list.php +++ b/htdocs/expedition/list.php @@ -111,7 +111,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index 80274f9b579..3d3d8a0de6c 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -39,13 +39,7 @@ if (! empty($conf->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/st if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -$langs->load('orders'); -$langs->load("companies"); -$langs->load("bills"); -$langs->load('propal'); -$langs->load('deliveries'); -$langs->load('stocks'); -$langs->load("productbatch"); +$langs->loadLangs(array('orders',"companies","bills",'propal','deliveries','stocks',"productbatch",'incoterm')); $id=GETPOST('id','int'); // id of order $ref= GETPOST('ref','alpha'); @@ -157,6 +151,15 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } + // Set incoterm + elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) + { + $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + // shipping method if ($action == 'setshippingmethod' && $user->rights->commande->creer) { $object = new Commande($db); @@ -191,9 +194,11 @@ if (empty($reshook)) // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { - $error++; - } + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } else if ($reshook < 0) $error++; } @@ -526,7 +531,7 @@ if ($id > 0 || ! empty($ref)) print '
    '; + print $object->showOutputField($val, $key, $value, '', '', '', 0); + //print dol_escape_htmltag($object->$key, 1, 1); + print '
    '; - else print '
    '; + print '
    '; print ''; print ''; print 'attributes[$object->table_element][ print ''; print ''; - print $extrafields->showInputField($key, $value,'','','',0,$object->id); + print $extrafields->showInputField($key, $value, '', '', '', 0, $object->id); print ''; diff --git a/htdocs/core/tpl/login.tpl.php b/htdocs/core/tpl/login.tpl.php index 251540b004e..62200405c60 100644 --- a/htdocs/core/tpl/login.tpl.php +++ b/htdocs/core/tpl/login.tpl.php @@ -267,7 +267,7 @@ if (!empty($conf->global->MAIN_EASTER_EGG_COMMITSTRIP)) { - '; print ''; print ''; @@ -29,7 +29,7 @@ if (!empty($conf->multicurrency->enabled)) print ''; print ''; -if($conf->global->PRODUCT_USE_UNITS) +if($conf->global->PRODUCT_USE_UNITS) print ''; print ''; diff --git a/htdocs/core/tpl/passwordforgotten.tpl.php b/htdocs/core/tpl/passwordforgotten.tpl.php index 9e155be88c9..32b103c2057 100644 --- a/htdocs/core/tpl/passwordforgotten.tpl.php +++ b/htdocs/core/tpl/passwordforgotten.tpl.php @@ -160,11 +160,11 @@ if (! empty($morelogincontent)) { -'; +// Link for direct external download print ''; print ''; @@ -777,7 +1053,7 @@ if ($action == 'create') // Other attributes $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'socid'=>$socid); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$expe,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) { @@ -1240,6 +1516,7 @@ if ($action == 'create') print ''; print ''; + //print $langs->trans("DetailBatchFormat", $dbatch->batch, dol_print_date($dbatch->eatby,"day"), dol_print_date($dbatch->sellby,"day"), $dbatch->qty); //print $line->fk_product.' - '.$dbatch->batch; print $langs->trans("Batch").': '; @@ -1327,7 +1604,13 @@ if ($action == 'create') print "
    '.$this->tpl['label'].''.$this->tpl['description'].''.$this->tpl['vat_rate'].''.$this->tpl['multicurrency_price'].''.$this->tpl['qty'].''.$langs->trans($this->tpl['unit']).''.$this->tpl['remise_percent'].'
    '.$langs->trans("DirectDownloadInternalLink").''; $modulepart='ecm'; $forcedownload=1; @@ -308,9 +339,10 @@ $fulllink=$urlwithroot.$rellink; print img_picto('','object_globe.png').' '; if ($action != 'edit') print ''; else print $fulllink; -if ($action != 'edit') print ' '.$langs->trans("Download").''; +if ($action != 'edit') print ' '.$langs->trans("Download").''; // No target here. print '
    '; if ($action != 'edit') print $langs->trans("DirectDownloadLink"); else print $langs->trans("FileSharedViaALink"); @@ -332,7 +364,7 @@ if (! empty($object->share)) print img_picto('','object_globe.png').' '; if ($action != 'edit') print ''; else print $fulllink; - if ($action != 'edit') print ' '.$langs->trans("Download").''; + if ($action != 'edit') print ' '.$langs->trans("Download").''; // No target here } else { @@ -374,7 +406,7 @@ if ($action == 'edit') // Confirmation de la suppression d'une ligne categorie if ($action == 'delete_file') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($_GET["section"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile',$urlfile), 'confirm_deletefile', '', 1, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile',$urlfile), 'confirm_deletefile', '', 1, 1); } @@ -385,7 +417,7 @@ if ($action != 'edit') if ($user->rights->ecm->setup) { - print ''.$langs->trans('Edit').''; + print ''.$langs->trans('Edit').''; //print ''.$langs->trans('Cancel').''; } diff --git a/htdocs/ecm/tpl/enablefiletreeajax.tpl.php b/htdocs/ecm/tpl/enablefiletreeajax.tpl.php index aadf3fdba22..3f19e1d666f 100644 --- a/htdocs/ecm/tpl/enablefiletreeajax.tpl.php +++ b/htdocs/ecm/tpl/enablefiletreeajax.tpl.php @@ -26,8 +26,6 @@ theme."/img/working2.gif".'\';'."\n"; - $openeddir='/'; ?> diff --git a/htdocs/expedition/card.php b/htdocs/expedition/card.php index 9fa609d9d76..e85cb70a74d 100644 --- a/htdocs/expedition/card.php +++ b/htdocs/expedition/card.php @@ -7,7 +7,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2013 Marcos García * Copyright (C) 2014 Cedric GROSS - * Copyright (C) 2014-2015 Francis Appels + * Copyright (C) 2014-2017 Francis Appels * Copyright (C) 2015 Claudio Aschieri * Copyright (C) 2016 Ferran Marcet * Copyright (C) 2016 Yasser Carreón @@ -69,6 +69,7 @@ $id = $origin_id; if (empty($origin_id)) $origin_id = GETPOST('origin_id','int'); // Id of order or propal if (empty($origin_id)) $origin_id = GETPOST('object_id','int'); // Id of order or propal $ref=GETPOST('ref','alpha'); +$line_id = GETPOST('lineid','int')?GETPOST('lineid','int'):''; // Security check $socid=''; @@ -173,9 +174,11 @@ if (empty($reshook)) $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { - $error++; - } + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } else if ($reshook < 0) $error++; } @@ -212,8 +215,8 @@ if (empty($reshook)) $objectsrc->fetch($object->origin_id); $object->socid = $objectsrc->socid; - $object->ref_customer = ''; // We don't use $objectsrc->ref_client, this is ref or order not shipment - $object->model_pdf = GETPOST('model','alpha'); + $object->ref_customer = GETPOST('ref_customer','alpha'); + $object->model_pdf = GETPOST('model'); $object->date_delivery = $date_delivery; // Date delivery planed $object->fk_delivery_address = $objectsrc->fk_delivery_address; $object->shipping_method_id = GETPOST('shipping_method_id','int'); @@ -596,6 +599,279 @@ if (empty($reshook)) } } + /* + * delete a line + */ + elseif ($action == 'deleteline' && ! empty($line_id)) + { + $object->fetch($id); + $lines = $object->lines; + $line = new ExpeditionLigne($db); + + $num_prod = count($lines); + for ($i = 0 ; $i < $num_prod ; $i++) + { + if ($lines[$i]->id == $line_id) + { + if (count($lines[$i]->details_entrepot) > 1) + { + // delete multi warehouse lines + foreach ($lines[$i]->details_entrepot as $details_entrepot) { + $line->id = $details_entrepot->line_id; + if (! $error && $line->delete($user) < 0) + { + $error++; + } + } + } + else + { + // delete single warehouse line + $line->id = $line_id; + if (! $error && $line->delete($user) < 0) + { + $error++; + } + } + } + unset($_POST["lineid"]); + } + + if(! $error) { + header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id); + exit(); + } + else + { + setEventMessages($line->error, $line->errors, 'errors'); + } + } + + /* + * Update a line + */ + else if ($action == 'updateline' && $user->rights->expedition->creer && GETPOST('save')) + { + // Clean parameters + + $qty=0; + $entrepot_id = 0; + $batch_id = 0; + + $lines = $object->lines; + $num_prod = count($lines); + for ($i = 0 ; $i < $num_prod ; $i++) + { + if ($lines[$i]->id == $line_id) + { + // line to update + $line = new ExpeditionLigne($db); + // Extrafields Lines + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $line->array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // Unset extrafield POST Data + if (is_array($extralabelsline)) { + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + $line->fk_product = $lines[$i]->fk_product; + if (is_array($lines[$i]->detail_batch) && count($lines[$i]->detail_batch) > 0) + { + // line with lot + foreach ($lines[$i]->detail_batch as $detail_batch) + { + $lotStock = new Productbatch($db); + $batch="batchl".$detail_batch->fk_expeditiondet."_".$detail_batch->fk_origin_stock; + $qty = "qtyl".$detail_batch->fk_expeditiondet.'_'.$detail_batch->id; + $batch_id = GETPOST($batch,'int'); + $batch_qty = GETPOST($qty, 'int'); + if (! empty($batch_id) && ($batch_id != $detail_batch->fk_origin_stock || $batch_qty != $detail_batch->dluo_qty)) + { + if ($lotStock->fetch($batch_id) > 0 && $line->fetch($detail_batch->fk_expeditiondet) > 0) // $line is ExpeditionLine + { + if ($lines[$i]->entrepot_id != 0) + { + // allow update line entrepot_id if not multi warehouse shipping + $line->entrepot_id = $lotStock->warehouseid; + } + + // detail_batch can be an object with keys, or an array of ExpeditionLineBatch + if (empty($line->detail_batch)) $line->detail_batch=new stdClass(); + + $line->detail_batch->fk_origin_stock = $batch_id; + $line->detail_batch->batch = $lotStock->batch; + $line->detail_batch->id = $detail_batch->id; + $line->detail_batch->entrepot_id = $lotStock->warehouseid; + $line->detail_batch->dluo_qty = $batch_qty; + if ($line->update($user) < 0) { + setEventMessages($line->error, $line->errors, 'errors'); + $error++; + } + } + else + { + setEventMessages($lotStock->error, $lotStock->errors, 'errors'); + $error++; + } + } + unset($_POST[$batch]); + unset($_POST[$qty]); + } + // add new batch + $lotStock = new Productbatch($db); + $batch="batchl".$line_id."_0"; + $qty = "qtyl".$line_id."_0"; + $batch_id = GETPOST($batch,'int'); + $batch_qty = GETPOST($qty, 'int'); + $lineIdToAddLot = 0; + if ($batch_qty > 0 && ! empty($batch_id)) + { + if ($lotStock->fetch($batch_id) > 0) + { + // check if lotStock warehouse id is same as line warehouse id + if ($lines[$i]->entrepot_id > 0) + { + // single warehouse shipment line + if ($lines[i]->entrepot_id == $lotStock->warehouseid) + { + $lineIdToAddLot = $line_id; + } + } + else if (count($lines[$i]->details_entrepot) > 1) + { + // multi warehouse shipment lines + foreach ($lines[$i]->details_entrepot as $detail_entrepot) + { + if ($detail_entrepot->entrepot_id == $lotStock->warehouseid) + { + $lineIdToAddLot = $detail_entrepot->line_id; + } + } + } + if ($lineIdToAddLot) + { + // add lot to existing line + if ($line->fetch($lineIdToAddLot) > 0) + { + $line->detail_batch->fk_origin_stock = $batch_id; + $line->detail_batch->batch = $lotStock->batch; + $line->detail_batch->entrepot_id = $lotStock->warehouseid; + $line->detail_batch->dluo_qty = $batch_qty; + if ($line->update($user) < 0) { + setEventMessages($line->error, $line->errors, 'errors'); + $error++; + } + } + else + { + setEventMessages($line->error, $line->errors, 'errors'); + $error++; + } + } + else + { + // create new line with new lot + $line->origin_line_id = $lines[$i]->origin_line_id; + $line->entrepot_id = $lotStock->warehouseid; + $line->detail_batch[0] = new ExpeditionLineBatch($db); + $line->detail_batch[0]->fk_origin_stock = $batch_id; + $line->detail_batch[0]->batch = $lotStock->batch; + $line->detail_batch[0]->entrepot_id = $lotStock->warehouseid; + $line->detail_batch[0]->dluo_qty = $batch_qty; + if ($object->create_line_batch($line, $line->array_options) < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + } + } + else + { + setEventMessages($lotStock->error, $lotStock->errors, 'errors'); + $error++; + } + } + } + else + { + // line without lot + if ($lines[$i]->entrepot_id > 0) + { + // single warehouse shipment line + $stockLocation="entl".$line_id; + $qty = "qtyl".$line_id; + $line->id = $line_id; + $line->entrepot_id = GETPOST($stockLocation,'int'); + $line->qty = GETPOST($qty, 'int'); + if ($line->update($user) < 0) { + setEventMessages($line->error, $line->errors, 'errors'); + $error++; + } + unset($_POST[$stockLocation]); + unset($_POST[$qty]); + } + else if (count($lines[$i]->details_entrepot) > 1) + { + // multi warehouse shipment lines + foreach ($lines[$i]->details_entrepot as $detail_entrepot) + { + if (! $error) { + $stockLocation="entl".$detail_entrepot->line_id; + $qty = "qtyl".$detail_entrepot->line_id; + $warehouse = GETPOST($stockLocation,'int'); + if (!empty ($warehouse)) + { + $line->id = $detail_entrepot->line_id; + $line->entrepot_id = $warehouse; + $line->qty = GETPOST($qty, 'int'); + if ($line->update($user) < 0) { + setEventMessages($line->error, $line->errors, 'errors'); + $error++; + } + } + unset($_POST[$stockLocation]); + unset($_POST[$qty]); + } + } + } + } + } + } + + unset($_POST["lineid"]); + + if (! $error) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + // Define output language + $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); + } + + $ret = $object->fetch($object->id); // Reload to get new records + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } + else + { + header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id); // Pour reaffichage de la fiche en cours d'edition + exit(); + } + } + + else if ($action == 'updateline' && $user->rights->expedition->creer && GETPOST('cancel','alpha') == $langs->trans('Cancel')) { + header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id); // Pour reaffichage de la fiche en cours d'edition + exit(); + } + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; // Actions to send emails @@ -691,7 +967,7 @@ if ($action == 'create') else if ($origin == 'propal') print $langs->trans('RefCustomerOrder'); else print $langs->trans('RefCustomer'); print ''; - print $object->ref_client; + print ''; print '
    "; - print '
    '; + print '
    '; + + print '
    '; + print ''; + print '  '; + print ''; // Cancel for create does not post form if we don't know the backtopage + print '
    '; print ''; @@ -1730,6 +2013,15 @@ else if ($id || $ref) /* * Lines of products */ + if ($action == 'editline') + { + print '
    + + + + + '; + } print '
    '; print '
    '; @@ -1741,34 +2033,62 @@ else if ($id || $ref) } print '
    '.$langs->trans("Products").''.$langs->trans("QtyOrdered").''.$langs->trans("QtyToShip").''.$langs->trans("QtyInOtherShipments").''; + if ($object->statut <= 1) + { + print $langs->trans("QtyToShip").' - '; + } + else + { + print $langs->trans("QtyShipped").' - '; + } + if (! empty($conf->stock->enabled)) + { + print $langs->trans("WarehouseSource").' - '; + } + if (! empty($conf->productbatch->enabled)) + { + print $langs->trans("Batch"); + } + print ''.$langs->trans("QtyShipped").''.$langs->trans("QtyToShip").''.$langs->trans("QtyShipped").''.$langs->trans("WarehouseSource").''.$langs->trans("QtyInOtherShipments").''.$langs->trans("Batch").''.$langs->trans("CalculatedWeight").''.$langs->trans("CalculatedVolume").''.$langs->trans("Size").''.$langs->trans("WarehouseSource").''.$langs->trans("Batch").'
    '.$lines[$i]->qty_asked.''.$lines[$i]->qty_shipped.''; + if (is_array($lines[$i]->detail_batch) && count($lines[$i]->detail_batch) > 0) + { + $line = new ExpeditionLigne($db); + foreach ($lines[$i]->detail_batch as $detail_batch) + { + print ''; + // Qty to ship or shipped + print ''; + // Batch number managment + if ($lines[$i]->entrepot_id == 0) + { + // only show lot numbers from src warehouse when shipping from multiple warehouses + $line->fetch($detail_batch->fk_expeditiondet); + } + print ''; + print ''; + } + // add a 0 qty lot row to be able to add a lot + print ''; + // Qty to ship or shipped + print ''; + // Batch number managment + print ''; + print ''; + } + else if (! empty($conf->stock->enabled)) + { + if ($lines[$i]->entrepot_id > 0) + { + print ''; + // Qty to ship or shipped + print ''; + // Warehouse source + print ''; + // Batch number managment + print ''; + print ''; + } + else if (count($lines[$i]->details_entrepot) > 1) + { + foreach ($lines[$i]->details_entrepot as $detail_entrepot) + { + print ''; + // Qty to ship or shipped + print ''; + // Warehouse source + print ''; + // Batch number managment + print ''; + print ''; + } + } + } + print '
    ' . '' . '' . $formproduct->selectLotStock($detail_batch->fk_origin_stock, 'batchl'.$detail_batch->fk_expeditiondet.'_'.$detail_batch->fk_origin_stock, '', 1, 0, $lines[$i]->fk_product, $line->entrepot_id). '
    ' . '' . '' . $formproduct->selectLotStock('', 'batchl'.$line_id.'_0', '', 1, 0, $lines[$i]->fk_product). '
    ' . '' . '' . $formproduct->selectWarehouses($lines[$i]->entrepot_id, 'entl'.$line_id, '', 1, 0, $lines[$i]->fk_product, '', 1). ' - ' . $langs->trans("NA") . '
    ' . '' . '' . $formproduct->selectWarehouses($detail_entrepot->entrepot_id, 'entl'.$detail_entrepot->line_id, '', 1, 0, $lines[$i]->fk_product, '', 1) . ' - ' . $langs->trans("NA") . '
    '.$lines[$i]->qty_shipped.''; + if ($lines[$i]->entrepot_id > 0) + { + $entrepot = new Entrepot($db); + $entrepot->fetch($lines[$i]->entrepot_id); + print $entrepot->getNomUrl(1); + } + else if (count($lines[$i]->details_entrepot) > 1) + { + $detail = ''; + foreach ($lines[$i]->details_entrepot as $detail_entrepot) + { + if ($detail_entrepot->entrepot_id > 0) + { + $entrepot = new Entrepot($db); + $entrepot->fetch($detail_entrepot->entrepot_id); + $detail.= $langs->trans("DetailWarehouseFormat",$entrepot->libelle,$detail_entrepot->qty_shipped).'
    '; + } + } + print $form->textwithtooltip(img_picto('', 'object_stock').' '.$langs->trans("DetailWarehouseNumber"),$detail); + } + print '
    '; + if ($lines[$i]->product_tobatch) + { + $detail = ''; + foreach ($lines[$i]->detail_batch as $dbatch) + { + $detail.= $langs->trans("DetailBatchFormat",$dbatch->batch,dol_print_date($dbatch->eatby,"day"),dol_print_date($dbatch->sellby,"day"),$dbatch->dluo_qty).'
    '; + } + print $form->textwithtooltip(img_picto('', 'object_barcode').' '.$langs->trans("DetailBatchNumber"),$detail); + } + else + { + print $langs->trans("NA"); + } + print '
    '; if ($lines[$i]->fk_product_type == 0) print $lines[$i]->weight*$lines[$i]->qty_shipped.' '.measuring_units_string($lines[$i]->weight_units,"weight"); @@ -1941,55 +2375,28 @@ else if ($id || $ref) // Size //print ''.$lines[$i]->volume*$lines[$i]->qty_shipped.' '.measuring_units_string($lines[$i]->volume_units,"volume").''; - if ($lines[$i]->entrepot_id > 0) - { - $entrepot = new Entrepot($db); - $entrepot->fetch($lines[$i]->entrepot_id); - print $entrepot->getNomUrl(1); - } - else if (count($lines[$i]->details_entrepot) > 1) - { - $detail = ''; - foreach ($lines[$i]->details_entrepot as $detail_entrepot) - { - if ($detail_entrepot->entrepot_id > 0) - { - $entrepot = new Entrepot($db); - $entrepot->fetch($detail_entrepot->entrepot_id); - $detail.= $langs->trans("DetailWarehouseFormat",$entrepot->libelle,$detail_entrepot->qty_shipped).'
    '; - } - } - print $form->textwithtooltip(img_picto('', 'object_stock').' '.$langs->trans("DetailWarehouseNumber"),$detail); - } - print '
    '; + print '
    '; + print '
    '; } - - // Batch number managment - if (! empty($conf->productbatch->enabled)) + else if ($object->statut == 0) { - if (isset($lines[$i]->detail_batch)) + // edit-delete buttons + print '
    '; + print 'id . '">' . img_edit() . ''; + print ''; + print 'id . '">' . img_delete() . ''; + print ''; - if ($lines[$i]->product_tobatch) - { - $detail = ''; - foreach ($lines[$i]->detail_batch as $dbatch) - { - $detail.= $langs->trans("DetailBatchFormat",$dbatch->batch,dol_print_date($dbatch->eatby,"day"),dol_print_date($dbatch->sellby,"day"),$dbatch->dluo_qty).'
    '; - } - print $form->textwithtooltip(img_picto('', 'object_barcode').' '.$langs->trans("DetailBatchNumber"),$detail); - } - else - { - print $langs->trans("NA"); - } - print '
    '; print $langs->trans('IncotermLabel'); print ''; - if ($user->rights->commande->creer) print ''.img_edit().''; + if ($user->rights->commande->creer) print ''.img_edit().''; else print ' '; print '
    '; print ''; diff --git a/htdocs/expensereport/ajax/ajaxik.php b/htdocs/expensereport/ajax/ajaxik.php index e1856f438b0..04baab6d7a0 100644 --- a/htdocs/expensereport/ajax/ajaxik.php +++ b/htdocs/expensereport/ajax/ajaxik.php @@ -64,12 +64,12 @@ else else { $range = ExpenseReportIk::getRangeByUser($userauthor, $fk_c_exp_tax_cat); - + if (empty($range)) echo json_encode(array('error' => $langs->transnoentitiesnoconv('ErrorRecordNotFound'), 'range' => $range)); else { - $offset = price($range->offset, 0, $langs, 1, -1, -1, $conf->currency); - echo json_encode(array('up' => $range->coef, 'offset' => $range->offset, 'title' => $langs->transnoentitiesnoconv('ExpenseRangeOffset', $offset), 'comment' => 'offset should be apply on addline or updateline')); + $ikoffset = price($range->ikoffset, 0, $langs, 1, -1, -1, $conf->currency); + echo json_encode(array('up' => $range->coef, 'ikoffset' => $range->ikoffset, 'title' => $langs->transnoentitiesnoconv('ExpenseRangeOffset', $offset), 'comment' => 'offset should be apply on addline or updateline')); } } } diff --git a/htdocs/expensereport/card.php b/htdocs/expensereport/card.php index 16dd8dbf8b1..29a058f2d33 100644 --- a/htdocs/expensereport/card.php +++ b/htdocs/expensereport/card.php @@ -296,9 +296,11 @@ if (empty($reshook)) // some hooks if (empty($reshook)) { $result = $object->insertExtraFields(); - if ($result < 0) { - $error++; - } + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } else if ($reshook < 0) $error++; } @@ -2396,8 +2398,8 @@ if ($action != 'presend') $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->expensereport->dir_output . "/" . dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed = 1; - $delallowed = 1; + $genallowed = $user->rights->expensereport->export; + $delallowed = $user->rights->expensereport->export; $var = true; print $formfile->showdocuments('expensereport',$filename,$filedir,$urlsource,$genallowed,$delallowed); $somethingshown = $formfile->numoffiles; diff --git a/htdocs/expensereport/class/api_expensereports.class.php b/htdocs/expensereport/class/api_expensereports.class.php index d1f123b791f..e89f4e35cdc 100644 --- a/htdocs/expensereport/class/api_expensereports.class.php +++ b/htdocs/expensereport/class/api_expensereports.class.php @@ -94,7 +94,7 @@ class ExpenseReports extends DolibarrApi * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" * @return array Array of Expense Report objects */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $user_ids = 0, $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -271,7 +271,7 @@ class ExpenseReports extends DolibarrApi ); if ($updateRes > 0) { - return $this->get($id)->line->rowid; + return $updateRes; } return false; diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index 63e4a3d351b..437114ab7df 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -1544,7 +1544,6 @@ class ExpenseReport extends CommonObject if ($short) return $url; - $picto='trip'; $label = '' . $langs->trans("ShowExpenseReport") . ''; if (! empty($this->ref)) $label .= '
    ' . $langs->trans('Ref') . ': ' . $this->ref; @@ -1583,8 +1582,11 @@ class ExpenseReport extends CommonObject $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend.' '); - $result.=$linkstart.($max?dol_trunc($ref,$max):$ref).$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; } @@ -1833,13 +1835,13 @@ class ExpenseReport extends CommonObject return false; } - if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) $offset = $range->offset; - else $offset = $range->offset / 12; // The amount of offset is a global value for the year + if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) $ikoffset = $range->ikoffset; + else $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year - // Test if offset has been applied for the current month + // Test if ikoffset has been applied for the current month if (!$this->offsetAlreadyGiven()) { - $new_up = $range->coef + ($offset / $this->line->qty); + $new_up = $range->coef + ($ikoffset / $this->line->qty); $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller); $this->line->value_unit = $tmp[5]; @@ -1854,7 +1856,7 @@ class ExpenseReport extends CommonObject } /** - * If the sql find any rows then the offset is already given (offset is applied at the first expense report line) + * If the sql find any rows then the ikoffset is already given (ikoffset is applied at the first expense report line) * * @return bool */ diff --git a/htdocs/expensereport/class/expensereport_ik.class.php b/htdocs/expensereport/class/expensereport_ik.class.php index 41170ce2fd4..da5c68da91b 100644 --- a/htdocs/expensereport/class/expensereport_ik.class.php +++ b/htdocs/expensereport/class/expensereport_ik.class.php @@ -21,7 +21,7 @@ * \ingroup expenseik * \brief File of class to manage expense ik */ - + require_once DOL_DOCUMENT_ROOT.'/core/class/coreobject.class.php'; /** @@ -32,30 +32,30 @@ class ExpenseReportIk extends CoreObject public $element='expenseik'; public $table_element='expensereport_ik'; public $fk_element='fk_expense_ik'; - + /** * c_exp_tax_cat Id * @var int */ public $fk_c_exp_tax_cat; - + /** * c_exp_tax_range id * @var int */ public $fk_range; - + /** * Coef * @var double */ public $coef; - + /** * Offset * @var double */ - public $offset; + public $ikoffset; /** * Attribute object linked with database @@ -66,7 +66,7 @@ class ExpenseReportIk extends CoreObject ,'fk_c_exp_tax_cat'=>array('type'=>'integer','index'=>true) ,'fk_range'=>array('type'=>'integer','index'=>true) ,'coef'=>array('type'=>'double') - ,'offset'=>array('type'=>'double') + ,'ikoffset'=>array('type'=>'double') ); /** @@ -74,35 +74,35 @@ class ExpenseReportIk extends CoreObject * * @param DoliDB $db Database handler */ - public function __construct(DoliDB &$db) + public function __construct(DoliDB &$db) { global $conf; parent::__construct($db); parent::init(); - + $this->errors = array(); } - + /** * Return expense categories in array - * + * * @param int $mode 1=only active; 2=only inactive; other value return all * @return array of category */ public static function getTaxCategories($mode=1) { global $db; - + $categories = array(); - + $sql = 'SELECT rowid, label, entity, active'; $sql.= ' FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat'; $sql.= ' WHERE entity IN (0,'. getEntity('').')'; if ($mode == 1) $sql.= ' AND active = 1'; elseif ($mode == 2) $sql.= 'AND active = 0'; - + dol_syslog(get_called_class().'::getTaxCategories sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) @@ -116,23 +116,23 @@ class ExpenseReportIk extends CoreObject { dol_print_error($db); } - + return $categories; } - + public static function getRangeByUser(User $userauthor, $fk_c_exp_tax_cat) { $default_range = (int) $userauthor->default_range; // if not defined, then 0 $ranges = self::getRangesByCategory($fk_c_exp_tax_cat); - + // substract 1 because array start from 0 if (empty($ranges) || !isset($ranges[$default_range-1])) return false; else return $ranges[$default_range-1]; } - + /** * Return an array of ranges for a category - * + * * @param int $fk_c_exp_tax_cat category id * @param int $active active * @return array @@ -140,15 +140,15 @@ class ExpenseReportIk extends CoreObject public static function getRangesByCategory($fk_c_exp_tax_cat, $active=1) { global $db; - + $ranges = array(); - + $sql = 'SELECT r.rowid FROM '.MAIN_DB_PREFIX.'c_exp_tax_range r'; if ($active) $sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; $sql.= ' WHERE r.fk_c_exp_tax_cat = '.$fk_c_exp_tax_cat; if ($active) $sql.= ' AND r.active = 1 AND c.active = 1'; $sql.= ' ORDER BY r.range_ik'; - + dol_syslog(get_called_class().'::getRangesByCategory sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) @@ -160,7 +160,7 @@ class ExpenseReportIk extends CoreObject { $object = new ExpenseReportIk($db); $object->fetch($obj->rowid); - + $ranges[] = $object; } } @@ -169,28 +169,28 @@ class ExpenseReportIk extends CoreObject { dol_print_error($db); } - + return $ranges; } - + /** * Return an array of ranges grouped by category - * + * * @return array */ public static function getAllRanges() { global $db; - + $ranges = array(); - + $sql = ' SELECT r.rowid, r.fk_c_exp_tax_cat, r.range_ik, c.label, i.rowid as fk_expense_ik, r.active as range_active, c.active as cat_active'; $sql.= ' FROM '.MAIN_DB_PREFIX.'c_exp_tax_range r'; $sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'expensereport_ik i ON (r.rowid = i.fk_range)'; $sql.= ' WHERE r.entity IN (0, '. getEntity('').')'; $sql.= ' ORDER BY r.fk_c_exp_tax_cat, r.range_ik'; - + dol_syslog(get_called_class().'::getAllRanges sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) @@ -200,7 +200,7 @@ class ExpenseReportIk extends CoreObject $ik = new ExpenseReportIk($db); if ($obj->fk_expense_ik > 0) $ik->fetch($obj->fk_expense_ik); $obj->ik = $ik; - + if (!isset($ranges[$obj->fk_c_exp_tax_cat])) $ranges[$obj->fk_c_exp_tax_cat] = array('label' => $obj->label, 'active' => $obj->cat_active, 'ranges' => array()); $ranges[$obj->fk_c_exp_tax_cat]['ranges'][] = $obj; } @@ -209,20 +209,20 @@ class ExpenseReportIk extends CoreObject { dol_print_error($db); } - + return $ranges; } - + /** * Return the max number of range by a category - * + * * @param int $default_c_exp_tax_cat id * @return int */ public static function getMaxRangeNumber($default_c_exp_tax_cat=0) { global $db,$conf; - + $sql = 'SELECT MAX(counted) as nbRange FROM ('; $sql.= ' SELECT COUNT(*) as counted'; $sql.= ' FROM '.MAIN_DB_PREFIX.'c_exp_tax_range r'; @@ -230,7 +230,7 @@ class ExpenseReportIk extends CoreObject if ($default_c_exp_tax_cat > 0) $sql .= ' AND r.fk_c_exp_tax_cat = '.$default_c_exp_tax_cat; $sql.= ' GROUP BY r.fk_c_exp_tax_cat'; $sql .= ') as counts'; - + dol_syslog(get_called_class().'::getMaxRangeNumber sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); if ($resql) @@ -242,7 +242,7 @@ class ExpenseReportIk extends CoreObject { dol_print_error($db); } - + return 0; } } diff --git a/htdocs/expensereport/class/expensereport_rule.class.php b/htdocs/expensereport/class/expensereport_rule.class.php index ba060e62a77..11bc480bf4f 100644 --- a/htdocs/expensereport/class/expensereport_rule.class.php +++ b/htdocs/expensereport/class/expensereport_rule.class.php @@ -96,15 +96,15 @@ class ExpenseReportRule extends CoreObject - /** - * Attribute object linked with database - * @var array - */ + /** + * Attribute object linked with database + * @var array + */ protected $fields=array( 'rowid'=>array('type'=>'integer','index'=>true) ,'dates'=>array('type'=>'date') ,'datee'=>array('type'=>'date') - ,'amount'=>array('type'=>'double') + ,'amount'=>array('type'=>'double') ,'restrictive'=>array('type'=>'integer') ,'fk_user'=>array('type'=>'integer') ,'fk_usergroup'=>array('type'=>'integer') @@ -114,16 +114,16 @@ class ExpenseReportRule extends CoreObject ,'entity'=>array('type'=>'integer') ); - /** - * Constructor - * - * @param DoliDB $db Database handler - */ + /** + * Constructor + * + * @param DoliDB $db Database handler + */ public function __construct(DoliDB &$db) { global $conf; - parent::__construct($db); + parent::__construct($db); parent::init(); $this->errors = array(); diff --git a/htdocs/expensereport/list.php b/htdocs/expensereport/list.php index 0c34ff43ef0..30d5eea98d6 100644 --- a/htdocs/expensereport/list.php +++ b/htdocs/expensereport/list.php @@ -31,6 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/usergroups.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php'; $langs->load("companies"); $langs->load("users"); @@ -62,6 +64,7 @@ $pagenext = $page + 1; if (!$sortorder) $sortorder="DESC"; if (!$sortfield) $sortfield="d.date_debut"; +$id = GETPOST('id', 'int'); $sall = GETPOST('sall', 'alphanohtml'); $search_ref = GETPOST('search_ref'); @@ -120,10 +123,14 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } +$canedituser=(! empty($user->admin) || $user->rights->user->user->creer); + +$object = new ExpenseReport($db); +$objectuser = new User($db); /* @@ -170,6 +177,51 @@ if (empty($reshook)) $permtodelete = $user->rights->expensereport->supprimer; $uploaddir = $conf->expensereport->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + + if ($action == 'update' && ! $cancel) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + if ($canedituser) // Case we can edit all field + { + $error = 0; + + if (!$error) + { + $objectuser->fetch($id); + + $objectuser->oldcopy = clone $objectuser; + + $db->begin(); + + $objectuser->default_range = GETPOST('default_range'); + $objectuser->default_c_exp_tax_cat = GETPOST('default_c_exp_tax_cat'); + + if (!$error) { + $ret = $objectuser->update($user); + if ($ret < 0) { + $error++; + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorLoginAlreadyExists", $objectuser->login), null, 'errors'); + } + else + { + setEventMessages($objectuser->error, $objectuser->errors, 'errors'); + } + } + } + + if (!$error && !count($objectuser->errors)) { + setEventMessages($langs->trans("UserModified"), null, 'mesgs'); + $db->commit(); + } + else { + $db->rollback(); + } + } + } + } } @@ -181,12 +233,26 @@ $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); +$fuser = new User($db); + $title = $langs->trans("ListOfTrips"); llxHeader('', $title); $max_year = 5; $min_year = 5; +// Récupération de l'ID de l'utilisateur +$user_id = $user->id; + +if ($id > 0) +{ + // Charge utilisateur edite + $fuser->fetch($id, '', '', 1); + $fuser->getrights(); + $user_id = $fuser->id; + + $search_user = $user_id; +} $sql = "SELECT d.rowid, d.ref, d.fk_user_author, d.total_ht, d.total_tva, d.total_ttc, d.fk_statut as status,"; $sql.= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_valid, d.date_approve, d.note_private, d.note_public,"; @@ -322,14 +388,103 @@ if ($resql) if ($optioncss != '') print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; + if ($id > 0) print ''; - $title = $langs->trans("ListTripsAndExpenses"); - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_generic.png', 0, '', '', $limit); + if ($id > 0) // For user tab + { + $title = $langs->trans("User"); + $linkback = ''.$langs->trans("BackToList").''; + $head = user_prepare_head($fuser); + + dol_fiche_head($head, 'expensereport', $title, -1, 'user'); + + dol_banner_tab($fuser,'id',$linkback,$user->rights->user->user->lire || $user->admin); + + print '
    '; + print '
    '; + + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) + { + print ''; + + if ($action == 'edit') + { + print ''; + print ''; + + print ''; + print ''; + } + else + { + print ''; + print ''; + + print ''; + print ''; + } + + print '
    '.$langs->trans("DefaultCategoryCar").''; + print $form->selectExpenseCategories($fuser->default_c_exp_tax_cat, 'default_c_exp_tax_cat', 1); + print '
    '.$langs->trans("DefaultRangeNumber").''; + $maxRangeNum = ExpenseReportIk::getMaxRangeNumber($fuser->default_c_exp_tax_cat); + print $form->selectarray('default_range', range(0, $maxRangeNum), $fuser->default_range); + print '
    '.$langs->trans("DefaultCategoryCar").''; + print dol_getIdFromCode($db, $fuser->default_c_exp_tax_cat, 'c_exp_tax_cat', 'rowid', 'label'); + print '
    '.$langs->trans("DefaultRangeNumber").''; + print $fuser->default_range; + print '
    '; + } + + print '
    '; + + /*if (empty($conf->global->HOLIDAY_HIDE_BALANCE)) + { + print '
    '; + + print '
    '; + + showMyBalance($holiday, $user_id); + }*/ + + dol_fiche_end(); + + if ($action != 'edit') + { + print '
    '; + + if (!empty($conf->global->MAIN_USE_EXPENSE_IK)) + { + print ''.$langs->trans("Modify").''; + } + + $canedit=(($user->id == $user_id && $user->rights->expensereport->creer) || ($user->id != $user_id)); + + // Boutons d'actions + if ($canedit) + { + print ''.$langs->trans("AddTrip").''; + } + + print '
    '; + } + else + { + print '
    '; + print ''; + print '

    '; + } + } + else + { + $title = $langs->trans("ListTripsAndExpenses"); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_generic.png', 0, '', '', $limit); + } if ($massaction == 'presend') { @@ -596,22 +751,22 @@ if ($resql) } // Start date if (! empty($arrayfields['d.date_debut']['checked'])) { - print ''.($obj->date_debut > 0 ? dol_print_date($obj->date_debut, 'day') : '').''; + print ''.($obj->date_debut > 0 ? dol_print_date($db->jdate($obj->date_debut), 'day') : '').''; if (! $i) $totalarray['nbfield']++; } // End date if (! empty($arrayfields['d.date_fin']['checked'])) { - print ''.($obj->date_fin > 0 ? dol_print_date($obj->date_fin, 'day') : '').''; + print ''.($obj->date_fin > 0 ? dol_print_date($db->jdate($obj->date_fin), 'day') : '').''; if (! $i) $totalarray['nbfield']++; } // Date validation if (! empty($arrayfields['d.date_valid']['checked'])) { - print ''.($obj->date_valid > 0 ? dol_print_date($obj->date_valid, 'day') : '').''; + print ''.($obj->date_valid > 0 ? dol_print_date($db->jdate($obj->date_valid), 'day') : '').''; if (! $i) $totalarray['nbfield']++; } // Date approval if (! empty($arrayfields['d.date_approve']['checked'])) { - print ''.($obj->date_approve > 0 ? dol_print_date($obj->date_approve, 'day') : '').''; + print ''.($obj->date_approve > 0 ? dol_print_date($db->jdate($obj->date_approve), 'day') : '').''; if (! $i) $totalarray['nbfield']++; } // Amount HT @@ -743,22 +898,24 @@ if ($resql) print ''."\n"; - - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + if (empty($id)) { - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - $filedir=$diroutputmassaction; - $genallowed=$user->rights->expensereport->lire; - $delallowed=$user->rights->expensereport->lire; + $filedir=$diroutputmassaction; + $genallowed=$user->rights->expensereport->lire; + $delallowed=$user->rights->expensereport->creer; - print $formfile->showdocuments('massfilesarea_expensereport','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
    '.$langs->trans("ShowTempMassFilesArea").''; + print $formfile->showdocuments('massfilesarea_expensereport','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
    '.$langs->trans("ShowTempMassFilesArea").''; + } } } else diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index 49c60078666..4c15a7c4480 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -99,6 +99,7 @@ $entitytolang = array( 'subproduct' => 'SubProduct', 'service' => 'Service', 'stock' => 'Stock', + 'movement' => 'StockMovement', 'batch' => 'Batch', 'warehouse' => 'Warehouse', 'category' => 'Category', diff --git a/htdocs/fichinter/admin/fichinter_extrafields.php b/htdocs/fichinter/admin/fichinter_extrafields.php index bab7572e60a..1afe5feaeed 100644 --- a/htdocs/fichinter/admin/fichinter_extrafields.php +++ b/htdocs/fichinter/admin/fichinter_extrafields.php @@ -41,7 +41,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/fichinter/admin/fichinterdet_extrafields.php b/htdocs/fichinter/admin/fichinterdet_extrafields.php index 5fadc3f4c2c..cd21b3d9590 100644 --- a/htdocs/fichinter/admin/fichinterdet_extrafields.php +++ b/htdocs/fichinter/admin/fichinterdet_extrafields.php @@ -41,7 +41,7 @@ $form = new Form($db); // List of supported format $tmptype2label=ExtraFields::$type2label; $type2label=array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->transnoentitiesnoconv($val); $action=GETPOST('action', 'alpha'); $attrname=GETPOST('attrname', 'alpha'); diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index 52c23f551d2..d2e6dd26765 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -60,6 +60,7 @@ $ref = GETPOST('ref','alpha'); $socid = GETPOST('socid','int'); $contratid = GETPOST('contratid','int'); $action = GETPOST('action','alpha'); +$cancel = GETPOST('cancel','alpha'); $confirm = GETPOST('confirm','alpha'); $mesg = GETPOST('msg','alpha'); $origin=GETPOST('origin','alpha'); @@ -105,6 +106,16 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { + if ($cancel) + { + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + $action=''; + } + 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 @@ -201,11 +212,11 @@ if (empty($reshook)) else if ($action == 'add' && $user->rights->ficheinter->creer) { $object->socid = $socid; - $object->duration = GETPOST('duration','int'); + $object->duration = GETPOST('duration','int'); $object->fk_project = GETPOST('projectid','int'); $object->fk_contrat = GETPOST('contratid','int'); $object->author = $user->id; - $object->description = GETPOST('description'); + $object->description = GETPOST('description','none'); $object->ref = $ref; $object->modelpdf = GETPOST('model','alpha'); $object->note_private = GETPOST('note_private','none'); @@ -276,7 +287,7 @@ if (empty($reshook)) $fk_parent_line=0; $num=count($lines); - for ($i=0;$i<$num;$i++) + for ($i=0; $i<$num; $i++) { $product_type=($lines[$i]->product_type?$lines[$i]->product_type:Product::TYPE_PRODUCT); @@ -829,7 +840,7 @@ if ($action == 'create') $soc=new Societe($db); - print load_fiche_titre($langs->trans("AddIntervention")); + print load_fiche_titre($langs->trans("AddIntervention"), '', 'title_commercial'); dol_htmloutput_mesg($mesg); @@ -1008,6 +1019,30 @@ if ($action == 'create') $newclassname=$classname; if ($newclassname=='Propal') $newclassname='CommercialProposal'; print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; + + // Amount + /* Hide amount because we only copy services so amount may differ than source + print '' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . ''; + print '' . $langs->trans('TotalVAT') . '' . price($objectsrc->total_tva) . ""; + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE + { + print '' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($objectsrc->total_localtax1) . ""; + } + + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF + { + print '' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($objectsrc->total_localtax2) . ""; + } + + print '' . $langs->trans('TotalTTC') . '' . price($objectsrc->total_ttc) . ""; + + if (!empty($conf->multicurrency->enabled)) + { + print '' . $langs->trans('MulticurrencyTotalHT') . '' . price($objectsrc->multicurrency_total_ht) . ''; + print '' . $langs->trans('MulticurrencyTotalVAT') . '' . price($objectsrc->multicurrency_total_tva) . ""; + print '' . $langs->trans('MulticurrencyTotalTTC') . '' . price($objectsrc->multicurrency_total_ttc) . ""; + } + */ } print ''; @@ -1029,6 +1064,18 @@ if ($action == 'create') print '
    '; print ''; + + // Show origin lines + if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) { + $title = $langs->trans('Services'); + print load_fiche_titre($title); + + print ''; + + $objectsrc->printOriginLinesList(empty($conf->global->FICHINTER_PRINT_PRODUCTS)?'services':''); // Show only service, except if option FICHINTER_PRINT_PRODUCTS is on + + print '
    '; + } } else { @@ -1604,22 +1651,8 @@ else if ($id > 0 || ! empty($ref)) else print ''; } - // Event agenda - if (! empty($conf->global->FICHINTER_ADDLINK_TO_EVENT)) - { - if (! empty($conf->agenda->enabled) && $object->statut > Fichinter::STATUS_DRAFT) - { - $langs->load("agenda"); - if ($object->statut < Fichinter::STATUS_BILLED) - { - if ($user->rights->agenda->myactions->create) print ''; - else print ''; - } - } - } - // Proposal - if (! empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) + if ($conf->service->enabled && ! empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) { $langs->load("propal"); if ($object->statut < Fichinter::STATUS_BILLED) @@ -1686,8 +1719,8 @@ else if ($id > 0 || ! empty($ref)) $filename=dol_sanitizeFileName($object->ref); $filedir=$conf->ficheinter->dir_output . "/".$filename; $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->ficheinter->creer; - $delallowed=$user->rights->ficheinter->supprimer; + $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); // Show links to link elements diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php index 68096eea8e9..25cf644db0f 100644 --- a/htdocs/fichinter/class/fichinter.class.php +++ b/htdocs/fichinter/class/fichinter.class.php @@ -671,7 +671,6 @@ class Fichinter extends CommonObject if (! empty($this->ref)) $label .= '
    ' . $langs->trans('Ref') . ': '.$this->ref; - $picto='intervention'; $url = DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id; if ($option !== 'nolink') @@ -698,9 +697,11 @@ class Fichinter extends CommonObject $linkstart.=$linkclose.'>'; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$linkstart.$this->ref.$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; } diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index d806923a241..3b4aca20951 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -119,7 +119,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -633,7 +633,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->ficheinter->lire; - $delallowed=$user->rights->ficheinter->supprimer; + $delallowed=$user->rights->ficheinter->creer; print $formfile->showdocuments('massfilesarea_interventions','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 02e0749d8c5..08a57fae706 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -393,7 +393,7 @@ if ($object->id > 0) print ''; print ''; print ''; $return = array(); diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php index 92792428a38..1d7efb236a2 100644 --- a/htdocs/fourn/class/api_supplier_invoices.class.php +++ b/htdocs/fourn/class/api_supplier_invoices.class.php @@ -76,6 +76,7 @@ class SupplierInvoices extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + $this->invoice->fetchObjectLinked(); return $this->_cleanObjectDatas($this->invoice); } @@ -95,7 +96,7 @@ class SupplierInvoices extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -336,6 +337,10 @@ class SupplierInvoices extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->rowid); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/fourn/class/api_supplier_orders.class.php b/htdocs/fourn/class/api_supplier_orders.class.php index 2695727c3ee..22cd4eb191c 100644 --- a/htdocs/fourn/class/api_supplier_orders.class.php +++ b/htdocs/fourn/class/api_supplier_orders.class.php @@ -76,6 +76,7 @@ class SupplierOrders extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + $this->order->fetchObjectLinked(); return $this->_cleanObjectDatas($this->order); } @@ -95,7 +96,7 @@ class SupplierOrders extends DolibarrApi * * @throws RestException */ - function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids='', $status='', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -340,6 +341,10 @@ class SupplierOrders extends DolibarrApi $object = parent::_cleanObjectDatas($object); unset($object->rowid); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); return $object; } diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 0b8d45b18ad..e3e29e83335 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -43,7 +43,7 @@ class CommandeFournisseur extends CommonOrder public $table_element='commande_fournisseur'; public $table_element_line = 'commande_fournisseurdet'; public $fk_element = 'fk_commande'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='order'; /** @@ -1235,23 +1235,44 @@ class CommandeFournisseur extends CommonOrder { // Add link with price request and supplier order if ($this->id) - { - $this->ref="(PROV".$this->id.")"; + { + $this->ref="(PROV".$this->id.")"; - // Add object linked - if (is_array($this->linked_objects) && ! empty($this->linked_objects)) - { - foreach($this->linked_objects as $origin => $origin_id) - { - $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) - { - dol_print_error($this->db); - $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 + } + + // 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++; + } + } + } + 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) { @@ -1446,10 +1467,10 @@ class CommandeFournisseur extends CommonOrder // We use 'none' instead of $fourn_ref, because fourn_ref may not exists anymore. So we will take the first supplier price ok. // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price. - $result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', $this->fk_soc); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$fourn_ref/$this->fk_soc + $result=$prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', ($this->fk_soc?$this->fk_soc:$this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$fourn_ref/$this->fk_soc if ($result > 0) { - $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice + $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it if ($remise_percent == 0 && $prod->remise_percent !=0) diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index e813268b8b2..afaa2e6a60f 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -44,7 +44,7 @@ class FactureFournisseur extends CommonInvoice public $table_element='facture_fourn'; public $table_element_line='facture_fourn_det'; public $fk_element='fk_facture_fourn'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='bill'; /** @@ -306,7 +306,42 @@ class FactureFournisseur extends CommonInvoice $resql=$this->db->query($sql); if (! $resql) $error++; - // Add object linked + 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++; + } + } + } + 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++; + } + } + } + } + + // Add linked object (deprecated, use ->linkedObjectsIds instead) if (! $error && $this->id && ! empty($this->origin) && ! empty($this->origin_id)) { $ret = $this->add_object_linked(); @@ -1276,8 +1311,9 @@ class FactureFournisseur extends CommonInvoice if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); - // We increase stock for product - $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref)); + $mouvP->origin = &$this; + // We increase stock for product + $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); } } } @@ -1461,6 +1497,7 @@ class FactureFournisseur extends CommonInvoice else { $this->error=$this->line->error; + $this->errors=$this->line->errors; $this->db->rollback(); return -2; } @@ -1472,7 +1509,7 @@ class FactureFournisseur extends CommonInvoice * @param int $id Id of line invoice * @param string $desc Description of line * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) - * @param double $vatrate VAT Rate + * @param double $vatrate VAT Rate (Can be '8.5', '8.5 (ABC)') * @param double $txlocaltax1 LocalTax1 Rate * @param double $txlocaltax2 LocalTax2 Rate * @param double $qty Quantity diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 23726ad15e6..6b4f1417100 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -45,8 +45,8 @@ if (! empty($conf->supplier_proposal->enabled)) if (!empty($conf->produit->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; if (!empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP @@ -95,8 +95,8 @@ $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Load object if ($id > 0 || ! empty($ref)) { - $ret = $object->fetch($id, $ref); - if ($ret < 0) dol_print_error($db,$object->error); + $ret = $object->fetch($id, $ref); + if ($ret < 0) dol_print_error($db,$object->error); $ret = $object->fetch_thirdparty(); if ($ret < 0) dol_print_error($db,$object->error); } @@ -143,7 +143,7 @@ if (empty($reshook)) if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) { - $result=$object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); + $result=$object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -157,14 +157,14 @@ if (empty($reshook)) // payment conditions if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer) { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } // payment mode if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) { - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -181,7 +181,7 @@ if (empty($reshook)) // bank account if ($action == 'setbankaccount' && $user->rights->fournisseur->commande->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } @@ -195,72 +195,72 @@ if (empty($reshook)) // Set project if ($action == 'classin' && $user->rights->fournisseur->commande->creer) { - $result=$object->setProject($projectid); + $result=$object->setProject($projectid); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } if ($action == 'setremisepercent' && $user->rights->fournisseur->commande->creer) { - $result = $object->set_remise($user, $_POST['remise_percent']); + $result = $object->set_remise($user, $_POST['remise_percent']); if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } if ($action == 'reopen') // no test on permission here, permission to use will depends on status { - if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) - { - if ($object->statut == 1) $newstatus=0; // Validated->Draft - else if ($object->statut == 2) $newstatus=0; // Approved->Draft - else if ($object->statut == 3) $newstatus=2; // Ordered->Approved - else if ($object->statut == 4) $newstatus=3; - else if ($object->statut == 5) - { - //$newstatus=2; // Ordered - // TODO Can we set it to submited ? - //$newstatus=3; // Submited - // TODO If there is at least one reception, we can set to Received->Received partially - $newstatus=4; // Received partially + if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) + { + if ($object->statut == 1) $newstatus=0; // Validated->Draft + else if ($object->statut == 2) $newstatus=0; // Approved->Draft + else if ($object->statut == 3) $newstatus=2; // Ordered->Approved + else if ($object->statut == 4) $newstatus=3; + else if ($object->statut == 5) + { + //$newstatus=2; // Ordered + // TODO Can we set it to submited ? + //$newstatus=3; // Submited + // TODO If there is at least one reception, we can set to Received->Received partially + $newstatus=4; // Received partially - } - else if ($object->statut == 6) $newstatus=2; // Canceled->Approved - else if ($object->statut == 7) $newstatus=3; // Canceled->Process running - else if ($object->statut == 9) $newstatus=1; // Refused->Validated - else $newstatus = 2; + } + else if ($object->statut == 6) $newstatus=2; // Canceled->Approved + else if ($object->statut == 7) $newstatus=3; // Canceled->Process running + else if ($object->statut == 9) $newstatus=1; // Refused->Validated + else $newstatus = 2; - //print "old status = ".$object->statut.' new status = '.$newstatus; - $db->begin(); + //print "old status = ".$object->statut.' new status = '.$newstatus; + $db->begin(); - $result = $object->setStatus($user, $newstatus); - if ($result > 0) - { - // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet. - $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; - $sql.= ' SET billed = 0'; - $sql.= ' WHERE rowid = '.$object->id; + $result = $object->setStatus($user, $newstatus); + if ($result > 0) + { + // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet. + $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; + $sql.= ' SET billed = 0'; + $sql.= ' WHERE rowid = '.$object->id; - $resql=$db->query($sql); + $resql=$db->query($sql); - if ($newstatus == 0) - { - $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; - $sql.= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null'; - $sql.= ' WHERE rowid = '.$object->id; + if ($newstatus == 0) + { + $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; + $sql.= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null'; + $sql.= ' WHERE rowid = '.$object->id; - $resql=$db->query($sql); - } + $resql=$db->query($sql); + } - $db->commit(); + $db->commit(); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } - else + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else { $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } - } + setEventMessages($object->error, $object->errors, 'errors'); + } + } } /* @@ -277,10 +277,10 @@ if (empty($reshook)) // Add a product line if ($action == 'addline' && $user->rights->fournisseur->commande->creer) { - $db->begin(); + $db->begin(); - $langs->load('errors'); - $error = 0; + $langs->load('errors'); + $error = 0; // Set if we used free entry or predefined product $predef=''; @@ -305,43 +305,43 @@ if (empty($reshook)) $remise_percent=GETPOST('remise_percent'.$predef); $price_ht_devise = GETPOST('multicurrency_price_ht'); - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } - if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0) - { - setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise === '') // Unit price can be 0 but not '' - { - setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && ! GETPOST('dp_desc')) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); - $error++; - } - if (! GETPOST('qty')) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error++; - } + if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0) + { + setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise === '') // Unit price can be 0 but not '' + { + setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && ! GETPOST('dp_desc')) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); + $error++; + } + if (! GETPOST('qty')) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error++; + } if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') { if ($combinations = GETPOST('combinations', 'array')) { @@ -358,14 +358,14 @@ if (empty($reshook)) } // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $txtva par celui du produit - if (($prod_entry_mode != 'free') && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { - $productsupplier = new ProductFournisseur($db); + // Ecrase $desc par celui du produit + // Ecrase $txtva par celui du produit + if (($prod_entry_mode != 'free') && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' + { + $productsupplier = new ProductFournisseur($db); - if (empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED)) // TODO this test seems useless - { + if (empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED)) // TODO this test seems useless + { $idprod=0; if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) } @@ -377,67 +377,67 @@ if (empty($reshook)) // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price $productsupplier->get_buyprice(0, -1, $idprod, 'none'); // We force qty to -1 to be sure to find if a supplier price exist } - elseif (GETPOST('idprodfournprice') > 0) - { - $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. - //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist - $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); - $res=$productsupplier->fetch($idprod); - } + elseif (GETPOST('idprodfournprice') > 0) + { + $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. + //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist + $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); + $res=$productsupplier->fetch($idprod); + } - if ($idprod > 0) - { - $label = $productsupplier->label; + if ($idprod > 0) + { + $label = $productsupplier->label; - $desc = $productsupplier->description; - if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); + $desc = $productsupplier->description; + if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); - $type = $productsupplier->type; + $type = $productsupplier->type; - $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); - $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); + $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); + $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice')); if (empty($tva_tx)) $tva_npr=0; - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - $result=$object->addline( - $desc, - $productsupplier->fourn_pu, - $qty, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $idprod, - $productsupplier->product_fourn_price_id, - $productsupplier->fourn_ref, - $remise_percent, - 'HT', - $pu_ttc, - $type, - $tva_npr, - '', - $date_start, - $date_end, - $array_options, - $productsupplier->fk_unit - ); - } - if ($idprod == -99 || $idprod == 0) - { - // Product not selected - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors'); - } - if ($idprod == -1) - { - // Quantity too low - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); - } - } - else if (empty($error)) + $result=$object->addline( + $desc, + $productsupplier->fourn_pu, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $idprod, + $productsupplier->product_fourn_price_id, + $productsupplier->fourn_ref, + $remise_percent, + 'HT', + $pu_ttc, + $type, + $tva_npr, + '', + $date_start, + $date_end, + $array_options, + $productsupplier->fk_unit + ); + } + if ($idprod == -99 || $idprod == 0) + { + // Product not selected + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors'); + } + if ($idprod == -1) + { + // Quantity too low + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); + } + } + else if (empty($error)) { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); @@ -449,208 +449,37 @@ if (empty($reshook)) $fk_unit= GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + $tva_tx = price2num($tva_tx); // When vat is text input field - // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + // Local Taxes + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - if (GETPOST('price_ht')!=='') - { - $price_base_type = 'HT'; - $ht = price2num(GETPOST('price_ht')); - $ttc = 0; - } - else - { - $ttc = price2num(GETPOST('price_ttc')); - $ht = $ttc / (1 + ($tva_tx / 100)); - $price_base_type = 'HT'; - } + if (GETPOST('price_ht')!=='') + { + $price_base_type = 'HT'; + $ht = price2num(GETPOST('price_ht')); + $ttc = 0; + } + else + { + $ttc = price2num(GETPOST('price_ttc')); + $ht = $ttc / (1 + ($tva_tx / 100)); + $price_base_type = 'HT'; + } $pu_ht_devise = price2num($price_ht_devise, 'MU'); $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type,'','', $date_start, $date_end, $array_options, $fk_unit, $pu_ht_devise); } - //print "xx".$tva_tx; exit; - if (! $error && $result > 0) - { - $db->commit(); - - $ret=$object->fetch($object->id); // Reload to get new records - - // 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->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - - unset($_POST ['prod_entry_mode']); - - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['pu']); - unset($_POST['price_ht']); - unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['label']); - unset($localtax1_tx); - unset($localtax2_tx); - unset($_POST['np_marginRate']); - unset($_POST['np_markRate']); - unset($_POST['dp_desc']); - unset($_POST['idprodfournprice']); - - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else + //print "xx".$tva_tx; exit; + if (! $error && $result > 0) { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } + $db->commit(); - $action = ''; - } + $ret=$object->fetch($object->id); // Reload to get new records - /* - * Updating a line in the order - */ - if ($action == 'updateline' && $user->rights->fournisseur->commande->creer && ! GETPOST('cancel','alpha')) - { - $vat_rate=(GETPOST('tva_tx')?GETPOST('tva_tx'):0); - - if ($lineid) - { - $line = new CommandeFournisseurLigne($db); - $res = $line->fetch($lineid); - if (!$res) dol_print_error($db); - } - - $productsupplier = new ProductFournisseur($db); - if ($productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid','int')) < 0 ) - { - setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); - } - - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) - $info_bits |= 0x01; - - // Define vat_rate - $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty); - $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); - - if (GETPOST('price_ht') != '') - { - $price_base_type = 'HT'; - $ht = price2num(GETPOST('price_ht')); - } - else - { - $vatratecleaned = $vat_rate; - if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)" - { - $vatratecleaned = trim($reg[1]); - $vatratecode = $reg[2]; - } - - $ttc = price2num(GETPOST('price_ttc')); - $ht = $ttc / (1 + ($vatratecleaned / 100)); - $price_base_type = 'HT'; - } - - $pu_ht_devise = GETPOST('multicurrency_subprice'); - - // Extrafields Lines - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); - // Unset extrafield POST Data - if (is_array($extralabelsline)) { - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } - } - - $result = $object->updateline( - $lineid, - $_POST['product_desc'], - $ht, - $_POST['qty'], - $_POST['remise_percent'], - $vat_rate, - $localtax1_rate, - $localtax2_rate, - $price_base_type, - 0, - isset($_POST["type"])?$_POST["type"]:$line->product_type, - false, - $date_start, - $date_end, - $array_options, - $_POST['units'], - $pu_ht_devise - ); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['idprodfournprice']); - unset($_POST['remmise_percent']); - unset($_POST['dp_desc']); - unset($_POST['np_desc']); - unset($_POST['pu']); - unset($_POST['tva_tx']); - unset($_POST['date_start']); - unset($_POST['date_end']); - unset($_POST['units']); - unset($localtax1_tx); - unset($localtax2_tx); - - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - - if ($result >= 0) - { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { @@ -668,12 +497,183 @@ if (empty($reshook)) $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) dol_print_error($db,$result); } - } - else - { + + unset($_POST ['prod_entry_mode']); + + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['pu']); + unset($_POST['price_ht']); + unset($_POST['multicurrency_price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['label']); + unset($localtax1_tx); + unset($localtax2_tx); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprodfournprice']); + + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else + { + $db->rollback(); + setEventMessages($object->error, $object->errors, 'errors'); + } + + $action = ''; + } + + /* + * Updating a line in the order + */ + if ($action == 'updateline' && $user->rights->fournisseur->commande->creer && ! GETPOST('cancel','alpha')) + { + $vat_rate=(GETPOST('tva_tx')?GETPOST('tva_tx'):0); + + if ($lineid) + { + $line = new CommandeFournisseurLigne($db); + $res = $line->fetch($lineid); + if (!$res) dol_print_error($db); + } + + $productsupplier = new ProductFournisseur($db); + if ($productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid','int')) < 0 ) + { + setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); + } + + $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) + $info_bits |= 0x01; + + // Define vat_rate + $vat_rate = str_replace('*', '', $vat_rate); + $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty); + $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); + + if (GETPOST('price_ht') != '') + { + $price_base_type = 'HT'; + $ht = price2num(GETPOST('price_ht')); + } + else + { + $vatratecleaned = $vat_rate; + if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)" + { + $vatratecleaned = trim($reg[1]); + $vatratecode = $reg[2]; + } + + $ttc = price2num(GETPOST('price_ttc')); + $ht = $ttc / (1 + ($vatratecleaned / 100)); + $price_base_type = 'HT'; + } + + $pu_ht_devise = GETPOST('multicurrency_subprice'); + + // Extrafields Lines + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // Unset extrafield POST Data + if (is_array($extralabelsline)) { + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } + + $result = $object->updateline( + $lineid, + $_POST['product_desc'], + $ht, + $_POST['qty'], + $_POST['remise_percent'], + $vat_rate, + $localtax1_rate, + $localtax2_rate, + $price_base_type, + 0, + isset($_POST["type"])?$_POST["type"]:$line->product_type, + false, + $date_start, + $date_end, + $array_options, + $_POST['units'], + $pu_ht_devise + ); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['idprodfournprice']); + unset($_POST['remmise_percent']); + unset($_POST['dp_desc']); + unset($_POST['np_desc']); + unset($_POST['pu']); + unset($_POST['tva_tx']); + unset($_POST['date_start']); + unset($_POST['date_end']); + unset($_POST['units']); + unset($localtax1_tx); + unset($localtax2_tx); + + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + + 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->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + } + else + { dol_print_error($db,$object->error); exit; - } + } } @@ -712,49 +712,49 @@ if (empty($reshook)) // Validate if ($action == 'confirm_valid' && $confirm == 'yes' && - ((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))) + ((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))) ) { - $object->date_commande=dol_now(); - $result = $object->valid($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 - - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - } - else + $object->date_commande=dol_now(); + $result = $object->valid($user); + if ($result >= 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + // 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 we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step - if (empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) - { - $action='confirm_approve'; // can make standard or first level approval also if permission is set - } + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + + // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step + if (empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) + { + $action='confirm_approve'; // can make standard or first level approval also if permission is set + } } if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) { - $idwarehouse=GETPOST('idwarehouse', 'int'); + $idwarehouse=GETPOST('idwarehouse', 'int'); - $qualified_for_stock_change=0; + $qualified_for_stock_change=0; if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change=$object->hasProductsOrServices(2); @@ -764,95 +764,95 @@ if (empty($reshook)) $qualified_for_stock_change=$object->hasProductsOrServices(1); } - // Check parameters - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER - { - if (! $idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; - } - } - - if (! $error) - { - $result = $object->approve($user, $idwarehouse, ($action=='confirm_approve2'?1:0)); - if ($result > 0) - { - 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); - } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER + { + if (! $idwarehouse || $idwarehouse == -1) { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $error++; + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action=''; + } + } + + if (! $error) + { + $result = $object->approve($user, $idwarehouse, ($action=='confirm_approve2'?1:0)); + if ($result > 0) + { + 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); + } + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } if ($action == 'confirm_refuse' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver) { - $result = $object->refuse($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->refuse($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) { - $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']); - if ($result > 0) - { - 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); - } - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - $action = ''; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']); + if ($result > 0) + { + 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); + } + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + $action = ''; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->commande->supprimer) { - $result=$object->delete($user); - if ($result > 0) - { - header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php'); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result=$object->delete($user); + if ($result > 0) + { + header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php'); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Action clone object @@ -874,7 +874,7 @@ if (empty($reshook)) } else { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $action=''; } } @@ -884,44 +884,44 @@ if (empty($reshook)) // Set status of reception (complete, partial, ...) if ($action == 'livraison' && $user->rights->fournisseur->commande->receptionner) { - if (GETPOST("type") != '') - { - $date_liv = dol_mktime(GETPOST('rehour'),GETPOST('remin'),GETPOST('resec'),GETPOST("remonth"),GETPOST("reday"),GETPOST("reyear")); + if (GETPOST("type") != '') + { + $date_liv = dol_mktime(GETPOST('rehour'),GETPOST('remin'),GETPOST('resec'),GETPOST("remonth"),GETPOST("reday"),GETPOST("reyear")); - $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($result > 0) - { - $langs->load("deliveries"); - setEventMessages($langs->trans("DeliveryStateSaved"), null); - $action = ''; - } - else if($result == -3) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - else - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors'); - } + $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can' + if ($result > 0) + { + $langs->load("deliveries"); + setEventMessages($langs->trans("DeliveryStateSaved"), null); + $action = ''; + } + else if($result == -3) + { + setEventMessages($object->error, $object->errors, 'errors'); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + else + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors'); + } } if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander) { - $result = $object->cancel($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->cancel($user); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Actions when printing a doc from card @@ -983,25 +983,25 @@ if (empty($reshook)) { $error=0; - if ($socid <1) - { - setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), null, 'errors'); - $action='create'; - $error++; - } + if ($socid <1) + { + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), null, 'errors'); + $action='create'; + $error++; + } - if (! $error) - { - $db->begin(); + if (! $error) + { + $db->begin(); - // Creation commande - $object->ref_supplier = GETPOST('refsupplier'); - $object->socid = $socid; + // Creation commande + $object->ref_supplier = GETPOST('refsupplier'); + $object->socid = $socid; $object->cond_reglement_id = GETPOST('cond_reglement_id'); - $object->mode_reglement_id = GETPOST('mode_reglement_id'); - $object->fk_account = GETPOST('fk_account', 'int'); - $object->note_private = GETPOST('note_private','none'); - $object->note_public = GETPOST('note_public','none'); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); + $object->note_private = GETPOST('note_private','none'); + $object->note_public = GETPOST('note_public','none'); $object->date_livraison = $datelivraison; $object->fk_incoterms = GETPOST('incoterm_id', 'int'); $object->location_incoterms = GETPOST('location_incoterms', 'alpha'); @@ -1010,23 +1010,23 @@ if (empty($reshook)) $object->fk_project = GETPOST('projectid'); // Fill array 'array_options' with data from add form - if (! $error) - { + if (! $error) + { $ret = $extrafields->setOptionalsFromPost($extralabels,$object); if ($ret < 0) $error++; - } + } - if (! $error) - { - // If creation from another object of another module (Example: origin=propal, originid=1) + if (! $error) + { + // If creation from another object of another module (Example: origin=propal, originid=1) if (! empty($origin) && ! empty($originid)) { if ($origin == 'order' || $origin == 'commande') { - $element = $subelement = 'commande'; - } - else - { + $element = $subelement = 'commande'; + } + else + { $element = 'supplier_proposal'; $subelement = 'supplier_proposal'; } @@ -1085,7 +1085,7 @@ if (empty($reshook)) // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if - // trigger used + // trigger used { $lines[$i]->fetch_optionals($lines[$i]->rowid); $array_option = $lines[$i]->array_options; @@ -1094,14 +1094,14 @@ if (empty($reshook)) $result = $productsupplier->find_min_price_product_fournisseur($lines[$i]->fk_product, $lines[$i]->qty, $srcobject->socid); if ($result>=0) { - $tva_tx = $lines[$i]->tva_tx; + $tva_tx = $lines[$i]->tva_tx; - if ($origin=="commande") - { - $soc=new societe($db); - $soc->fetch($socid); - $tva_tx=get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $productsupplier->product_fourn_price_id); - } + if ($origin=="commande") + { + $soc=new societe($db); + $soc->fetch($socid); + $tva_tx=get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $productsupplier->product_fourn_price_id); + } $result = $object->addline( $desc, @@ -1150,132 +1150,132 @@ if (empty($reshook)) if ($reshook < 0) $error ++; } else { - setEventMessages($srcobject->error, $srcobject->errors, 'errors'); + setEventMessages($srcobject->error, $srcobject->errors, 'errors'); $error ++; } } else { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $error ++; } } else { - $id = $object->create($user); - if ($id < 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } + $id = $object->create($user); + if ($id < 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } } - } + } - if ($error) - { - $langs->load("errors"); - $db->rollback(); - $action='create'; - $_GET['socid']=$_POST['socid']; - } - else + if ($error) { - $db->commit(); - header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); - exit; - } - } + $langs->load("errors"); + $db->rollback(); + $action='create'; + $_GET['socid']=$_POST['socid']; + } + else + { + $db->commit(); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + exit; + } + } } if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && ! GETPOST('cancel','alpha')) { - $ws_url = $object->thirdparty->webservices_url; - $ws_key = $object->thirdparty->webservices_key; - $ws_user = GETPOST('ws_user','alpha'); - $ws_password = GETPOST('ws_password','alpha'); - $ws_entity = GETPOST('ws_entity','int'); - $ws_thirdparty = GETPOST('ws_thirdparty','int'); + $ws_url = $object->thirdparty->webservices_url; + $ws_key = $object->thirdparty->webservices_key; + $ws_user = GETPOST('ws_user','alpha'); + $ws_password = GETPOST('ws_password','alpha'); + $ws_entity = GETPOST('ws_entity','int'); + $ws_thirdparty = GETPOST('ws_thirdparty','int'); - // NS and Authentication parameters - $ws_ns='http://www.dolibarr.org/ns/'; - $ws_authentication=array( - 'dolibarrkey'=>$ws_key, - 'sourceapplication'=>'DolibarrWebServiceClient', - 'login'=>$ws_user, - 'password'=>$ws_password, - 'entity'=>$ws_entity - ); + // NS and Authentication parameters + $ws_ns='http://www.dolibarr.org/ns/'; + $ws_authentication=array( + 'dolibarrkey'=>$ws_key, + 'sourceapplication'=>'DolibarrWebServiceClient', + 'login'=>$ws_user, + 'password'=>$ws_password, + 'entity'=>$ws_entity + ); - //Is sync supplier web services module activated? and everything filled? - if (empty($conf->syncsupplierwebservices->enabled)) { - setEventMessages($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name")), null, 'mesgs'); - } else if (empty($ws_url) || empty($ws_key)) { - setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors'); - } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) { - setEventMessages($langs->trans("ErrorFieldsRequired"),null, 'errors'); - } - else - { - //Create SOAP client and connect it to order - $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); - $soapclient_order->soap_defencoding='UTF-8'; - $soapclient_order->decodeUTF8(false); + //Is sync supplier web services module activated? and everything filled? + if (empty($conf->syncsupplierwebservices->enabled)) { + setEventMessages($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name")), null, 'mesgs'); + } else if (empty($ws_url) || empty($ws_key)) { + setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors'); + } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) { + setEventMessages($langs->trans("ErrorFieldsRequired"),null, 'errors'); + } + else + { + //Create SOAP client and connect it to order + $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); + $soapclient_order->soap_defencoding='UTF-8'; + $soapclient_order->decodeUTF8(false); - //Create SOAP client and connect it to product/service - $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); - $soapclient_product->soap_defencoding='UTF-8'; - $soapclient_product->decodeUTF8(false); + //Create SOAP client and connect it to product/service + $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); + $soapclient_product->soap_defencoding='UTF-8'; + $soapclient_product->decodeUTF8(false); - //Prepare the order lines from order - $order_lines = array(); - foreach ($object->lines as $line) - { - $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); - $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); + //Prepare the order lines from order + $order_lines = array(); + foreach ($object->lines as $line) + { + $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); + $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); - if ($result_product["result"]["result_code"] == "OK") - { - $order_lines[] = array( - 'desc' => $line->product_desc, - 'type' => $line->product_type, - 'product_id' => $result_product["product"]["id"], - 'vat_rate' => $line->tva_tx, - 'qty' => $line->qty, - 'price' => $line->price, - 'unitprice' => $line->subprice, - 'total_net' => $line->total_ht, - 'total_vat' => $line->total_tva, - 'total' => $line->total_ttc, - 'date_start' => $line->date_start, - 'date_end' => $line->date_end, - ); - } - } + if ($result_product["result"]["result_code"] == "OK") + { + $order_lines[] = array( + 'desc' => $line->product_desc, + 'type' => $line->product_type, + 'product_id' => $result_product["product"]["id"], + 'vat_rate' => $line->tva_tx, + 'qty' => $line->qty, + 'price' => $line->price, + 'unitprice' => $line->subprice, + 'total_net' => $line->total_ht, + 'total_vat' => $line->total_tva, + 'total' => $line->total_ttc, + 'date_start' => $line->date_start, + 'date_end' => $line->date_end, + ); + } + } - //Prepare the order header - $order = array( - 'thirdparty_id' => $ws_thirdparty, - 'date' => dol_print_date(dol_now(),'dayrfc'), - 'total_net' => $object->total_ht, - 'total_var' => $object->total_tva, - 'total' => $object->total_ttc, - 'lines' => $order_lines - ); + //Prepare the order header + $order = array( + 'thirdparty_id' => $ws_thirdparty, + 'date' => dol_print_date(dol_now(),'dayrfc'), + 'total_net' => $object->total_ht, + 'total_var' => $object->total_tva, + 'total' => $object->total_ttc, + 'lines' => $order_lines + ); - $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); - $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); + $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); + $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); - if (empty($result_order["result"]["result_code"])) //No result, check error str - { - setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); - } - else if ($result_order["result"]["result_code"] != "OK") //Something went wrong - { - setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors'); - } - else - { - setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs'); - } - } + if (empty($result_order["result"]["result_code"])) //No result, check error str + { + setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); + } + else if ($result_order["result"]["result_code"] != "OK") //Something went wrong + { + setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors'); + } + else + { + setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs'); + } + } } if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer) @@ -1344,11 +1344,6 @@ if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $help_url='EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('',$langs->trans("Order"),$help_url); -/* *************************************************************************** */ -/* */ -/* Mode vue et edition */ -/* */ -/* *************************************************************************** */ $now=dol_now(); if ($action=='create') @@ -1395,9 +1390,9 @@ if ($action=='create') $soc = $objectsrc->client; $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); - $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); + $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1461,10 +1456,10 @@ if ($action=='create') else { print $form->select_company((empty($socid)?'':$socid), 'socid', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); - // reload page to retrieve customer informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { - print ''; - } - print ' '.$langs->trans("AddThirdParty").''; + } + print ' '.$langs->trans("AddThirdParty").''; } print ''; @@ -1504,14 +1499,14 @@ if ($action=='create') $form->select_date($datelivraison?$datelivraison:-1,'liv_',$usehourmin,$usehourmin,'',"set"); print ''; - // Bank Account - if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) - { - $langs->load("bank"); - print ''; - } + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) + { + $langs->load("bank"); + print ''; + } // Project if (! empty($conf->projet->enabled)) @@ -1524,13 +1519,13 @@ if ($action=='create') print ''; } - // Incoterms + // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; print ''; - print ''; } @@ -1539,8 +1534,8 @@ if ($action=='create') { print ''; print ''; - print ''; } @@ -1595,19 +1590,19 @@ if ($action=='create') } // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; if (empty($reshook) && ! empty($extrafields->attribute_label)) - { + { print $object->showOptionals($extrafields,'edit'); - } + } // Bouton "Create Draft" - print "
    '.$langs->trans("ProductsAndServices").''; - print ''.$langs->trans("AllProductServicePrices").' '.$object->nbOfProductRefs().''; + print ''.$langs->trans("AllProductReferencesOfSupplier").' '.$object->nbOfProductRefs().''; print '
    ' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print '
    ' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
    '; - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:'')); + print ''; + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:'')); print '
    '.fieldLabel('Currency','multicurrency_code').''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print '
    \n"; + print "\n"; - dol_fiche_end(); + dol_fiche_end(); print '
    '; print ''; @@ -1634,9 +1629,9 @@ elseif (! empty($object->id)) { $result = $object->fetch($id, $ref); - $societe = new Fournisseur($db); - $result=$societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + $societe = new Fournisseur($db); + $result=$societe->fetch($object->socid); + if ($result < 0) dol_print_error($db); $author = new User($db); $author->fetch($object->user_author_id); @@ -1679,7 +1674,7 @@ elseif (! empty($object->id)) // We check if number is temporary number if (preg_match('/^[\(]?PROV/i',$object->ref) || empty($object->ref)) // empty should not happened, but when it occurs, the test save life { - $newref = $object->getNextNumRef($object->thirdparty); + $newref = $object->getNextNumRef($object->thirdparty); } else $newref = $object->ref; @@ -1706,15 +1701,15 @@ elseif (! empty($object->id)) // Confirm approval if ($action == 'approve' || $action == 'approve2') { - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } $formquestion=array(); if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) @@ -1794,34 +1789,34 @@ elseif (! empty($object->id)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
    '.$langs->trans('Project') . ' '; - if ($user->rights->fournisseur->commande->creer) - { - 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.='
    '; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
    '; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (! empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref.=''; - $morehtmlref.=$proj->ref; - $morehtmlref.=''; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->fournisseur->commande->creer) + { + 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.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } $morehtmlref.='
    '; @@ -1941,24 +1936,24 @@ elseif (! empty($object->id)) print ''; } - // Bank Account + // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) { - print ''; - print ''; - print '
    '; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->fournisseur->commande->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ''; - print ''; + print ''; + print ''; + print '
    '; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->fournisseur->commande->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ''; + print ''; } // Delivery date planed @@ -1986,7 +1981,7 @@ elseif (! empty($object->id)) if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin='dayhour'; print $object->date_livraison ? dol_print_date($object->date_livraison, $usehourmin) : ' '; if ($object->hasDelay() && ! empty($object->date_livraison)) { - print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); + print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); } } print ''; @@ -2001,14 +1996,14 @@ elseif (! empty($object->id)) if (!empty($conf->incoterm->enabled)) { print ''; - print '
    '; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->fournisseur->commande->creer) print ''.img_edit().''; - else print ' '; - print '
    '; - print ''; - print ''; + print '
    '; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->fournisseur->commande->creer) print ''.img_edit().''; + else print ' '; + print '
    '; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2017,7 +2012,7 @@ elseif (! empty($object->id)) { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } // Other attributes @@ -2034,20 +2029,20 @@ elseif (! empty($object->id)) if (!empty($conf->multicurrency->enabled)) { - // Multicurrency Amount HT - print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; - print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount HT + print '' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . ''; + print '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount VAT - print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; - print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount VAT + print '' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . ''; + print '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; - // Multicurrency Amount TTC - print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; - print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; - print ''; + // Multicurrency Amount TTC + print '' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . ''; + print '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . ''; + print ''; } // Total @@ -2111,7 +2106,7 @@ elseif (! empty($object->id)) //$result = $object->getLinesArray(); - print '
    + print ' @@ -2123,7 +2118,7 @@ elseif (! empty($object->id)) include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print ''; // Add free products/services form @@ -2153,7 +2148,7 @@ elseif (! empty($object->id)) } } print '
    '; - print '
    '; + print '
    '; print '
    '; dol_fiche_end(); @@ -2175,8 +2170,8 @@ elseif (! empty($object->id)) // Validate if ($object->statut == 0 && $num > 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))) + 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))) { $tmpbuttonlabel=$langs->trans('Validate'); if ($user->rights->fournisseur->commande->approuver && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) $tmpbuttonlabel = $langs->trans("ValidateAndApprove"); @@ -2269,24 +2264,24 @@ elseif (! empty($object->id)) // Reopen if (in_array($object->statut, array(2))) { - $buttonshown=0; - if (! $buttonshown && $user->rights->fournisseur->commande->approuver) - { - if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) - || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) - { - print ''.$langs->trans("Disapprove").''; - $buttonshown++; - } - } - if (! $buttonshown && $user->rights->fournisseur->commande->approve2 && ! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) - { - if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) - || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) - { - print ''.$langs->trans("Disapprove").''; - } - } + $buttonshown=0; + if (! $buttonshown && $user->rights->fournisseur->commande->approuver) + { + if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) + || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) + { + print ''.$langs->trans("Disapprove").''; + $buttonshown++; + } + } + if (! $buttonshown && $user->rights->fournisseur->commande->approve2 && ! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) + { + if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) + || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) + { + print ''.$langs->trans("Disapprove").''; + } + } } if (in_array($object->statut, array(3, 4, 5, 6, 7, 9))) { @@ -2310,14 +2305,14 @@ elseif (! empty($object->id)) if ($object->statut == 2) { - if ($user->rights->fournisseur->commande->commander) - { - print ''; - } - else - { - print ''; - } + if ($user->rights->fournisseur->commande->commander) + { + print ''; + } + else + { + print ''; + } } // Create bill @@ -2335,17 +2330,17 @@ elseif (! empty($object->id)) // Classify billed manually (need one invoice if module invoice is on, no condition on invoice if not) if ($user->rights->fournisseur->commande->creer && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) // statut 2 means approved { - if (empty($conf->facture->enabled)) - { - print ''.$langs->trans("ClassifyBilled").''; - } - else if (!empty($object->linkedObjectsIds['invoice_supplier'])) - { + if (empty($conf->facture->enabled)) + { + print ''.$langs->trans("ClassifyBilled").''; + } + else if (!empty($object->linkedObjectsIds['invoice_supplier'])) + { if ($user->rights->fournisseur->facture->creer) { - print ''.$langs->trans("ClassifyBilled").''; + print ''.$langs->trans("ClassifyBilled").''; } - } + } } // Create a remote order using WebService only if module is activated @@ -2383,57 +2378,59 @@ elseif (! empty($object->id)) if ($user->rights->fournisseur->commande->commander && $object->statut == 2 && $action == 'makeorder') { - // Set status to ordered (action=commande) - print ''."\n"; - print '
    '; - print ''; - print ''; - print load_fiche_titre($langs->trans("ToOrder"),'',''); - print ''; - //print ''; - print ''; + // Set status to ordered (action=commande) + print ''."\n"; + print ''; - print ''; + print ''; + print ''; + print load_fiche_titre($langs->trans("ToOrder"),'',''); + print '
    '.$langs->trans("ToOrder").'
    '.$langs->trans("OrderDate").''; - $date_com = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - print $form->select_date($date_com,'',1,1,'',"commande",1,1,1); - print '
    '.$langs->trans("OrderMode").''; - $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); - print '
    '; + //print ''; + print ''; - print ''; - print ''; - print '
    '.$langs->trans("ToOrder").'
    '.$langs->trans("OrderDate").''; + $date_com = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + print $form->select_date($date_com,'',1,1,'',"commande",1,1,1); + print '
    '.$langs->trans("Comment").'
    '; - print ''; - print '     '; - print ''; - print '
    '; - print '
    '; - print "
    "; + print ''.$langs->trans("OrderMode").''; + $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); + print ''; + + print ''.$langs->trans("Comment").''; + print ''; + print ''; + print '     '; + print ''; + print ''; + print ''; + + print ''; + print "
    "; } if ($action != 'makeorder') { - print '
    '; + print '
    '; - /* + /* * Documents generes */ - $comfournref = dol_sanitizeFileName($object->ref); - $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf'; - $relativepath = $comfournref.'/'.$comfournref.'.pdf'; - $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->fournisseur->commande->creer; - $delallowed=$user->rights->fournisseur->commande->supprimer; + $comfournref = dol_sanitizeFileName($object->ref); + $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf'; + $relativepath = $comfournref.'/'.$comfournref.'.pdf'; + $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref; + $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed=$user->rights->fournisseur->commande->lire; + $delallowed=$user->rights->fournisseur->commande->creer; - print $formfile->showdocuments('commande_fournisseur',$comfournref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,0,0,'','','',$object->thirdparty->default_lang); - $somethingshown=$formfile->numoffiles; + print $formfile->showdocuments('commande_fournisseur',$comfournref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,0,0,'','','',$object->thirdparty->default_lang); + $somethingshown=$formfile->numoffiles; - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order','order_supplier')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order','order_supplier')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; + print '
    '; if ($user->rights->fournisseur->commande->receptionner && ($object->statut == 3 || $object->statut == 4)) { @@ -2468,10 +2465,10 @@ elseif (! empty($object->id)) print "
    "; } - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object,'order_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions=new FormActions($db); + $somethingshown = $formactions->showactions($object,'order_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); print '
    '; } diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index 3894cf28cc4..5194d6296bb 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -158,7 +158,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -1233,7 +1233,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->fournisseur->commande->lire; - $delallowed=$user->rights->fournisseur->commande->lire; + $delallowed=$user->rights->fournisseur->commande->creer; print $formfile->showdocuments('massfilesarea_supplier_order','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 6241a80aec1..de05d2f1a6e 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -133,9 +133,9 @@ if (empty($reshook)) // Link invoice to order if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) { - $object->fetch($id); - $object->fetch_thirdparty(); - $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); + $object->fetch($id); + $object->fetch_thirdparty(); + $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } // Action clone object @@ -147,95 +147,95 @@ if (empty($reshook)) // } // else // { - $result=$object->createFromClone($id); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF'].'?action=editref_supplier&id='.$result); - exit; - } - else - { - $langs->load("errors"); - setEventMessages($langs->trans($object->error), null, 'errors'); - $action=''; - } + $result=$object->createFromClone($id); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?action=editref_supplier&id='.$result); + exit; + } + else + { + $langs->load("errors"); + setEventMessages($langs->trans($object->error), null, 'errors'); + $action=''; + } // } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) + ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate))) ) { - $idwarehouse=GETPOST('idwarehouse'); + $idwarehouse=GETPOST('idwarehouse'); - $object->fetch($id); - $object->fetch_thirdparty(); + $object->fetch($id); + $object->fetch_thirdparty(); - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } - // Check parameters - if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - if (! $idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action=''; - } - } + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + if (! $idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action=''; + } + } - if (! $error) - { - $result = $object->validate($user,'',$idwarehouse); - if ($result < 0) - { - setEventMessages($object->error,$object->errors,'errors'); - }else{ - // 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) + { + $result = $object->validate($user,'',$idwarehouse); + if ($result < 0) + { + setEventMessages($object->error,$object->errors,'errors'); + }else{ + // 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->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } - } - } + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + } + } } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) { - $object->fetch($id); - $object->fetch_thirdparty(); - $result=$object->delete($user); - if ($result > 0) - { - header('Location: list.php'); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $object->fetch_thirdparty(); + $result=$object->delete($user); + if ($result > 0) + { + header('Location: list.php'); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Remove a product line @@ -273,12 +273,12 @@ if (empty($reshook)) elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $result=$object->set_paid($user); - if ($result<0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->fetch($id); + $result=$object->set_paid($user); + if ($result<0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Set supplier ref @@ -291,34 +291,34 @@ if (empty($reshook)) } else { - // Define output language - $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); - } - 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); - } + // Define output language + $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); + } + 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); + } } } // payments conditions if ($action == 'setconditions' && $user->rights->fournisseur->facture->creer) { - $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); + $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int')); } // payment mode else if ($action == 'setmode' && $user->rights->fournisseur->facture->creer) { - $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); } // Multicurrency Code @@ -333,71 +333,71 @@ if (empty($reshook)) // bank account else if ($action == 'setbankaccount' && $user->rights->fournisseur->facture->creer) { - $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } // Set label elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $object->label=GETPOST('label'); - $result=$object->update($user); - if ($result < 0) dol_print_error($db); + $object->fetch($id); + $object->label=GETPOST('label'); + $result=$object->update($user); + if ($result < 0) dol_print_error($db); } elseif ($action == 'setdatef' && $user->rights->fournisseur->facture->creer) { - $newdate=dol_mktime(0,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']); - if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)?0:$conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) - { - if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); - else setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); - } + $newdate=dol_mktime(0,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']); + if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)?0:$conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) + { + if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); + else setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); + } - $object->fetch($id); + $object->fetch($id); - $object->date=$newdate; - $date_echence_calc=$object->calculate_date_lim_reglement(); - if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) - { - $object->date_echeance = $date_echence_calc; - } - if ($object->date_echeance && $object->date_echeance < $object->date) - { - $object->date_echeance=$object->date; - } + $object->date=$newdate; + $date_echence_calc=$object->calculate_date_lim_reglement(); + if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) + { + $object->date_echeance = $date_echence_calc; + } + if ($object->date_echeance && $object->date_echeance < $object->date) + { + $object->date_echeance=$object->date; + } - $result=$object->update($user); - if ($result < 0) dol_print_error($db,$object->error); + $result=$object->update($user); + if ($result < 0) dol_print_error($db,$object->error); } elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']); - if (! empty($object->date_echeance) && $object->date_echeance < $object->date) - { - $object->date_echeance=$object->date; - setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings'); - } - $result=$object->update($user); - if ($result < 0) dol_print_error($db,$object->error); + $object->fetch($id); + $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']); + if (! empty($object->date_echeance) && $object->date_echeance < $object->date) + { + $object->date_echeance=$object->date; + setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings'); + } + $result=$object->update($user); + if ($result < 0) dol_print_error($db,$object->error); } // Delete payment elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { $object->fetch($id); - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) - { - $paiementfourn = new PaiementFourn($db); - $result=$paiementfourn->fetch(GETPOST('paiement_id')); - if ($result > 0) { - $result=$paiementfourn->delete(); // If fetch ok and found - header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) + { + $paiementfourn = new PaiementFourn($db); + $result=$paiementfourn->fetch(GETPOST('paiement_id')); + if ($result > 0) { + $result=$paiementfourn->delete(); // If fetch ok and found + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); } - if ($result < 0) { - setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors'); - } - } + if ($result < 0) { + setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors'); + } + } } // Create @@ -460,7 +460,7 @@ if (empty($reshook)) $id = $object->createFromCurrent($user); if ($id <= 0) { - $error++; + $error++; setEventMessages($object->error, $object->errors, 'errors'); } } @@ -555,7 +555,7 @@ if (empty($reshook)) // Defined the new fk_parent_line if ($result > 0 && $line->product_type == 9) { - $fk_parent_line = $result; + $fk_parent_line = $result; } } @@ -746,38 +746,6 @@ if (empty($reshook)) { $error++; } - - if (! $error) - { - // If some invoice's lines already known - for ($i = 1 ; $i < 9 ; $i++) - { - $label = $_POST['label'.$i]; - $amountht = price2num($_POST['amount'.$i]); - $amountttc = price2num($_POST['amountttc'.$i]); - $tauxtva = price2num($_POST['tauxtva'.$i]); - $qty = $_POST['qty'.$i]; - $fk_product = $_POST['fk_product'.$i]; - if ($label) - { - if ($amountht) - { - $price_base='HT'; $amount=$amountht; - } - else - { - $price_base='TTC'; $amount=$amountttc; - } - $atleastoneline=1; - - $product=new Product($db); - $product->fetch($_POST['idprod'.$i]); - - $ret=$object->addline($label, $amount, $tauxtva, $product->localtax1_tx, $product->localtax2_tx, $qty, $fk_product, $remise_percent, '', '', '', 0, $price_base, $_POST['rang'.$i], 1); - if ($ret < 0) $error++; - } - } - } } } } @@ -816,41 +784,49 @@ if (empty($reshook)) $db->begin(); $object->fetch($id); - $object->fetch_thirdparty(); + $object->fetch_thirdparty(); - $tva_tx = GETPOST('tva_tx'); + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); if (GETPOST('price_ht') != '') - { - $up = price2num(GETPOST('price_ht')); - $price_base_type = 'HT'; - } - else - { - $up = price2num(GETPOST('price_ttc')); - $price_base_type = 'TTC'; - } + { + $up = price2num(GETPOST('price_ht')); + $price_base_type = 'HT'; + } + else + { + $up = price2num(GETPOST('price_ttc')); + $price_base_type = 'TTC'; + } - if (GETPOST('productid')) - { - $prod = new Product($db); - $prod->fetch(GETPOST('productid')); - $label = $prod->description; - if (trim($_POST['product_desc']) != trim($label)) $label=$_POST['product_desc']; + if (GETPOST('productid')) + { + $prod = new Product($db); + $prod->fetch(GETPOST('productid')); + $label = $prod->description; + if (trim($_POST['product_desc']) != trim($label)) $label=$_POST['product_desc']; - $type = $prod->type; - } - else - { - $label = $_POST['product_desc']; - $type = $_POST["type"]?$_POST["type"]:0; - } + $type = $prod->type; + } + else + { + $label = $_POST['product_desc']; + $type = $_POST["type"]?$_POST["type"]:0; + } - $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); - $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); + $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); + + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $tva_tx)) + $info_bits |= 0x01; + + // Define vat_rate + $tva_tx = str_replace('*', '', $tva_tx); + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - $localtax1_tx= get_localtax($_POST['tauxtva'], 1, $mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($_POST['tauxtva'], 2, $mysoc,$object->thirdparty); $remise_percent=GETPOST('remise_percent'); $pu_ht_devise = GETPOST('multicurrency_subprice'); @@ -865,7 +841,7 @@ if (empty($reshook)) } } - $result=$object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, 0, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise); + $result=$object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise); if ($result >= 0) { unset($_POST['label']); @@ -882,28 +858,28 @@ if (empty($reshook)) unset($_POST['date_endmonth']); unset($_POST['date_endyear']); - $db->commit(); - } - else - { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } + $db->commit(); + } + else + { + $db->rollback(); + setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer) { $db->begin(); - $ret=$object->fetch($id); - if ($ret < 0) - { - dol_print_error($db,$object->error); - exit; - } - $ret=$object->fetch_thirdparty(); + $ret=$object->fetch($id); + if ($ret < 0) + { + dol_print_error($db,$object->error); + exit; + } + $ret=$object->fetch_thirdparty(); - $langs->load('errors'); + $langs->load('errors'); $error=0; // Set if we used free entry or predefined product @@ -930,43 +906,43 @@ if (empty($reshook)) $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - // Unset extrafield - if (is_array($extralabelsline)) { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); - } - } + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + // Unset extrafield + if (is_array($extralabelsline)) { + // Get extra fields + foreach ($extralabelsline as $key => $value) { + unset($_POST["options_" . $key]); + } + } - if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0) - { - setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise==='') // Unit price can be 0 but not '' - { - setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors'); - $error++; - } - if ($prod_entry_mode =='free' && ! GETPOST('dp_desc')) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); - $error++; - } - if (! GETPOST('qty')) - { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); - $error++; - } + if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0) + { + setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise==='') // Unit price can be 0 but not '' + { + setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors'); + $error++; + } + if ($prod_entry_mode =='free' && ! GETPOST('dp_desc')) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); + $error++; + } + if (! GETPOST('qty')) + { + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); + $error++; + } if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') { if ($combinations = GETPOST('combinations', 'array')) { @@ -983,11 +959,11 @@ if (empty($reshook)) } if ($prod_entry_mode != 'free' && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { - $productsupplier=new ProductFournisseur($db); + { + $productsupplier=new ProductFournisseur($db); - $idprod=0; - if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + $idprod=0; + if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) if (preg_match('/^idprod_([0-9]+)$/',GETPOST('idprodfournprice'), $reg)) { @@ -997,68 +973,68 @@ if (empty($reshook)) // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price $productsupplier->get_buyprice(0, -1, $idprod, 'none'); // We force qty to -1 to be sure to find if a supplier price exist } - elseif (GETPOST('idprodfournprice') > 0) - { - $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. - //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist - $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); - $res=$productsupplier->fetch($idprod); - } + elseif (GETPOST('idprodfournprice') > 0) + { + $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat. + //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist + $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch); + $res=$productsupplier->fetch($idprod); + } - //Replaces $fk_unit with the product's - if ($idprod > 0) - { - $label = $productsupplier->label; + //Replaces $fk_unit with the product's + if ($idprod > 0) + { + $label = $productsupplier->label; - $desc = $productsupplier->description; - if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); + $desc = $productsupplier->description; + if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc); - $tva_tx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); - $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); + $tva_tx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); + $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']); if (empty($tva_tx)) $tva_npr=0; - $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); - $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); + $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); + $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - $type = $productsupplier->type; - $price_base_type = 'HT'; + $type = $productsupplier->type; + $price_base_type = 'HT'; - // TODO Save the product supplier ref into database (like done for supplier propal and order) into field ref_supplier (must rename field ref into ref_supplier first) - $result=$object->addline( - $desc, - $productsupplier->fourn_pu, - $tva_tx, - $localtax1_tx, - $localtax2_tx, - $qty, - $idprod, - $remise_percent, - $date_start, - $date_end, - 0, - $tva_npr, - $price_base_type, - $type, - -1, - 0, - $array_options, - $productsupplier->fk_unit - ); - } - if ($idprod == -99 || $idprod == 0) - { - // Product not selected - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); - } - if ($idprod == -1) - { - // Quantity too low - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); - } - } + // TODO Save the product supplier ref into database (like done for supplier propal and order) into field ref_supplier (must rename field ref into ref_supplier first) + $result=$object->addline( + $desc, + $productsupplier->fourn_pu, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $qty, + $idprod, + $remise_percent, + $date_start, + $date_end, + 0, + $tva_npr, + $price_base_type, + $type, + -1, + 0, + $array_options, + $productsupplier->fk_unit + ); + } + if ($idprod == -99 || $idprod == 0) + { + // Product not selected + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); + } + if ($idprod == -1) + { + // Quantity too low + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); + } + } else if (empty($error)) // $price_ht is already set { $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); @@ -1069,11 +1045,11 @@ if (empty($reshook)) $fk_unit= GETPOST('units', 'alpha'); - $tva_tx = price2num($tva_tx); // When vat is text input field + $tva_tx = price2num($tva_tx); // When vat is text input field - // Local Taxes - $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); - $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); + // Local Taxes + $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty); + $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty); if ($price_ht !== '') { @@ -1088,135 +1064,161 @@ if (empty($reshook)) $pu_ht_devise = price2num($price_ht_devise, 'MU'); $result=$object->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $date_start, $date_end, 0, $tva_npr, $price_base_type, $type, -1, 0, $array_options, $fk_unit, 0, $pu_ht_devise); - } + } - //print "xx".$tva_tx; exit; - if (! $error && $result > 0) - { - $db->commit(); + //print "xx".$tva_tx; exit; + if (! $error && $result > 0) + { + $db->commit(); - // 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 + // 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->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } unset($_POST ['prod_entry_mode']); - unset($_POST['qty']); - unset($_POST['type']); - unset($_POST['remise_percent']); - unset($_POST['pu']); - unset($_POST['price_ht']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['pu']); + unset($_POST['price_ht']); unset($_POST['multicurrency_price_ht']); - unset($_POST['price_ttc']); - unset($_POST['tva_tx']); - unset($_POST['label']); - unset($localtax1_tx); - unset($localtax2_tx); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['label']); + unset($localtax1_tx); + unset($localtax2_tx); unset($_POST['np_marginRate']); unset($_POST['np_markRate']); - unset($_POST['dp_desc']); + unset($_POST['dp_desc']); unset($_POST['idprodfournprice']); - unset($_POST['units']); + unset($_POST['units']); - unset($_POST['date_starthour']); - unset($_POST['date_startmin']); - unset($_POST['date_startsec']); - unset($_POST['date_startday']); - unset($_POST['date_startmonth']); - unset($_POST['date_startyear']); - unset($_POST['date_endhour']); - unset($_POST['date_endmin']); - unset($_POST['date_endsec']); - unset($_POST['date_endday']); - unset($_POST['date_endmonth']); - unset($_POST['date_endyear']); - } - else + unset($_POST['date_starthour']); + unset($_POST['date_startmin']); + unset($_POST['date_startsec']); + unset($_POST['date_startday']); + unset($_POST['date_startmonth']); + unset($_POST['date_startyear']); + unset($_POST['date_endhour']); + unset($_POST['date_endmin']); + unset($_POST['date_endsec']); + unset($_POST['date_endday']); + unset($_POST['date_endmonth']); + unset($_POST['date_endyear']); + } + else { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } + $db->rollback(); + setEventMessages($object->error, $object->errors, 'errors'); + } - $action = ''; + $action = ''; } elseif ($action == 'classin' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); - $result=$object->setProject($projectid); + $object->fetch($id); + $result=$object->setProject($projectid); } // Set invoice to draft status - elseif ($action == 'edit' && $user->rights->fournisseur->facture->creer) + elseif ($action == 'confirm_edit' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer) { - $object->fetch($id); + $object->fetch($id); - $totalpaye = $object->getSommePaiement(); - $resteapayer = $object->total_ttc - $totalpaye; + $totalpaye = $object->getSommePaiement(); + $resteapayer = $object->total_ttc - $totalpaye; - // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees - //$ventilExportCompta = $object->getVentilExportCompta(); + // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees + //$ventilExportCompta = $object->getVentilExportCompta(); // On verifie si aucun paiement n'a ete effectue - if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) + if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0) { - $object->set_draft($user); + $idwarehouse = GETPOST('idwarehouse'); - // 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 + $object->fetch_thirdparty(); - $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db,$result); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } - $action=''; - } + // Check parameters + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + if (! $idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action=''; + } + } + + $object->set_draft($user, $idwarehouse); + + // 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->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } + + $action=''; + } } // Set invoice to validated/unpaid status elseif ($action == 'reopen' && $user->rights->fournisseur->facture->creer) { - $result = $object->fetch($id); - if ($object->statut == FactureFournisseur::STATUS_CLOSED - || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) - { - $result = $object->set_unpaid($user); - if ($result > 0) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $result = $object->fetch($id); + if ($object->statut == FactureFournisseur::STATUS_CLOSED + || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) + { + $result = $object->set_unpaid($user); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } // Actions when printing a doc from card @@ -1239,14 +1241,14 @@ if (empty($reshook)) { $calculationrule=GETPOST('calculationrule'); - $object->fetch($id); - $object->fetch_thirdparty(); + $object->fetch($id); + $object->fetch_thirdparty(); $result=$object->update_price(0, (($calculationrule=='totalofround')?'0':'1'), 0, $object->thirdparty); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } + if ($result <= 0) + { + dol_print_error($db,$result); + exit; + } } if ($action == 'update_extras') { @@ -1371,9 +1373,9 @@ if ($action == 'create') $facturestatic = new FactureFournisseur($db); $extralabels = $extrafields->fetch_name_optionals_label($facturestatic->table_element); - print load_fiche_titre($langs->trans('NewBill')); + print load_fiche_titre($langs->trans('NewBill')); - dol_htmloutput_events(); + dol_htmloutput_events(); $currency_code = $conf->currency; @@ -1385,49 +1387,49 @@ if ($action == 'create') if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code; } - if (! empty($origin) && ! empty($originid)) - { - // Parse element/subelement (ex: project_task) - $element = $subelement = $origin; + if (! empty($origin) && ! empty($originid)) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $origin; - if ($element == 'project') - { - $projectid = $originid; - $element = 'projet'; - } - else if (in_array($element,array('order_supplier'))) - { - // For compatibility - if ($element == 'order') { - $element = $subelement = 'commande'; - } - if ($element == 'propal') { - $element = 'comm/propal'; $subelement = 'propal'; - } - if ($element == 'contract') { - $element = $subelement = 'contrat'; - } - if ($element == 'order_supplier') { - $element = 'fourn'; $subelement = 'fournisseur.commande'; - } + if ($element == 'project') + { + $projectid = $originid; + $element = 'projet'; + } + else if (in_array($element,array('order_supplier'))) + { + // For compatibility + if ($element == 'order') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; $subelement = 'propal'; + } + if ($element == 'contract') { + $element = $subelement = 'contrat'; + } + if ($element == 'order_supplier') { + $element = 'fourn'; $subelement = 'fournisseur.commande'; + } - require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; - $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur'; - $objectsrc = new $classname($db); - $objectsrc->fetch($originid); - $objectsrc->fetch_thirdparty(); + require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; + $classname = ucfirst($subelement); + if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur'; + $objectsrc = new $classname($db); + $objectsrc->fetch($originid); + $objectsrc->fetch_thirdparty(); - $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); - //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); + $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:''); + //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:''); - $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); - $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); - $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); - $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); - $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); - $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; + $soc = $objectsrc->thirdparty; + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); + $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); + $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); + $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; if (!empty($conf->multicurrency->enabled)) { @@ -1435,56 +1437,61 @@ if ($action == 'create') if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; } - $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); - $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); - $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); - $datedue=($datetmp==''?-1:$datetmp); - } - } - else - { + $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); + $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); + $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); + $datedue=($datetmp==''?-1:$datetmp); + + // Replicate extrafields + $objectsrc->fetch_optionals($originid); + $object->array_options = $objectsrc->array_options; + + } + } + else + { $cond_reglement_id = $societe->cond_reglement_supplier_id; $mode_reglement_id = $societe->mode_reglement_supplier_id; - $fk_account = $societe->fk_account; - $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); - $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); - $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); - $datedue=($datetmp==''?-1:$datetmp); + $fk_account = $societe->fk_account; + $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); + $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); + $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); + $datedue=($datetmp==''?-1:$datetmp); if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; - } + } - print '
    '; - print ''; - print ''; - if ($societe->id > 0) print '' . "\n"; - print ''; - print ''; + print ''; + print ''; + print ''; + if ($societe->id > 0) print '' . "\n"; + print ''; + print ''; if (!empty($currency_tx)) print ''; - dol_fiche_head(); + dol_fiche_head(); - print ''; + print '
    '; - // Ref - print ''; + // Ref + print ''; - // Third party - print ''; - print ''; + print ''; + } + print ' '.$langs->trans("AddThirdParty").''; + } + print ''; - // Ref supplier - print ''; - print ''; + // Ref supplier + print ''; + print ''; - // Type invoice + // Type invoice $facids = $facturestatic->list_replacable_supplier_invoices($societe->id); if ($facids < 0) { dol_print_error($db, $facturestatic); @@ -1640,19 +1647,19 @@ if ($action == 'create') if (empty($origin)) { - if ($conf->global->MAIN_FEATURES_LEVEL > 0) // Need to fix reports of standard accounting module to manage supplier credit note - { - if ($societe->id > 0) - { - // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { - print '
    '; - $tmp=' + if ($conf->global->MAIN_FEATURES_LEVEL > 0) // Need to fix reports of standard accounting module to manage supplier credit note + { + if ($societe->id > 0) + { + // Credit note + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) + { + print '
    '; + $tmp=' jQuery(document).ready(function() { if (! jQuery("#radio_creditnote").is(":checked")) { @@ -1666,41 +1673,41 @@ if ($action == 'create') }); }); '; - $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; - // $text.=''; - $text .= ''; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; + $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; + // $text.=''; + $text .= ''; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; - print '
    '; - print '    0 ? 'checked':'').' /> "; - print '
        0 ? 'checked':'').' /> "; - print '
    '; + print '
    '; + print '    0 ? 'checked':'').' /> "; + print '
        0 ? 'checked':'').' /> "; + print '
    '; - print '
    '; - } - } - else - { - print '
    '; - $tmp=' '; - $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; - $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; - $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); - print $desc; - print '
    ' . "\n"; - } - } + print '
    '; + } + } + else + { + print '
    '; + $tmp=' '; + $text = $tmp.$langs->trans("InvoiceAvoir") . ' '; + $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
    ' . "\n"; + } + } } print ''; @@ -1727,18 +1734,18 @@ if ($action == 'create') print ''; } - // Label - print ''; + // Label + print ''; - // Date invoice - print ''; + // Date invoice + print ''; - // Due date - print ''; + // Due date + print ''; // Payment term print ''; - // Bank Account - print ''; + // Bank Account + print ''; // Multicurrency if (! empty($conf->multicurrency->enabled)) { print ''; print ''; - print ''; } @@ -1781,73 +1788,73 @@ if ($action == 'create') { print ''; print ''; - print ''; } // Public note print ''; - print ''; + print ''; // print ''; - print ''; + print ''; - // Private note - print ''; - print ''; - // print ''; - print ''; + // Private note + print ''; + print ''; + // print ''; + print ''; if (empty($reshook) && ! empty($extrafields->attribute_label)) { print $object->showOptionals($extrafields, 'edit'); } - if (is_object($objectsrc)) - { - print "\n"; - print "\n"; - print ''."\n"; - print ''."\n"; - print ''."\n"; - print ''; - print ''; + if (is_object($objectsrc)) + { + print "\n"; + print "\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''; + print ''; - $txt=$langs->trans($classname); - if ($classname=='CommandeFournisseur') { - $langs->load('orders'); - $txt=$langs->trans("SupplierOrder"); - } - print ''; - print ''; - print '"; - if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 - { - print '"; - } + $txt=$langs->trans($classname); + if ($classname=='CommandeFournisseur') { + $langs->load('orders'); + $txt=$langs->trans("SupplierOrder"); + } + print ''; + print ''; + print '"; + if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 + { + print '"; + } - if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 - { - print '"; - } - print '"; + if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 + { + print '"; + } + print '"; if (!empty($conf->multicurrency->enabled)) { @@ -1855,168 +1862,211 @@ if ($action == 'create') print '"; print '"; } - } + } - // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Other options + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - // Bouton "Create Draft" - print "
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    '.$langs->trans('Ref').''.$langs->trans('Draft').'
    '.$langs->trans('Supplier').''; + // Third party + print '
    '.$langs->trans('Supplier').''; - if ($societe->id > 0) - { - print $societe->getNomUrl(1); - print ''; - } - else - { - print $form->select_company($societe->id, 'socid', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); - // reload page to retrieve supplier informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { - print ''; - } - print ' '.$langs->trans("AddThirdParty").''; - } - print '
    '.$langs->trans('RefSupplier').'
    '.$langs->trans('RefSupplier').'
    '.$langs->trans('Label').'
    '.$langs->trans('Label').'
    '.$langs->trans('DateInvoice').''; - $form->select_date($dateinvoice,'','','','',"add",1,1); - print '
    '.$langs->trans('DateInvoice').''; + $form->select_date($dateinvoice,'','','','',"add",1,1); + print '
    '.$langs->trans('DateMaxPayment').''; - $form->select_date($datedue,'ech','','','',"add",1,1); - print '
    '.$langs->trans('DateMaxPayment').''; + $form->select_date($datedue,'ech','','','',"add",1,1); + print '
    '.$langs->trans('PaymentConditionsShort').''; @@ -1750,18 +1757,18 @@ if ($action == 'create') $form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id, 'mode_reglement_id', 'DBIT'); print '
    '.$langs->trans('BankAccount').''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); - print '
    '.$langs->trans('BankAccount').''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
    '.fieldLabel('Currency','multicurrency_code').''; - print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); + print ''; + print $form->selectMultiCurrency($currency_code, 'multicurrency_code'); print '
    '; - print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:'')); + print ''; + print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:'')); print '
    '.$langs->trans('NotePublic').''; - $note_public = $object->getDefaultCreateValueFor('note_public'); - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print ''; + $note_public = $object->getDefaultCreateValueFor('note_public'); + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
    '.$langs->trans('NotePrivate').''; - $note_private = $object->getDefaultCreateValueFor('note_private'); - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - print '
    '.$langs->trans('NotePrivate').''; + $note_private = $object->getDefaultCreateValueFor('note_private'); + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + print '
    '.$txt.''.$objectsrc->getNomUrl(1); - // We check if Origin document (id and type is known) has already at least one invoice attached to it - $objectsrc->fetchObjectLinked($originid,$origin,'','invoice_supplier'); - $cntinvoice=count($objectsrc->linkedObjects['invoice_supplier']); - if ($cntinvoice>=1) - { - setEventMessages('WarningBillExist', null, 'warnings'); - echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['invoice_supplier'])->getNomUrl(1).')'; - } - echo '
    '.$langs->trans('TotalHT').''.price($objectsrc->total_ht).'
    '.$langs->trans('TotalVAT').''.price($objectsrc->total_tva)."
    '.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($objectsrc->total_localtax1)."
    '.$txt.''.$objectsrc->getNomUrl(1); + // We check if Origin document (id and type is known) has already at least one invoice attached to it + $objectsrc->fetchObjectLinked($originid,$origin,'','invoice_supplier'); + $cntinvoice=count($objectsrc->linkedObjects['invoice_supplier']); + if ($cntinvoice>=1) + { + setEventMessages('WarningBillExist', null, 'warnings'); + echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['invoice_supplier'])->getNomUrl(1).')'; + } + echo '
    '.$langs->trans('TotalHT').''.price($objectsrc->total_ht).'
    '.$langs->trans('TotalVAT').''.price($objectsrc->total_tva)."
    '.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($objectsrc->total_localtax1)."
    '.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($objectsrc->total_localtax2)."
    '.$langs->trans('TotalTTC').''.price($objectsrc->total_ttc)."
    '.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($objectsrc->total_localtax2)."
    '.$langs->trans('TotalTTC').''.price($objectsrc->total_ttc)."
    ' . $langs->trans('MulticurrencyTotalVAT') . '' . price($objectsrc->multicurrency_total_tva) . "
    ' . $langs->trans('MulticurrencyTotalTTC') . '' . price($objectsrc->multicurrency_total_ttc) . "
    \n"; + // Bouton "Create Draft" + print "\n"; - dol_fiche_end(); + dol_fiche_end(); - print '
    '; - print ''; + print '
    '; + print ''; print '     '; print ''; - print '
    '; + print '
    '; - print "
    \n"; + print "\n"; - // Show origin lines - if (is_object($objectsrc)) - { - print '
    '; + // Show origin lines + if (is_object($objectsrc)) + { + print '
    '; - $title=$langs->trans('ProductsAndServices'); - print load_fiche_titre($title); + $title=$langs->trans('ProductsAndServices'); + print load_fiche_titre($title); - print ''; + print '
    '; - $objectsrc->printOriginLinesList(); + $objectsrc->printOriginLinesList(); - print '
    '; - } + print ''; + } } else { - if ($id > 0 || ! empty($ref)) - { - /* *************************************************************************** */ - /* */ - /* Fiche en mode visu ou edition */ - /* */ - /* *************************************************************************** */ + if ($id > 0 || ! empty($ref)) + { + /* *************************************************************************** */ + /* */ + /* Fiche en mode visu ou edition */ + /* */ + /* *************************************************************************** */ - $now=dol_now(); + $now=dol_now(); - $productstatic = new Product($db); + $productstatic = new Product($db); - $object->fetch($id,$ref); - $result=$object->fetch_thirdparty(); - if ($result < 0) dol_print_error($db); + $object->fetch($id,$ref); + $result=$object->fetch_thirdparty(); + if ($result < 0) dol_print_error($db); - $societe = new Fournisseur($db); - $result=$societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + $societe = new Fournisseur($db); + $result=$societe->fetch($object->socid); + if ($result < 0) dol_print_error($db); - // fetch optionals attributes and labels + // fetch optionals attributes and labels $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $alreadypaid=$object->getSommePaiement(); - /* + /* * View card */ - $head = facturefourn_prepare_head($object); - $titre=$langs->trans('SupplierInvoice'); + $head = facturefourn_prepare_head($object); + $titre=$langs->trans('SupplierInvoice'); - dol_fiche_head($head, 'card', $titre, -1, 'bill'); + dol_fiche_head($head, 'card', $titre, -1, 'bill'); - // Clone confirmation - if ($action == 'clone') - { - // Create an array for form - $formquestion=array( - //'text' => $langs->trans("ConfirmClone"), - //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1) - ); - // Paiement incomplet. On demande si motif = escompte ou autre + // Clone confirmation + if ($action == 'clone') + { + // Create an array for form + $formquestion=array( + //'text' => $langs->trans("ConfirmClone"), + //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1) + ); + // Paiement incomplet. On demande si motif = escompte ou autre $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes', 1); - } + } - // Confirmation de la validation - if ($action == 'valid') - { + // Confirmation de la validation + if ($action == 'valid') + { // on verifie si l'objet est en numerotation provisoire - $objectref = substr($object->ref, 1, 4); - if ($objectref == 'PROV') - { - $savdate=$object->date; - $numref = $object->getNextNumRef($societe); - } - else - { - $numref = $object->ref; - } + $objectref = substr($object->ref, 1, 4); + if ($objectref == 'PROV') + { + $savdate=$object->date; + $numref = $object->getNextNumRef($societe); + } + else + { + $numref = $object->ref; + } - $text=$langs->trans('ConfirmValidateBill',$numref); - /*if (! empty($conf->notification->enabled)) + $text=$langs->trans('ConfirmValidateBill',$numref); + /*if (! empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php'; $notify=new Notify($db); $text.='
    '; $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object); }*/ - $formquestion=array(); + $formquestion=array(); - $qualified_for_stock_change=0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change=$object->hasProductsOrServices(2); - } - else - { - $qualified_for_stock_change=$object->hasProductsOrServices(1); - } + $qualified_for_stock_change=0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change=$object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change=$object->hasProductsOrServices(1); + } if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct=new FormProduct($db); - $formquestion=array( - //'text' => $langs->trans("ConfirmClone"), - //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), - //array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1))); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value) + ); } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1, 240); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1); } - // Confirmation set paid - if ($action == 'paid') + // Confirmation edit (back to draft) + if ($action == 'edit') { + $formquestion = array(); + + $qualified_for_stock_change = 0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change = $object->hasProductsOrServices(2); + } + else + { + $qualified_for_stock_change = $object->hasProductsOrServices(1); + } + if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value) + ); + } + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); + + } + + // Confirmation set paid + if ($action == 'paid') + { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1); - } + } - // Confirmation de la suppression de la facture fournisseur - if ($action == 'delete') - { + // Confirmation de la suppression de la facture fournisseur + if ($action == 'delete') + { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1); - } - if ($action == 'deletepaiement') - { - $payment_id = GETPOST('paiement_id'); + } + if ($action == 'deletepaiement') + { + $payment_id = GETPOST('paiement_id'); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1); - } + } - // Confirmation to delete line + // Confirmation to delete line if ($action == 'ask_deleteline') { $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } - if (!$formconfirm) - { + if (!$formconfirm) + { $parameters=array('lineid'=>$lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) $formconfirm.=$hookmanager->resPrint; @@ -2215,9 +2265,9 @@ else print ''; print ''; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { - if($action == 'actualizemulticurrencyrate') { - list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); - } + if($action == 'actualizemulticurrencyrate') { + list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); + } $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code); @@ -2230,35 +2280,35 @@ else print ''; } - // Bank Account - print ''; - print ''; - print '
    '; - print $langs->trans('BankAccount'); - print ''; - if ($action != 'editbankaccount' && $user->rights->fournisseur->facture->creer) - print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; - print ''; - if ($action == 'editbankaccount') { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); - } else { - $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); - } - print ""; - print ''; + // Bank Account + print ''; + print ''; + print '
    '; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->fournisseur->facture->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; + print ''; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print ""; + print ''; // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; - print '
    '; - print $langs->trans('IncotermLabel'); - print ''; - if ($user->rights->fournisseur->facture->creer) print ''.img_edit().''; - else print ' '; - print '
    '; - print ''; - print ''; + print '
    '; + print $langs->trans('IncotermLabel'); + print ''; + if ($user->rights->fournisseur->facture->creer) print ''.img_edit().''; + else print ' '; + print '
    '; + print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2267,142 +2317,142 @@ else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id); } - print ''; + print ''; } - // Other attributes - $cols = 2; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print ''; + print ''; - print '
    '; - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; + print '
    '; - print ''; + print '
    '; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { - // Multicurrency Amount HT - print ''; - print ''; - print ''; + // Multicurrency Amount HT + print ''; + print ''; + print ''; - // Multicurrency Amount VAT - print ''; - print ''; - print ''; + // Multicurrency Amount VAT + print ''; + print ''; + print ''; - // Multicurrency Amount TTC - print ''; - print ''; - print ''; - } + // Multicurrency Amount TTC + print ''; + print ''; + print ''; + } - // Amount - print ''; - print ''; + // Amount + print ''; + print ''; - // Amount Local Taxes - //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj=="1") //Localtax1 - { - print ''; - print ''; - print ''; - } - if ($societe->localtax2_assuj=="1") //Localtax2 - { - print ''; - print ''; - print ''; - } - print ''; + // Amount Local Taxes + //TODO: Place into a function to control showing by country or study better option + if ($societe->localtax1_assuj=="1") //Localtax1 + { + print ''; + print ''; + print ''; + } + if ($societe->localtax2_assuj=="1") //Localtax2 + { + print ''; + print ''; + print ''; + } + print ''; - print '
    ' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '.$langs->trans('AmountHT').''.price($object->total_ht,1,$langs,0,-1,-1,$conf->currency).'
    '.$langs->trans('AmountVAT').''.price($object->total_tva,1,$langs,0,-1,-1,$conf->currency).'
            '; - if (GETPOST('calculationrule')) $calculationrule=GETPOST('calculationrule','alpha'); - else $calculationrule=(empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)?'totalofround':'roundoftotal'); - if ($calculationrule == 'totalofround') $calculationrulenum=1; - else $calculationrulenum=2; - $s=$langs->trans("ReCalculate").' '; - $s.=''.$langs->trans("Mode1").''; - $s.=' / '; - $s.=''.$langs->trans("Mode2").''; - print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc",$calculationrulenum).'
    '.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('','help')); - print '
    '.$langs->trans('AmountHT').''.price($object->total_ht,1,$langs,0,-1,-1,$conf->currency).'
    '.$langs->trans('AmountVAT').''.price($object->total_tva,1,$langs,0,-1,-1,$conf->currency).'
            '; + if (GETPOST('calculationrule')) $calculationrule=GETPOST('calculationrule','alpha'); + else $calculationrule=(empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)?'totalofround':'roundoftotal'); + if ($calculationrule == 'totalofround') $calculationrulenum=1; + else $calculationrulenum=2; + $s=$langs->trans("ReCalculate").' '; + $s.=''.$langs->trans("Mode1").''; + $s.=' / '; + $s.=''.$langs->trans("Mode2").''; + print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc",$calculationrulenum).'
    '.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('','help')); + print '
    '.$langs->transcountry("AmountLT1",$societe->country_code).''.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).'
    '.$langs->transcountry("AmountLT2",$societe->country_code).''.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).'
    '.$langs->trans('AmountTTC').''.price($object->total_ttc,1,$langs,0,-1,-1,$conf->currency).'
    '.$langs->transcountry("AmountLT1",$societe->country_code).''.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).'
    '.$langs->transcountry("AmountLT2",$societe->country_code).''.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).'
    '.$langs->trans('AmountTTC').''.price($object->total_ttc,1,$langs,0,-1,-1,$conf->currency).'
    '; + print ''; - /* + /* * List of payments */ - $totalpaye = 0; + $totalpaye = 0; $sign = 1; if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = - 1; $nbrows=9; $nbcols=3; - if (! empty($conf->projet->enabled)) $nbrows++; - if (! empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } - if (! empty($conf->incoterm->enabled)) $nbrows++; + if (! empty($conf->projet->enabled)) $nbrows++; + if (! empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } + if (! empty($conf->incoterm->enabled)) $nbrows++; if (! empty($conf->multicurrency->enabled)) $nbrows += 5; - // Local taxes - if ($societe->localtax1_assuj=="1") $nbrows++; - if ($societe->localtax2_assuj=="1") $nbrows++; + // Local taxes + 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.= ' 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'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid'; - $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; - $sql.= ' ORDER BY p.datep, p.tms'; + $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, 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'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid'; + $sql.= ' WHERE pf.fk_facturefourn = '.$object->id; + $sql.= ' ORDER BY p.datep, p.tms'; - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - print ''; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + print '
    ' . ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . ''.$langs->trans('Date').''.$langs->trans('Type').''.$langs->trans('BankAccount').''.$langs->trans('Amount').' 
    '; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; - $var=false; - if ($num > 0) - { - while ($i < $num) - { - $objp = $db->fetch_object($result); + $var=false; + if ($num > 0) + { + while ($i < $num) + { + $objp = $db->fetch_object($result); - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) - { - $bankaccountstatic->id=$objp->baid; - $bankaccountstatic->ref=$objp->baref; - $bankaccountstatic->label=$objp->baref; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id=$objp->baid; + $bankaccountstatic->ref=$objp->baref; + $bankaccountstatic->label=$objp->baref; $bankaccountstatic->number = $objp->banumber; if (! empty($conf->accounting->enabled)) { @@ -2413,28 +2463,28 @@ else $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0,1,1,'',1); } - print ''; - } - print ''; - print ''; - print ''; - $totalpaye += $objp->amount; - $i++; - } - } - else - { - print ''; - } + print ''; + } + print ''; + print ''; + print ''; + $totalpaye += $objp->amount; + $i++; + } + } + else + { + print ''; + } /* if ($object->paye == 0) @@ -2449,12 +2499,12 @@ else } */ - $db->free($result); - } - else - { - dol_print_error($db); - } + $db->free($result); + } + else + { + dol_print_error($db); + } if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { @@ -2466,7 +2516,7 @@ else print $langs->trans('AlreadyPaid'); print ' :'; - $resteapayer = $object->total_ttc - $totalpaye; + $resteapayer = $object->total_ttc - $totalpaye; $resteapayeraffiche = $resteapayer; $cssforamountpaymentcomplete = 'amountpaymentcomplete'; @@ -2585,32 +2635,32 @@ else print '
    ' . ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . ''.$langs->trans('Date').''.$langs->trans('Type').''.$langs->trans('BankAccount').''.$langs->trans('Amount').' 
    '; - $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->payment_code=$objp->payment_code; - print $paymentstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->dp), 'day') . ''; - print $form->form_modes_reglement(null, $objp->paiement_type,'none').' '.$objp->num_paiement; - print '
    '; + $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->payment_code=$objp->payment_code; + print $paymentstatic->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->dp), 'day') . ''; + print $form->form_modes_reglement(null, $objp->paiement_type,'none').' '.$objp->num_paiement; + print ''; - if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1,'transactions'); - print '' . price($sign * $objp->amount) . ''; - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) - { - print 'rowid.'">'; - print img_delete(); - print ''; - } - print '
    '.$langs->trans("None").'
    '; + if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1,'transactions'); + print '' . price($sign * $objp->amount) . ''; + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) + { + print 'rowid.'">'; + print img_delete(); + print ''; + } + print '
    '.$langs->trans("None").'
    0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
    '; - print '
    '; - print '
    '; - print '
    '; + print '
    '; + print '
    '; + print '
    '; - print '

    '; + print '

    '; - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { - $blocname = 'contacts'; - $title = $langs->trans('ContactsAddresses'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) + { + $blocname = 'contacts'; + $title = $langs->trans('ContactsAddresses'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $colwidth=20; - $blocname = 'notes'; - $title = $langs->trans('Notes'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - } + if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $colwidth=20; + $blocname = 'notes'; + $title = $langs->trans('Notes'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + } - /* + /* * Lines */ - print '
    '; + print ''; print ''; print ''; print ''; @@ -2621,7 +2671,7 @@ else include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; } - print '
    '; + print '
    '; print ''; global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; @@ -2634,7 +2684,7 @@ else $num=count($object->lines); // Form to add new line - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $user->rights->fournisseur->facture->creer) + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $user->rights->fournisseur->facture->creer) { if ($action != 'editline') { @@ -2646,76 +2696,76 @@ else $parameters = array(); $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } - } + } - print '
    '; - print '
    '; - print ''; + print ''; + print '
    '; + print ''; - dol_fiche_end(); + dol_fiche_end(); - if ($action != 'presend') - { - /* + if ($action != 'presend') + { + /* * Boutons actions */ - print '
    '; + print '
    '; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { // Modify a validated invoice with no payments - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'edit' && $object->getSommePaiement() == 0 && $user->rights->fournisseur->facture->creer) + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $user->rights->fournisseur->facture->creer) { print ''; } // Reopen a standard paid invoice - if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT) && ($object->statut == 2 || $object->statut == 3)) // A paid invoice (partially or completely) - { - if (! $facidnext && $object->close_code != 'replaced' && $user->rights->fournisseur->facture->creer) // Not replaced by another invoice - { - print ''; - } - else - { - if ($user->rights->fournisseur->facture->creer) { - print '
    '.$langs->trans('ReOpen').'
    '; - } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { - print '
    '.$langs->trans('ReOpen').'
    '; - } - } - } + if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT) && ($object->statut == 2 || $object->statut == 3)) // A paid invoice (partially or completely) + { + if (! $facidnext && $object->close_code != 'replaced' && $user->rights->fournisseur->facture->creer) // Not replaced by another invoice + { + print ''; + } + else + { + if ($user->rights->fournisseur->facture->creer) { + print '
    '.$langs->trans('ReOpen').'
    '; + } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { + print '
    '.$langs->trans('ReOpen').'
    '; + } + } + } - // Send by mail - if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) - { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send) - { - print ''; - } - else print '
    '.$langs->trans('SendByMail').'
    '; - } + // Send by mail + if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) + { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send) + { + print ''; + } + else print '
    '.$langs->trans('SendByMail').'
    '; + } // Make payments - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) { print ''; // must use facid because id is for payment id not invoice } // Classify paid - if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) { print ''; - //print ''.$langs->trans('ClassifyPaid').''; - } + //print ''.$langs->trans('ClassifyPaid').''; + } // Reverse back money or convert to reduction if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { @@ -2744,7 +2794,7 @@ else } // Validate - if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) { if (count($object->lines)) { @@ -2768,11 +2818,11 @@ else print ''; } - // Clone - if ($action != 'edit' && $user->rights->fournisseur->facture->creer) - { - print ''; - } + // Clone + if ($action != 'edit' && $user->rights->fournisseur->facture->creer) + { + print ''; + } // Create a credit note if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $user->rights->fournisseur->facture->creer) @@ -2784,7 +2834,7 @@ else } // Delete - if ($action != 'edit' && $user->rights->fournisseur->facture->supprimer) + if ($action != 'confirm_edit' && $user->rights->fournisseur->facture->supprimer) { if ($object->getSommePaiement()) { print ''; @@ -2794,56 +2844,56 @@ else } print '
    '; - if ($action != 'edit') + if ($action != 'confirm_edit') { print '
    '; /* * Documents generes */ - $ref=dol_sanitizeFileName($object->ref); - $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; - $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir; - $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id; - $genallowed=$user->rights->fournisseur->facture->creer; - $delallowed=$user->rights->fournisseur->facture->supprimer; - $modelpdf=(! empty($object->modelpdf)?$object->modelpdf:(empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)?'':$conf->global->INVOICE_SUPPLIER_ADDON_PDF)); + $ref=dol_sanitizeFileName($object->ref); + $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; + $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir; + $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->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; + print $formfile->showdocuments('facture_fournisseur',$subdir,$filedir,$urlsource,$genallowed,$delallowed,$modelpdf,1,0,0,40,0,'','','',$societe->default_lang); + $somethingshown=$formfile->numoffiles; - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
    '; - //print ''; - //print '
    '; + print '
    '; + //print ''; + //print '
    '; - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object,'invoice_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions=new FormActions($db); + $somethingshown = $formactions->showactions($object,'invoice_supplier',$socid,1,'listaction'.($genallowed?'largetitle':'')); print '
    '; - //print ''; - } + //print ''; + } } - } + } - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } - // Presend form - $modelmail='supplier_order_send'; - $defaulttopic='SendBillRef'; - $diroutput = $conf->fournisseur->facture->dir_output; - $trackid = 'sin'.$object->id; + // Presend form + $modelmail='supplier_order_send'; + $defaulttopic='SendBillRef'; + $diroutput = $conf->fournisseur->facture->dir_output; + $trackid = 'sin'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; - } + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; + } } diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 77c0559aeca..c46f3de647e 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -51,9 +51,7 @@ $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -if ($page == -1) { - $page = 0; -} +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index e6c8023496c..508a9e28117 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -175,7 +175,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { foreach($extrafields->attribute_label as $key => $val) { - if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); } } @@ -1166,7 +1166,7 @@ if ($resql) $filedir=$diroutputmassaction; $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->creer; print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index 36749977927..14eca2c58d0 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -374,8 +374,8 @@ if ($result > 0) $ref=dol_sanitizeFileName($object->ref); $filedir = $conf->fournisseur->payment->dir_output.'/'.dol_sanitizeFileName($object->ref); $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id; - $genallowed=$user->rights->fournisseur->facture->creer; - $delallowed=$user->rights->fournisseur->facture->supprimer; + $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)); print $formfile->showdocuments('supplier_payment',$ref,$filedir,$urlsource,$genallowed,$delallowed,$modelpdf,1,0,0,40,0,'','','',$societe->default_lang); diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index ba976c2ee48..4381eacb3a7 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -34,8 +34,7 @@ class Holiday extends CommonObject { public $element='holiday'; public $table_element='holiday'; - protected $isnolinkedbythird = 1; // No field fk_soc - protected $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 0; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto = 'holiday'; /** @@ -829,7 +828,7 @@ class Holiday extends CommonObject global $langs; $result=''; - $picto='holiday'; + $label=$langs->trans("Show").': '.$this->ref; $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id; @@ -845,9 +844,11 @@ class Holiday extends CommonObject $linkstart = ''; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$linkstart.$this->ref.$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; } diff --git a/htdocs/holiday/list.php b/htdocs/holiday/list.php index f25dcb9e227..efe1c87820e 100644 --- a/htdocs/holiday/list.php +++ b/htdocs/holiday/list.php @@ -259,6 +259,8 @@ if ($id > 0) $fuser->fetch($id, '', '', 1); $fuser->getrights(); $user_id = $fuser->id; + + $search_employee = $user_id; } // Récupération des congés payés de l'utilisateur ou de tous les users diff --git a/htdocs/hrm/class/establishment.class.php b/htdocs/hrm/class/establishment.class.php index 413cb0cb584..8a99788d040 100644 --- a/htdocs/hrm/class/establishment.class.php +++ b/htdocs/hrm/class/establishment.class.php @@ -32,7 +32,7 @@ class Establishment extends CommonObject public $table_element='establishment'; public $table_element_line = ''; public $fk_element = 'fk_establishment'; - protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe public $picto='building'; public $id; diff --git a/htdocs/includes/jquery/plugins/fileupload/README.md b/htdocs/includes/jquery/plugins/fileupload/README.md deleted file mode 100644 index 513a028f06d..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# jQuery File Upload Plugin - -## Demo -[Demo File Upload](http://blueimp.github.com/jQuery-File-Upload/) - -## Setup instructions -* [How to setup the plugin on your website](https://github.com/blueimp/jQuery-File-Upload/wiki/Setup) -* [How to use only the basic plugin (minimal setup guide).](https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin) - -## Features -* **Multiple file upload:** - Allows to select multiple files at once and upload them simultaneously. -* **Drag & Drop support:** - Allows to upload files by dragging them from your desktop or filemanager and dropping them on your browser window. -* **Upload progress bar:** - Shows a progress bar indicating the upload progress for individual files and for all uploads combined. -* **Cancelable uploads:** - Individual file uploads can be canceled to stop the upload progress. -* **Resumable uploads:** - Aborted uploads can be resumed with browsers supporting the Blob API. -* **Chunked uploads:** - Large files can be uploaded in smaller chunks with browsers supporting the Blob API. -* **Client-side image resizing:** - Images can be automatically resized on client-side with browsers supporting the required JS APIs. -* **Preview images:** - A preview of image files can be displayed before uploading with browsers supporting the required JS APIs. -* **No browser plugins (e.g. Adobe Flash) required:** - The implementation is based on open standards like HTML5 and JavaScript and requires no additional browser plugins. -* **Graceful fallback for legacy browsers:** - Uploads files via XMLHttpRequests if supported and uses iframes as fallback for legacy browsers. -* **HTML file upload form fallback:** - Shows a standard HTML file upload form if JavaScript is disabled. -* **Cross-site file uploads:** - Supports uploading files to a different domain with Cross-site XMLHttpRequests. -* **Multiple plugin instances:** - Allows to use multiple plugin instances on the same webpage. -* **Customizable and extensible:** - Provides an API to set individual options and define callBack methods for various upload events. -* **Multipart and file contents stream uploads:** - Files can be uploaded as standard "multipart/form-data" or file contents stream (HTTP PUT file upload). -* **Compatible with any server-side application platform:** - Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads. - -## Requirements -* [jQuery](http://jquery.com/) v. 1.6+ -* [jQuery UI widget factory](http://wiki.jqueryui.com/w/page/12138135/Widget%20factory) v. 1.8+ -* [jQuery Iframe Transport plugin](https://github.com/blueimp/jQuery-File-Upload/blob/master/jquery.iframe-transport.js) (included) -* [JavaScript Templates engine](https://github.com/blueimp/JavaScript-Templates) v. 2.1.0+ (optional) -* [JavaScript Load Image function](https://github.com/blueimp/JavaScript-Load-Image) v. 1.1.6+ (optional) -* [JavaScript Canvas to Blob function](https://github.com/blueimp/JavaScript-Canvas-to-Blob) v. 2.0.0+ (optional) -* [Bootstrap CSS Toolkit](https://github.com/twitter/bootstrap/) v. 2.0+ (optional) - -The jQuery UI widget factory is a requirement for the basic File Upload plugin, but very lightweight without any other dependencies. -The jQuery Iframe Transport is required for [browsers without XHR file upload support](https://github.com/blueimp/jQuery-File-Upload/wiki/Browser-support). -The UI version of the File Upload plugin also requires the JavaScript Templates engine as well as the JavaScript Load Image and JavaScript Canvas to Blob functions (for the image previews and resizing functionality). These dependencies are marked as optional, as the basic File Upload plugin can be used without them and the UI version of the plugin can be extended to override these dependencies with alternative solutions. - -The User Interface is built with Twitter's [Bootstrap](https://github.com/twitter/bootstrap/) Toolkit. This enables a CSS based, responsive layout and fancy transition effects on modern browsers. The demo also includes the [Bootstrap Image Gallery Plugin](https://github.com/blueimp/Bootstrap-Image-Gallery). Both of these components are optional and not required. - -The repository also includes the [jQuery XDomainRequest Transport plugin](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/cors/jquery.xdr-transport.js), which enables Cross-domain AJAX requests (GET and POST only) in Microsoft Internet Explorer >= 8. However, the XDomainRequest object doesn't support file uploads and the plugin is only used by the [Demo](http://blueimp.github.com/jQuery-File-Upload/) for Cross-domain requests to delete uploaded files from the demo file upload service. - -[Cross-domain File Uploads](https://github.com/blueimp/jQuery-File-Upload/wiki/Cross-domain-uploads) using the [Iframe Transport plugin](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js) require a redirect back to the origin server to retrieve the upload results. The [example implementation](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/main.js) makes use of [result.html](https://github.com/blueimp/jQuery-File-Upload/blob/master/cors/result.html) as a static redirect page for the origin server. - -## Browser Support (tested versions) -* Google Chrome - 7.0+ -* Apple Safari - 4.0+ -* Mozilla Firefox - 3.0+ -* Opera - 10.0+ -* Microsoft Internet Explorer 6.0+ - -Drag & Drop is only supported on Google Chrome, Firefox 4.0+ and Safari 5.0+. -Microsoft Internet Explorer has no support for multiple file selection or upload progress. -[Extended browser support information](https://github.com/blueimp/jQuery-File-Upload/wiki/Browser-support). - -## License -Released under the [MIT license](http://www.opensource.org/licenses/MIT). diff --git a/htdocs/includes/jquery/plugins/fileupload/css/jquery.fileupload-ui.css b/htdocs/includes/jquery/plugins/fileupload/css/jquery.fileupload-ui.css deleted file mode 100644 index c86d3d8e712..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/css/jquery.fileupload-ui.css +++ /dev/null @@ -1,117 +0,0 @@ -@charset 'UTF-8'; -/* - * jQuery File Upload UI Plugin CSS 6.3 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -.fileinput-button { - position: relative; - overflow: hidden; - float: left; - margin-right: 5px; -} -.fileinput-button input { - position: absolute; - top: 0; - right: 0; - margin: 0; - border: solid transparent; - border-width: 0 0 100px 200px; - opacity: 0; - filter: alpha(opacity=0); - -moz-transform: translate(-300px, 0) scale(4); - direction: ltr; - cursor: pointer; -} -.fileupload-buttonbar .ui-button, -.fileupload-buttonbar .toggle { - margin-bottom: 5px; -} -.files .progress { - width: 200px; -} -.files .progress, -.fileupload-buttonbar .progress { - height: 20px; -} -.files .ui-progressbar-value, -.fileupload-buttonbar .ui-progressbar-value { - background: url(../img/progressbar.gif); -} -.fileupload-buttonbar .fade, -.files .fade { - display: none; -} -.fileupload-loading { - position: absolute; - left: 50%; - width: 128px; - height: 128px; - background: url(../img/loading.gif) center no-repeat; - display: none; -} -.fileupload-processing .fileupload-loading { - display: block; -} - -/* Fix for IE 6: */ -*html .fileinput-button { - margin-right: -2px; -} -*html .fileinput-button .ui-button-text { - line-height: 24px; -} -*html .fileupload-buttonbar .ui-button { - margin-left: 3px; -} - -/* Fix for IE 7: */ -*+html .fileinput-button { - margin-right: 1px; -} -*+html .fileinput-button .ui-button-text { - line-height: 24px; -} -*+html .fileupload-buttonbar .ui-button { - margin-left: 3px; -} - -@media (max-width: 480px) { - .files .preview * { - width: 40px; - } - .files .name * { - width: 80px; - display: inline-block; - word-wrap: break-word; - } - .files .progress { - width: 20px; - } - .files .delete { - width: 60px; - } -} - -/* Fix for Webkit (Safari, Chrome) */ -@media screen and (-webkit-min-device-pixel-ratio:0) { - .fileinput-button { - margin-top: 2px; - } -} - -.span5 { - width: 400px; - float: left; -} -.span7 { - width: 560px ; - float: left; -} - diff --git a/htdocs/includes/jquery/plugins/fileupload/img/loading.gif b/htdocs/includes/jquery/plugins/fileupload/img/loading.gif deleted file mode 100644 index 90f28cbdbb3..00000000000 Binary files a/htdocs/includes/jquery/plugins/fileupload/img/loading.gif and /dev/null differ diff --git a/htdocs/includes/jquery/plugins/fileupload/img/progressbar.gif b/htdocs/includes/jquery/plugins/fileupload/img/progressbar.gif deleted file mode 100644 index fbcce6bc9ab..00000000000 Binary files a/htdocs/includes/jquery/plugins/fileupload/img/progressbar.gif and /dev/null differ diff --git a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.postmessage-transport.js b/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.postmessage-transport.js deleted file mode 100644 index 931b6352ba2..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.postmessage-transport.js +++ /dev/null @@ -1,117 +0,0 @@ -/* - * jQuery postMessage Transport Plugin 1.1 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint unparam: true, nomen: true */ -/*global define, window, document */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - - var counter = 0, - names = [ - 'accepts', - 'cache', - 'contents', - 'contentType', - 'crossDomain', - 'data', - 'dataType', - 'headers', - 'ifModified', - 'mimeType', - 'password', - 'processData', - 'timeout', - 'traditional', - 'type', - 'url', - 'username' - ], - convert = function (p) { - return p; - }; - - $.ajaxSetup({ - converters: { - 'postmessage text': convert, - 'postmessage json': convert, - 'postmessage html': convert - } - }); - - $.ajaxTransport('postmessage', function (options) { - if (options.postMessage && window.postMessage) { - var iframe, - loc = $('').prop('href', options.postMessage)[0], - target = loc.protocol + '//' + loc.host, - xhrUpload = options.xhr().upload; - return { - send: function (_, completeCallback) { - var message = { - id: 'postmessage-transport-' + (counter += 1) - }, - eventName = 'message.' + message.id; - iframe = $( - '' - ).bind('load', function () { - $.each(names, function (i, name) { - message[name] = options[name]; - }); - message.dataType = message.dataType.replace('postmessage ', ''); - $(window).bind(eventName, function (e) { - e = e.originalEvent; - var data = e.data, - ev; - if (e.origin === target && data.id === message.id) { - if (data.type === 'progress') { - ev = document.createEvent('Event'); - ev.initEvent(data.type, false, true); - $.extend(ev, data); - xhrUpload.dispatchEvent(ev); - } else { - completeCallback( - data.status, - data.statusText, - {postmessage: data.result}, - data.headers - ); - iframe.remove(); - $(window).unbind(eventName); - } - } - }); - iframe[0].contentWindow.postMessage( - message, - target - ); - }).appendTo(document.body); - }, - abort: function () { - if (iframe) { - iframe.remove(); - } - } - }; - } - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.xdr-transport.js b/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.xdr-transport.js deleted file mode 100644 index c42c54828d8..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/cors/jquery.xdr-transport.js +++ /dev/null @@ -1,85 +0,0 @@ -/* - * jQuery XDomainRequest Transport Plugin 1.1.2 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - * - * Based on Julian Aubourg's ajaxHooks xdr.js: - * https://github.com/jaubourg/ajaxHooks/ - */ - -/*jslint unparam: true */ -/*global define, window, XDomainRequest */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - if (window.XDomainRequest && !$.support.cors) { - $.ajaxTransport(function (s) { - if (s.crossDomain && s.async) { - if (s.timeout) { - s.xdrTimeout = s.timeout; - delete s.timeout; - } - var xdr; - return { - send: function (headers, completeCallback) { - function callback(status, statusText, responses, responseHeaders) { - xdr.onload = xdr.onerror = xdr.ontimeout = $.noop; - xdr = null; - completeCallback(status, statusText, responses, responseHeaders); - } - xdr = new XDomainRequest(); - // XDomainRequest only supports GET and POST: - if (s.type === 'DELETE') { - s.url = s.url + (/\?/.test(s.url) ? '&' : '?') + - '_method=DELETE'; - s.type = 'POST'; - } else if (s.type === 'PUT') { - s.url = s.url + (/\?/.test(s.url) ? '&' : '?') + - '_method=PUT'; - s.type = 'POST'; - } - xdr.open(s.type, s.url); - xdr.onload = function () { - callback( - 200, - 'OK', - {text: xdr.responseText}, - 'Content-Type: ' + xdr.contentType - ); - }; - xdr.onerror = function () { - callback(404, 'Not Found'); - }; - if (s.xdrTimeout) { - xdr.ontimeout = function () { - callback(0, 'timeout'); - }; - xdr.timeout = s.xdrTimeout; - } - xdr.send((s.hasContent && s.data) || null); - }, - abort: function () { - if (xdr) { - xdr.onerror = $.noop(); - xdr.abort(); - } - } - }; - } - }); - } -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-fp.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-fp.js deleted file mode 100644 index 634fb5e4ee5..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-fp.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - * jQuery File Upload File Processing Plugin 1.0 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2012, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global define, window, document */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define([ - 'jquery', - 'load-image', - 'canvas-to-blob', - './jquery.fileupload' - ], factory); - } else { - // Browser globals: - factory( - window.jQuery, - window.loadImage - ); - } -}(function ($, loadImage) { - 'use strict'; - - // The File Upload IP version extends the basic fileupload widget - // with file processing functionality: - $.widget('blueimpFP.fileupload', $.blueimp.fileupload, { - - options: { - // The list of file processing actions: - process: [ - /* - { - action: 'load', - fileTypes: /^image\/(gif|jpeg|png)$/, - maxFileSize: 20000000 // 20MB - }, - { - action: 'resize', - maxWidth: 1920, - maxHeight: 1200, - minWidth: 800, - minHeight: 600 - }, - { - action: 'save' - } - */ - ], - - // The add callback is invoked as soon as files are added to the - // fileupload widget (via file input selection, drag & drop or add - // API call). See the basic file upload widget for more information: - add: function (e, data) { - $(this).fileupload('process', data).done(function () { - data.submit(); - }); - } - }, - - processActions: { - // Loads the image given via data.files and data.index - // as canvas element. - // Accepts the options fileTypes (regular expression) - // and maxFileSize (integer) to limit the files to load: - load: function (data, options) { - var that = this, - file = data.files[data.index], - dfd = $.Deferred(); - if (window.HTMLCanvasElement && - window.HTMLCanvasElement.prototype.toBlob && - ($.type(options.maxFileSize) !== 'number' || - file.size < options.maxFileSize) && - (!options.fileTypes || - options.fileTypes.test(file.type))) { - loadImage( - file, - function (canvas) { - data.canvas = canvas; - dfd.resolveWith(that, [data]); - }, - {canvas: true} - ); - } else { - dfd.rejectWith(that, [data]); - } - return dfd.promise(); - }, - // Resizes the image given as data.canvas and updates - // data.canvas with the resized image. - // Accepts the options maxWidth, maxHeight, minWidth and - // minHeight to scale the given image: - resize: function (data, options) { - if (data.canvas) { - var canvas = loadImage.scale(data.canvas, options); - if (canvas.width !== data.canvas.width || - canvas.height !== data.canvas.height) { - data.canvas = canvas; - data.processed = true; - } - } - return data; - }, - // Saves the processed image given as data.canvas - // inplace at data.index of data.files: - save: function (data, options) { - // Do nothing if no processing has happened: - if (!data.canvas || !data.processed) { - return data; - } - var that = this, - file = data.files[data.index], - name = file.name, - dfd = $.Deferred(), - callback = function (blob) { - if (!blob.name) { - if (file.type === blob.type) { - blob.name = file.name; - } else if (file.name) { - blob.name = file.name.replace( - /\..+$/, - '.' + blob.type.substr(6) - ); - } - } - // Store the created blob at the position - // of the original file in the files list: - data.files[data.index] = blob; - dfd.resolveWith(that, [data]); - }; - // Use canvas.mozGetAsFile directly, to retain the filename, as - // Gecko doesn't support the filename option for FormData.append: - if (data.canvas.mozGetAsFile) { - callback(data.canvas.mozGetAsFile( - (/^image\/(jpeg|png)$/.test(file.type) && name) || - ((name && name.replace(/\..+$/, '')) || - 'blob') + '.png', - file.type - )); - } else { - data.canvas.toBlob(callback, file.type); - } - return dfd.promise(); - } - }, - - // Resizes the file at the given index and stores the created blob at - // the original position of the files list, returns a Promise object: - _processFile: function (files, index, options) { - var that = this, - dfd = $.Deferred().resolveWith(that, [{ - files: files, - index: index - }]), - chain = dfd.promise(); - that._processing += 1; - $.each(options.process, function (i, settings) { - chain = chain.pipe(function (data) { - return that.processActions[settings.action] - .call(this, data, settings); - }); - }); - chain.always(function () { - that._processing -= 1; - if (that._processing === 0) { - that.element - .removeClass('fileupload-processing'); - } - }); - if (that._processing === 1) { - that.element.addClass('fileupload-processing'); - } - return chain; - }, - - // Processes the files given as files property of the data parameter, - // returns a Promise object that allows to bind a done handler, which - // will be invoked after processing all files (inplace) is done: - process: function (data) { - var that = this, - options = $.extend({}, this.options, data); - if (options.process && options.process.length && - this._isXHRUpload(options)) { - $.each(data.files, function (index, file) { - that._processingQueue = that._processingQueue.pipe( - function () { - var dfd = $.Deferred(); - that._processFile(data.files, index, options) - .always(function () { - dfd.resolveWith(that); - }); - return dfd.promise(); - } - ); - }); - } - return this._processingQueue; - }, - - _create: function () { - $.blueimp.fileupload.prototype._create.call(this); - this._processing = 0; - this._processingQueue = $.Deferred().resolveWith(this) - .promise(); - } - - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-jui.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-jui.js deleted file mode 100644 index 69736a4a44d..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-jui.js +++ /dev/null @@ -1,141 +0,0 @@ -/* - * jQuery File Upload jQuery UI Plugin 1.2 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2012, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true */ -/*global define, window */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery', './jquery.fileupload-ui.js'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - $.widget('blueimpJUI.fileupload', $.blueimpUI.fileupload, { - options: { - sent: function (e, data) { - if (data.context && data.dataType && - data.dataType.substr(0, 6) === 'iframe') { - // Iframe Transport does not support progress events. - // In lack of an indeterminate progress bar, we set - // the progress to 100%, showing the full animated bar: - data.context - .find('.progress').progressbar( - 'option', - 'value', - 100 - ); - } - }, - progress: function (e, data) { - if (data.context) { - data.context.find('.progress').progressbar( - 'option', - 'value', - parseInt(data.loaded / data.total * 100, 10) - ); - } - }, - progressall: function (e, data) { - var $this = $(this); - $this.find('.fileupload-progress') - .find('.progress').progressbar( - 'option', - 'value', - parseInt(data.loaded / data.total * 100, 10) - ).end() - .find('.progress-extended').each(function () { - $(this).html( - $this.data('fileupload') - ._renderExtendedProgress(data) - ); - }); - } - }, - _renderUpload: function (func, files) { - var node = $.blueimpUI.fileupload.prototype - ._renderUpload.call(this, func, files), - showIconText = $(window).width() > 480; - node.find('.progress').empty().progressbar(); - node.find('.start button').button({ - icons: {primary: 'ui-icon-circle-arrow-e'}, - text: showIconText - }); - node.find('.cancel button').button({ - icons: {primary: 'ui-icon-cancel'}, - text: showIconText - }); - return node; - }, - _renderDownload: function (func, files) { - var node = $.blueimpUI.fileupload.prototype - ._renderDownload.call(this, func, files), - showIconText = $(window).width() > 480; - node.find('.delete button').button({ - icons: {primary: 'ui-icon-trash'}, - text: showIconText - }); - return node; - }, - _transition: function (node) { - var that = this, - deferred = $.Deferred(); - if (node.hasClass('fade')) { - node.fadeToggle(function () { - deferred.resolveWith(node); - }); - } else { - deferred.resolveWith(node); - } - return deferred; - }, - _create: function () { - $.blueimpUI.fileupload.prototype._create.call(this); - this.element - .find('.fileupload-buttonbar') - .find('.fileinput-button').each(function () { - var input = $(this).find('input:file').detach(); - $(this) - .button({icons: {primary: 'ui-icon-plusthick'}}) - .append(input); - }) - .end().find('.start') - .button({icons: {primary: 'ui-icon-circle-arrow-e'}}) - .end().find('.cancel') - .button({icons: {primary: 'ui-icon-cancel'}}) - .end().find('.delete') - .button({icons: {primary: 'ui-icon-trash'}}) - .end().find('.progress').empty().progressbar(); - }, - destroy: function () { - this.element - .find('.fileupload-buttonbar') - .find('.fileinput-button').each(function () { - var input = $(this).find('input:file').detach(); - $(this) - .button('destroy') - .append(input); - }) - .end().find('.start') - .button('destroy') - .end().find('.cancel') - .button('destroy') - .end().find('.delete') - .button('destroy') - .end().find('.progress').progressbar('destroy'); - $.blueimpUI.fileupload.prototype.destroy.call(this); - } - }); -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-ui.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-ui.js deleted file mode 100644 index 4c36f00865b..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload-ui.js +++ /dev/null @@ -1,736 +0,0 @@ -/* - * jQuery File Upload User Interface Plugin 6.9.4 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global define, window, document, URL, webkitURL, FileReader */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define([ - 'jquery', - 'tmpl', - 'load-image', - './jquery.fileupload-fp' - ], factory); - } else { - // Browser globals: - factory( - window.jQuery, - window.tmpl, - window.loadImage - ); - } -}(function ($, tmpl, loadImage) { - 'use strict'; - - // The UI version extends the FP (file processing) version or the basic - // file upload widget and adds complete user interface interaction: - var parentWidget = ($.blueimpFP || $.blueimp).fileupload; - $.widget('blueimpUI.fileupload', parentWidget, { - - options: { - // By default, files added to the widget are uploaded as soon - // as the user clicks on the start buttons. To enable automatic - // uploads, set the following option to true: - autoUpload: false, - // The following option limits the number of files that are - // allowed to be uploaded using this widget: - maxNumberOfFiles: undefined, - // The maximum allowed file size: - maxFileSize: undefined, - // The minimum allowed file size: - minFileSize: undefined, - // The regular expression for allowed file types, matches - // against either file type or file name: - acceptFileTypes: /.+$/i, - // The regular expression to define for which files a preview - // image is shown, matched against the file type: - previewSourceFileTypes: /^image\/(gif|jpeg|png)$/, - // The maximum file size of images that are to be displayed as preview: - previewSourceMaxFileSize: 5000000, // 5MB - // The maximum width of the preview images: - previewMaxWidth: 80, - // The maximum height of the preview images: - previewMaxHeight: 80, - // By default, preview images are displayed as canvas elements - // if supported by the browser. Set the following option to false - // to always display preview images as img elements: - previewAsCanvas: true, - // The ID of the upload template: - uploadTemplateId: 'template-upload', - // The ID of the download template: - downloadTemplateId: 'template-download', - // The container for the list of files. If undefined, it is set to - // an element with class "files" inside of the widget element: - filesContainer: undefined, - // By default, files are appended to the files container. - // Set the following option to true, to prepend files instead: - prependFiles: false, - // The expected data type of the upload response, sets the dataType - // option of the $.ajax upload requests: - dataType: 'json', - - // The add callback is invoked as soon as files are added to the fileupload - // widget (via file input selection, drag & drop or add API call). - // See the basic file upload widget for more information: - add: function (e, data) { - var that = $(this).data('fileupload'), - options = that.options, - files = data.files; - $(this).fileupload('process', data).done(function () { - that._adjustMaxNumberOfFiles(-files.length); - data.maxNumberOfFilesAdjusted = true; - data.files.valid = data.isValidated = that._validate(files); - data.context = that._renderUpload(files).data('data', data); - options.filesContainer[ - options.prependFiles ? 'prepend' : 'append' - ](data.context); - that._renderPreviews(files, data.context); - that._forceReflow(data.context); - that._transition(data.context).done( - function () { - if ((that._trigger('added', e, data) !== false) && - (options.autoUpload || data.autoUpload) && - data.autoUpload !== false && data.isValidated) { - data.submit(); - } - } - ); - }); - }, - // Callback for the start of each file upload request: - send: function (e, data) { - var that = $(this).data('fileupload'); - if (!data.isValidated) { - if (!data.maxNumberOfFilesAdjusted) { - that._adjustMaxNumberOfFiles(-data.files.length); - data.maxNumberOfFilesAdjusted = true; - } - if (!that._validate(data.files)) { - return false; - } - } - if (data.context && data.dataType && - data.dataType.substr(0, 6) === 'iframe') { - // Iframe Transport does not support progress events. - // In lack of an indeterminate progress bar, we set - // the progress to 100%, showing the full animated bar: - data.context - .find('.progress').addClass( - !$.support.transition && 'progress-animated' - ) - .attr('aria-valuenow', 100) - .find('.bar').css( - 'width', - '100%' - ); - } - return that._trigger('sent', e, data); - }, - // Callback for successful uploads: - done: function (e, data) { - var that = $(this).data('fileupload'), - template; - if (data.context) { - data.context.each(function (index) { - var file = ($.isArray(data.result) && - data.result[index]) || {error: 'emptyResult'}; - if (file.error) { - that._adjustMaxNumberOfFiles(1); - } - that._transition($(this)).done( - function () { - var node = $(this); - template = that._renderDownload([file]) - .replaceAll(node); - that._forceReflow(template); - that._transition(template).done( - function () { - data.context = $(this); - that._trigger('completed', e, data); - } - ); - } - ); - }); - } else { - if ($.isArray(data.result)) { - $.each(data.result, function (index, file) { - if (data.maxNumberOfFilesAdjusted && file.error) { - that._adjustMaxNumberOfFiles(1); - } else if (!data.maxNumberOfFilesAdjusted && - !file.error) { - that._adjustMaxNumberOfFiles(-1); - } - }); - data.maxNumberOfFilesAdjusted = true; - } - template = that._renderDownload(data.result) - .appendTo(that.options.filesContainer); - that._forceReflow(template); - that._transition(template).done( - function () { - data.context = $(this); - that._trigger('completed', e, data); - } - ); - } - }, - // Callback for failed (abort or error) uploads: - fail: function (e, data) { - var that = $(this).data('fileupload'), - template; - if (data.maxNumberOfFilesAdjusted) { - that._adjustMaxNumberOfFiles(data.files.length); - } - if (data.context) { - data.context.each(function (index) { - if (data.errorThrown !== 'abort') { - var file = data.files[index]; - file.error = file.error || data.errorThrown || - true; - that._transition($(this)).done( - function () { - var node = $(this); - template = that._renderDownload([file]) - .replaceAll(node); - that._forceReflow(template); - that._transition(template).done( - function () { - data.context = $(this); - that._trigger('failed', e, data); - } - ); - } - ); - } else { - that._transition($(this)).done( - function () { - $(this).remove(); - that._trigger('failed', e, data); - } - ); - } - }); - } else if (data.errorThrown !== 'abort') { - data.context = that._renderUpload(data.files) - .appendTo(that.options.filesContainer) - .data('data', data); - that._forceReflow(data.context); - that._transition(data.context).done( - function () { - data.context = $(this); - that._trigger('failed', e, data); - } - ); - } else { - that._trigger('failed', e, data); - } - }, - // Callback for upload progress events: - progress: function (e, data) { - if (data.context) { - var progress = parseInt(data.loaded / data.total * 100, 10); - data.context.find('.progress') - .attr('aria-valuenow', progress) - .find('.bar').css( - 'width', - progress + '%' - ); - } - }, - // Callback for global upload progress events: - progressall: function (e, data) { - var $this = $(this), - progress = parseInt(data.loaded / data.total * 100, 10), - globalProgressNode = $this.find('.fileupload-progress'), - extendedProgressNode = globalProgressNode - .find('.progress-extended'); - if (extendedProgressNode.length) { - extendedProgressNode.html( - $this.data('fileupload')._renderExtendedProgress(data) - ); - } - globalProgressNode - .find('.progress') - .attr('aria-valuenow', progress) - .find('.bar').css( - 'width', - progress + '%' - ); - }, - // Callback for uploads start, equivalent to the global ajaxStart event: - start: function (e) { - var that = $(this).data('fileupload'); - that._transition($(this).find('.fileupload-progress')).done( - function () { - that._trigger('started', e); - } - ); - }, - // Callback for uploads stop, equivalent to the global ajaxStop event: - stop: function (e) { - var that = $(this).data('fileupload'); - that._transition($(this).find('.fileupload-progress')).done( - function () { - $(this).find('.progress') - .attr('aria-valuenow', '0') - .find('.bar').css('width', '0%'); - $(this).find('.progress-extended').html(' '); - that._trigger('stopped', e); - } - ); - }, - // Callback for file deletion: - destroy: function (e, data) { - var that = $(this).data('fileupload'); - if (data.url) { - $.ajax(data); - that._adjustMaxNumberOfFiles(1); - } - that._transition(data.context).done( - function () { - $(this).remove(); - that._trigger('destroyed', e, data); - } - ); - } - }, - - // Link handler, that allows to download files - // by drag & drop of the links to the desktop: - _enableDragToDesktop: function () { - var link = $(this), - url = link.prop('href'), - name = link.prop('download'), - type = 'application/octet-stream'; - link.bind('dragstart', function (e) { - try { - e.originalEvent.dataTransfer.setData( - 'DownloadURL', - [type, name, url].join(':') - ); - } catch (err) {} - }); - }, - - _adjustMaxNumberOfFiles: function (operand) { - if (typeof this.options.maxNumberOfFiles === 'number') { - this.options.maxNumberOfFiles += operand; - if (this.options.maxNumberOfFiles < 1) { - this._disableFileInputButton(); - } else { - this._enableFileInputButton(); - } - } - }, - - _formatFileSize: function (bytes) { - if (typeof bytes !== 'number') { - return ''; - } - if (bytes >= 1000000000) { - return (bytes / 1000000000).toFixed(2) + ' GB'; - } - if (bytes >= 1000000) { - return (bytes / 1000000).toFixed(2) + ' MB'; - } - return (bytes / 1000).toFixed(2) + ' KB'; - }, - - _formatBitrate: function (bits) { - if (typeof bits !== 'number') { - return ''; - } - if (bits >= 1000000000) { - return (bits / 1000000000).toFixed(2) + ' Gbit/s'; - } - if (bits >= 1000000) { - return (bits / 1000000).toFixed(2) + ' Mbit/s'; - } - if (bits >= 1000) { - return (bits / 1000).toFixed(2) + ' kbit/s'; - } - return bits + ' bit/s'; - }, - - _formatTime: function (seconds) { - var date = new Date(seconds * 1000), - days = parseInt(seconds / 86400, 10); - days = days ? days + 'd ' : ''; - return days + - ('0' + date.getUTCHours()).slice(-2) + ':' + - ('0' + date.getUTCMinutes()).slice(-2) + ':' + - ('0' + date.getUTCSeconds()).slice(-2); - }, - - _formatPercentage: function (floatValue) { - return (floatValue * 100).toFixed(2) + ' %'; - }, - - _renderExtendedProgress: function (data) { - return this._formatBitrate(data.bitrate) + ' | ' + - this._formatTime( - (data.total - data.loaded) * 8 / data.bitrate - ) + ' | ' + - this._formatPercentage( - data.loaded / data.total - ) + ' | ' + - this._formatFileSize(data.loaded) + ' / ' + - this._formatFileSize(data.total); - }, - - _hasError: function (file) { - if (file.error) { - return file.error; - } - // The number of added files is subtracted from - // maxNumberOfFiles before validation, so we check if - // maxNumberOfFiles is below 0 (instead of below 1): - if (this.options.maxNumberOfFiles < 0) { - return 'maxNumberOfFiles'; - } - // Files are accepted if either the file type or the file name - // matches against the acceptFileTypes regular expression, as - // only browsers with support for the File API report the type: - if (!(this.options.acceptFileTypes.test(file.type) || - this.options.acceptFileTypes.test(file.name))) { - return 'acceptFileTypes'; - } - if (this.options.maxFileSize && - file.size > this.options.maxFileSize) { - return 'maxFileSize'; - } - if (typeof file.size === 'number' && - file.size < this.options.minFileSize) { - return 'minFileSize'; - } - return null; - }, - - _validate: function (files) { - var that = this, - valid = !!files.length; - $.each(files, function (index, file) { - file.error = that._hasError(file); - if (file.error) { - valid = false; - } - }); - return valid; - }, - - _renderTemplate: function (func, files) { - if (!func) { - return $(); - } - var result = func({ - files: files, - formatFileSize: this._formatFileSize, - options: this.options - }); - if (result instanceof $) { - return result; - } - return $(this.options.templatesContainer).html(result).children(); - }, - - _renderPreview: function (file, node) { - var that = this, - options = this.options, - dfd = $.Deferred(); - return ((loadImage && loadImage( - file, - function (img) { - node.append(img); - that._forceReflow(node); - that._transition(node).done(function () { - dfd.resolveWith(node); - }); - if (!$.contains(document.body, node[0])) { - // If the element is not part of the DOM, - // transition events are not triggered, - // so we have to resolve manually: - dfd.resolveWith(node); - } - }, - { - maxWidth: options.previewMaxWidth, - maxHeight: options.previewMaxHeight, - canvas: options.previewAsCanvas - } - )) || dfd.resolveWith(node)) && dfd; - }, - - _renderPreviews: function (files, nodes) { - var that = this, - options = this.options; - nodes.find('.preview span').each(function (index, element) { - var file = files[index]; - if (options.previewSourceFileTypes.test(file.type) && - ($.type(options.previewSourceMaxFileSize) !== 'number' || - file.size < options.previewSourceMaxFileSize)) { - that._processingQueue = that._processingQueue.pipe(function () { - var dfd = $.Deferred(); - that._renderPreview(file, $(element)).done( - function () { - dfd.resolveWith(that); - } - ); - return dfd.promise(); - }); - } - }); - return this._processingQueue; - }, - - _renderUpload: function (files) { - return this._renderTemplate( - this.options.uploadTemplate, - files - ); - }, - - _renderDownload: function (files) { - return this._renderTemplate( - this.options.downloadTemplate, - files - ).find('a[download]').each(this._enableDragToDesktop).end(); - }, - - _startHandler: function (e) { - e.preventDefault(); - var button = $(this), - template = button.closest('.template-upload'), - data = template.data('data'); - if (data && data.submit && !data.jqXHR && data.submit()) { - button.prop('disabled', true); - } - }, - - _cancelHandler: function (e) { - e.preventDefault(); - var template = $(this).closest('.template-upload'), - data = template.data('data') || {}; - if (!data.jqXHR) { - data.errorThrown = 'abort'; - e.data.fileupload._trigger('fail', e, data); - } else { - data.jqXHR.abort(); - } - }, - - _deleteHandler: function (e) { - e.preventDefault(); - var button = $(this); - e.data.fileupload._trigger('destroy', e, { - context: button.closest('.template-download'), - url: button.attr('data-url'), - type: button.attr('data-type') || 'DELETE', - dataType: e.data.fileupload.options.dataType - }); - }, - - _forceReflow: function (node) { - return $.support.transition && node.length && - node[0].offsetWidth; - }, - - _transition: function (node) { - var dfd = $.Deferred(); - if ($.support.transition && node.hasClass('fade')) { - node.bind( - $.support.transition.end, - function (e) { - // Make sure we don't respond to other transitions events - // in the container element, e.g. from button elements: - if (e.target === node[0]) { - node.unbind($.support.transition.end); - dfd.resolveWith(node); - } - } - ).toggleClass('in'); - } else { - node.toggleClass('in'); - dfd.resolveWith(node); - } - return dfd; - }, - - _initButtonBarEventHandlers: function () { - var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'), - filesList = this.options.filesContainer, - ns = this.options.namespace; - fileUploadButtonBar.find('.start') - .bind('click.' + ns, function (e) { - e.preventDefault(); - filesList.find('.start button').click(); - }); - fileUploadButtonBar.find('.cancel') - .bind('click.' + ns, function (e) { - e.preventDefault(); - filesList.find('.cancel button').click(); - }); - fileUploadButtonBar.find('.delete') - .bind('click.' + ns, function (e) { - e.preventDefault(); - filesList.find('.delete input:checked') - .siblings('button').click(); - fileUploadButtonBar.find('.toggle') - .prop('checked', false); - }); - fileUploadButtonBar.find('.toggle') - .bind('change.' + ns, function (e) { - filesList.find('.delete input').prop( - 'checked', - $(this).is(':checked') - ); - }); - }, - - _destroyButtonBarEventHandlers: function () { - this.element.find('.fileupload-buttonbar button') - .unbind('click.' + this.options.namespace); - this.element.find('.fileupload-buttonbar .toggle') - .unbind('change.' + this.options.namespace); - }, - - _initEventHandlers: function () { - parentWidget.prototype._initEventHandlers.call(this); - var eventData = {fileupload: this}; - this.options.filesContainer - .delegate( - '.start button', - 'click.' + this.options.namespace, - eventData, - this._startHandler - ) - .delegate( - '.cancel button', - 'click.' + this.options.namespace, - eventData, - this._cancelHandler - ) - .delegate( - '.delete button', - 'click.' + this.options.namespace, - eventData, - this._deleteHandler - ); - this._initButtonBarEventHandlers(); - }, - - _destroyEventHandlers: function () { - var options = this.options; - this._destroyButtonBarEventHandlers(); - options.filesContainer - .undelegate('.start button', 'click.' + options.namespace) - .undelegate('.cancel button', 'click.' + options.namespace) - .undelegate('.delete button', 'click.' + options.namespace); - parentWidget.prototype._destroyEventHandlers.call(this); - }, - - _enableFileInputButton: function () { - this.element.find('.fileinput-button input') - .prop('disabled', false) - .parent().removeClass('disabled'); - }, - - _disableFileInputButton: function () { - this.element.find('.fileinput-button input') - .prop('disabled', true) - .parent().addClass('disabled'); - }, - - _initTemplates: function () { - var options = this.options; - options.templatesContainer = document.createElement( - options.filesContainer.prop('nodeName') - ); - if (tmpl) { - if (options.uploadTemplateId) { - options.uploadTemplate = tmpl(options.uploadTemplateId); - } - if (options.downloadTemplateId) { - options.downloadTemplate = tmpl(options.downloadTemplateId); - } - } - }, - - _initFilesContainer: function () { - var options = this.options; - if (options.filesContainer === undefined) { - options.filesContainer = this.element.find('.files'); - } else if (!(options.filesContainer instanceof $)) { - options.filesContainer = $(options.filesContainer); - } - }, - - _stringToRegExp: function (str) { - var parts = str.split('/'), - modifiers = parts.pop(); - parts.shift(); - return new RegExp(parts.join('/'), modifiers); - }, - - _initRegExpOptions: function () { - var options = this.options; - if ($.type(options.acceptFileTypes) === 'string') { - options.acceptFileTypes = this._stringToRegExp( - options.acceptFileTypes - ); - } - if ($.type(options.previewSourceFileTypes) === 'string') { - options.previewSourceFileTypes = this._stringToRegExp( - options.previewSourceFileTypes - ); - } - }, - - _initSpecialOptions: function () { - parentWidget.prototype._initSpecialOptions.call(this); - this._initFilesContainer(); - this._initTemplates(); - this._initRegExpOptions(); - }, - - _create: function () { - parentWidget.prototype._create.call(this); - this._refreshOptionsList.push( - 'filesContainer', - 'uploadTemplateId', - 'downloadTemplateId' - ); - if (!$.blueimpFP) { - this._processingQueue = $.Deferred().resolveWith(this).promise(); - this.process = function () { - return this._processingQueue; - }; - } - }, - - enable: function () { - parentWidget.prototype.enable.call(this); - this.element.find('input, button').prop('disabled', false); - this._enableFileInputButton(); - }, - - disable: function () { - this.element.find('input, button').prop('disabled', true); - this._disableFileInputButton(); - parentWidget.prototype.disable.call(this); - } - - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload.js deleted file mode 100644 index 4bbd287295a..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.fileupload.js +++ /dev/null @@ -1,972 +0,0 @@ -/* - * jQuery File Upload Plugin 5.13 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global define, window, document, Blob, FormData, location */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define([ - 'jquery', - 'jquery.ui.widget' - ], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - - // The FileReader API is not actually used, but works as feature detection, - // as e.g. Safari supports XHR file uploads via the FormData API, - // but not non-multipart XHR file uploads: - $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader); - $.support.xhrFormDataFileUpload = !!window.FormData; - - // The fileupload widget listens for change events on file input fields defined - // via fileInput setting and paste or drop events of the given dropZone. - // In addition to the default jQuery Widget methods, the fileupload widget - // exposes the "add" and "send" methods, to add or directly send files using - // the fileupload API. - // By default, files added via file input selection, paste, drag & drop or - // "add" method are uploaded immediately, but it is possible to override - // the "add" callback option to queue file uploads. - $.widget('blueimp.fileupload', { - - options: { - // The namespace used for event handler binding on the dropZone and - // fileInput collections. - // If not set, the name of the widget ("fileupload") is used. - namespace: undefined, - // The drop target collection, by the default the complete document. - // Set to null or an empty collection to disable drag & drop support: - dropZone: $(document), - // The file input field collection, that is listened for change events. - // If undefined, it is set to the file input fields inside - // of the widget element on plugin initialization. - // Set to null or an empty collection to disable the change listener. - fileInput: undefined, - // By default, the file input field is replaced with a clone after - // each input field change event. This is required for iframe transport - // queues and allows change events to be fired for the same file - // selection, but can be disabled by setting the following option to false: - replaceFileInput: true, - // The parameter name for the file form data (the request argument name). - // If undefined or empty, the name property of the file input field is - // used, or "files[]" if the file input name property is also empty, - // can be a string or an array of strings: - paramName: undefined, - // By default, each file of a selection is uploaded using an individual - // request for XHR type uploads. Set to false to upload file - // selections in one request each: - singleFileUploads: true, - // To limit the number of files uploaded with one XHR request, - // set the following option to an integer greater than 0: - limitMultiFileUploads: undefined, - // Set the following option to true to issue all file upload requests - // in a sequential order: - sequentialUploads: false, - // To limit the number of concurrent uploads, - // set the following option to an integer greater than 0: - limitConcurrentUploads: undefined, - // Set the following option to true to force iframe transport uploads: - forceIframeTransport: false, - // Set the following option to the location of a redirect url on the - // origin server, for cross-domain iframe transport uploads: - redirect: undefined, - // The parameter name for the redirect url, sent as part of the form - // data and set to 'redirect' if this option is empty: - redirectParamName: undefined, - // Set the following option to the location of a postMessage window, - // to enable postMessage transport uploads: - postMessage: undefined, - // By default, XHR file uploads are sent as multipart/form-data. - // The iframe transport is always using multipart/form-data. - // Set to false to enable non-multipart XHR uploads: - multipart: true, - // To upload large files in smaller chunks, set the following option - // to a preferred maximum chunk size. If set to 0, null or undefined, - // or the browser does not support the required Blob API, files will - // be uploaded as a whole. - maxChunkSize: undefined, - // When a non-multipart upload or a chunked multipart upload has been - // aborted, this option can be used to resume the upload by setting - // it to the size of the already uploaded bytes. This option is most - // useful when modifying the options object inside of the "add" or - // "send" callbacks, as the options are cloned for each file upload. - uploadedBytes: undefined, - // By default, failed (abort or error) file uploads are removed from the - // global progress calculation. Set the following option to false to - // prevent recalculating the global progress data: - recalculateProgress: true, - // Interval in milliseconds to calculate and trigger progress events: - progressInterval: 100, - // Interval in milliseconds to calculate progress bitrate: - bitrateInterval: 500, - - // Additional form data to be sent along with the file uploads can be set - // using this option, which accepts an array of objects with name and - // value properties, a function returning such an array, a FormData - // object (for XHR file uploads), or a simple object. - // The form of the first fileInput is given as parameter to the function: - formData: function (form) { - return form.serializeArray(); - }, - - // The add callback is invoked as soon as files are added to the fileupload - // widget (via file input selection, drag & drop, paste or add API call). - // If the singleFileUploads option is enabled, this callback will be - // called once for each file in the selection for XHR file uplaods, else - // once for each file selection. - // The upload starts when the submit method is invoked on the data parameter. - // The data object contains a files property holding the added files - // and allows to override plugin options as well as define ajax settings. - // Listeners for this callback can also be bound the following way: - // .bind('fileuploadadd', func); - // data.submit() returns a Promise object and allows to attach additional - // handlers using jQuery's Deferred callbacks: - // data.submit().done(func).fail(func).always(func); - add: function (e, data) { - data.submit(); - }, - - // Other callbacks: - // Callback for the submit event of each file upload: - // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); - // Callback for the start of each file upload request: - // send: function (e, data) {}, // .bind('fileuploadsend', func); - // Callback for successful uploads: - // done: function (e, data) {}, // .bind('fileuploaddone', func); - // Callback for failed (abort or error) uploads: - // fail: function (e, data) {}, // .bind('fileuploadfail', func); - // Callback for completed (success, abort or error) requests: - // always: function (e, data) {}, // .bind('fileuploadalways', func); - // Callback for upload progress events: - // progress: function (e, data) {}, // .bind('fileuploadprogress', func); - // Callback for global upload progress events: - // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); - // Callback for uploads start, equivalent to the global ajaxStart event: - // start: function (e) {}, // .bind('fileuploadstart', func); - // Callback for uploads stop, equivalent to the global ajaxStop event: - // stop: function (e) {}, // .bind('fileuploadstop', func); - // Callback for change events of the fileInput collection: - // change: function (e, data) {}, // .bind('fileuploadchange', func); - // Callback for paste events to the dropZone collection: - // paste: function (e, data) {}, // .bind('fileuploadpaste', func); - // Callback for drop events of the dropZone collection: - // drop: function (e, data) {}, // .bind('fileuploaddrop', func); - // Callback for dragover events of the dropZone collection: - // dragover: function (e) {}, // .bind('fileuploaddragover', func); - - // The plugin options are used as settings object for the ajax calls. - // The following are jQuery ajax settings required for the file uploads: - processData: false, - contentType: false, - cache: false - }, - - // A list of options that require a refresh after assigning a new value: - _refreshOptionsList: [ - 'namespace', - 'dropZone', - 'fileInput', - 'multipart', - 'forceIframeTransport' - ], - - _BitrateTimer: function () { - this.timestamp = +(new Date()); - this.loaded = 0; - this.bitrate = 0; - this.getBitrate = function (now, loaded, interval) { - var timeDiff = now - this.timestamp; - if (!this.bitrate || !interval || timeDiff > interval) { - this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; - this.loaded = loaded; - this.timestamp = now; - } - return this.bitrate; - }; - }, - - _isXHRUpload: function (options) { - return !options.forceIframeTransport && - ((!options.multipart && $.support.xhrFileUpload) || - $.support.xhrFormDataFileUpload); - }, - - _getFormData: function (options) { - var formData; - if (typeof options.formData === 'function') { - return options.formData(options.form); - } - if ($.isArray(options.formData)) { - return options.formData; - } - if (options.formData) { - formData = []; - $.each(options.formData, function (name, value) { - formData.push({name: name, value: value}); - }); - return formData; - } - return []; - }, - - _getTotal: function (files) { - var total = 0; - $.each(files, function (index, file) { - total += file.size || 1; - }); - return total; - }, - - _onProgress: function (e, data) { - if (e.lengthComputable) { - var now = +(new Date()), - total, - loaded; - if (data._time && data.progressInterval && - (now - data._time < data.progressInterval) && - e.loaded !== e.total) { - return; - } - data._time = now; - total = data.total || this._getTotal(data.files); - loaded = parseInt( - e.loaded / e.total * (data.chunkSize || total), - 10 - ) + (data.uploadedBytes || 0); - this._loaded += loaded - (data.loaded || data.uploadedBytes || 0); - data.lengthComputable = true; - data.loaded = loaded; - data.total = total; - data.bitrate = data._bitrateTimer.getBitrate( - now, - loaded, - data.bitrateInterval - ); - // Trigger a custom progress event with a total data property set - // to the file size(s) of the current upload and a loaded data - // property calculated accordingly: - this._trigger('progress', e, data); - // Trigger a global progress event for all current file uploads, - // including ajax calls queued for sequential file uploads: - this._trigger('progressall', e, { - lengthComputable: true, - loaded: this._loaded, - total: this._total, - bitrate: this._bitrateTimer.getBitrate( - now, - this._loaded, - data.bitrateInterval - ) - }); - } - }, - - _initProgressListener: function (options) { - var that = this, - xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); - // Accesss to the native XHR object is required to add event listeners - // for the upload progress event: - if (xhr.upload) { - $(xhr.upload).bind('progress', function (e) { - var oe = e.originalEvent; - // Make sure the progress event properties get copied over: - e.lengthComputable = oe.lengthComputable; - e.loaded = oe.loaded; - e.total = oe.total; - that._onProgress(e, options); - }); - options.xhr = function () { - return xhr; - }; - } - }, - - _initXHRData: function (options) { - var formData, - file = options.files[0], - // Ignore non-multipart setting if not supported: - multipart = options.multipart || !$.support.xhrFileUpload, - paramName = options.paramName[0]; - if (!multipart || options.blob) { - // For non-multipart uploads and chunked uploads, - // file meta data is not part of the request body, - // so we transmit this data as part of the HTTP headers. - // For cross domain requests, these headers must be allowed - // via Access-Control-Allow-Headers or removed using - // the beforeSend callback: - options.headers = $.extend(options.headers, { - 'X-File-Name': file.name, - 'X-File-Type': file.type, - 'X-File-Size': file.size - }); - if (!options.blob) { - // Non-chunked non-multipart upload: - options.contentType = file.type; - options.data = file; - } else if (!multipart) { - // Chunked non-multipart upload: - options.contentType = 'application/octet-stream'; - options.data = options.blob; - } - } - if (multipart && $.support.xhrFormDataFileUpload) { - if (options.postMessage) { - // window.postMessage does not allow sending FormData - // objects, so we just add the File/Blob objects to - // the formData array and let the postMessage window - // create the FormData object out of this array: - formData = this._getFormData(options); - if (options.blob) { - formData.push({ - name: paramName, - value: options.blob - }); - } else { - $.each(options.files, function (index, file) { - formData.push({ - name: options.paramName[index] || paramName, - value: file - }); - }); - } - } else { - if (options.formData instanceof FormData) { - formData = options.formData; - } else { - formData = new FormData(); - $.each(this._getFormData(options), function (index, field) { - formData.append(field.name, field.value); - }); - } - if (options.blob) { - formData.append(paramName, options.blob, file.name); - } else { - $.each(options.files, function (index, file) { - // File objects are also Blob instances. - // This check allows the tests to run with - // dummy objects: - if (file instanceof Blob) { - formData.append( - options.paramName[index] || paramName, - file, - file.name - ); - } - }); - } - } - options.data = formData; - } - // Blob reference is not needed anymore, free memory: - options.blob = null; - }, - - _initIframeSettings: function (options) { - // Setting the dataType to iframe enables the iframe transport: - options.dataType = 'iframe ' + (options.dataType || ''); - // The iframe transport accepts a serialized array as form data: - options.formData = this._getFormData(options); - // Add redirect url to form data on cross-domain uploads: - if (options.redirect && $('').prop('href', options.url) - .prop('host') !== location.host) { - options.formData.push({ - name: options.redirectParamName || 'redirect', - value: options.redirect - }); - } - }, - - _initDataSettings: function (options) { - if (this._isXHRUpload(options)) { - if (!this._chunkedUpload(options, true)) { - if (!options.data) { - this._initXHRData(options); - } - this._initProgressListener(options); - } - if (options.postMessage) { - // Setting the dataType to postmessage enables the - // postMessage transport: - options.dataType = 'postmessage ' + (options.dataType || ''); - } - } else { - this._initIframeSettings(options, 'iframe'); - } - }, - - _getParamName: function (options) { - var fileInput = $(options.fileInput), - paramName = options.paramName; - if (!paramName) { - paramName = []; - fileInput.each(function () { - var input = $(this), - name = input.prop('name') || 'files[]', - i = (input.prop('files') || [1]).length; - while (i) { - paramName.push(name); - i -= 1; - } - }); - if (!paramName.length) { - paramName = [fileInput.prop('name') || 'files[]']; - } - } else if (!$.isArray(paramName)) { - paramName = [paramName]; - } - return paramName; - }, - - _initFormSettings: function (options) { - // Retrieve missing options from the input field and the - // associated form, if available: - if (!options.form || !options.form.length) { - options.form = $(options.fileInput.prop('form')); - } - options.paramName = this._getParamName(options); - if (!options.url) { - options.url = options.form.prop('action') || location.href; - } - // The HTTP request method must be "POST" or "PUT": - options.type = (options.type || options.form.prop('method') || '') - .toUpperCase(); - if (options.type !== 'POST' && options.type !== 'PUT') { - options.type = 'POST'; - } - }, - - _getAJAXSettings: function (data) { - var options = $.extend({}, this.options, data); - this._initFormSettings(options); - this._initDataSettings(options); - return options; - }, - - // Maps jqXHR callbacks to the equivalent - // methods of the given Promise object: - _enhancePromise: function (promise) { - promise.success = promise.done; - promise.error = promise.fail; - promise.complete = promise.always; - return promise; - }, - - // Creates and returns a Promise object enhanced with - // the jqXHR methods abort, success, error and complete: - _getXHRPromise: function (resolveOrReject, context, args) { - var dfd = $.Deferred(), - promise = dfd.promise(); - context = context || this.options.context || promise; - if (resolveOrReject === true) { - dfd.resolveWith(context, args); - } else if (resolveOrReject === false) { - dfd.rejectWith(context, args); - } - promise.abort = dfd.promise; - return this._enhancePromise(promise); - }, - - // Uploads a file in multiple, sequential requests - // by splitting the file up in multiple blob chunks. - // If the second parameter is true, only tests if the file - // should be uploaded in chunks, but does not invoke any - // upload requests: - _chunkedUpload: function (options, testOnly) { - var that = this, - file = options.files[0], - fs = file.size, - ub = options.uploadedBytes = options.uploadedBytes || 0, - mcs = options.maxChunkSize || fs, - // Use the Blob methods with the slice implementation - // according to the W3C Blob API specification: - slice = file.webkitSlice || file.mozSlice || file.slice, - upload, - n, - jqXHR, - pipe; - if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || - options.data) { - return false; - } - if (testOnly) { - return true; - } - if (ub >= fs) { - file.error = 'uploadedBytes'; - return this._getXHRPromise( - false, - options.context, - [null, 'error', file.error] - ); - } - // n is the number of blobs to upload, - // calculated via filesize, uploaded bytes and max chunk size: - n = Math.ceil((fs - ub) / mcs); - // The chunk upload method accepting the chunk number as parameter: - upload = function (i) { - if (!i) { - return that._getXHRPromise(true, options.context); - } - // Upload the blobs in sequential order: - return upload(i -= 1).pipe(function () { - // Clone the options object for each chunk upload: - var o = $.extend({}, options); - o.blob = slice.call( - file, - ub + i * mcs, - ub + (i + 1) * mcs - ); - // Expose the chunk index: - o.chunkIndex = i; - // Expose the number of chunks: - o.chunksNumber = n; - // Store the current chunk size, as the blob itself - // will be dereferenced after data processing: - o.chunkSize = o.blob.size; - // Process the upload data (the blob and potential form data): - that._initXHRData(o); - // Add progress listeners for this chunk upload: - that._initProgressListener(o); - jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context)) - .done(function () { - // Create a progress event if upload is done and - // no progress event has been invoked for this chunk: - if (!o.loaded) { - that._onProgress($.Event('progress', { - lengthComputable: true, - loaded: o.chunkSize, - total: o.chunkSize - }), o); - } - options.uploadedBytes = o.uploadedBytes += - o.chunkSize; - }); - return jqXHR; - }); - }; - // Return the piped Promise object, enhanced with an abort method, - // which is delegated to the jqXHR object of the current upload, - // and jqXHR callbacks mapped to the equivalent Promise methods: - pipe = upload(n); - pipe.abort = function () { - return jqXHR.abort(); - }; - return this._enhancePromise(pipe); - }, - - _beforeSend: function (e, data) { - if (this._active === 0) { - // the start callback is triggered when an upload starts - // and no other uploads are currently running, - // equivalent to the global ajaxStart event: - this._trigger('start'); - // Set timer for global bitrate progress calculation: - this._bitrateTimer = new this._BitrateTimer(); - } - this._active += 1; - // Initialize the global progress values: - this._loaded += data.uploadedBytes || 0; - this._total += this._getTotal(data.files); - }, - - _onDone: function (result, textStatus, jqXHR, options) { - if (!this._isXHRUpload(options)) { - // Create a progress event for each iframe load: - this._onProgress($.Event('progress', { - lengthComputable: true, - loaded: 1, - total: 1 - }), options); - } - options.result = result; - options.textStatus = textStatus; - options.jqXHR = jqXHR; - this._trigger('done', null, options); - }, - - _onFail: function (jqXHR, textStatus, errorThrown, options) { - options.jqXHR = jqXHR; - options.textStatus = textStatus; - options.errorThrown = errorThrown; - this._trigger('fail', null, options); - if (options.recalculateProgress) { - // Remove the failed (error or abort) file upload from - // the global progress calculation: - this._loaded -= options.loaded || options.uploadedBytes || 0; - this._total -= options.total || this._getTotal(options.files); - } - }, - - _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { - this._active -= 1; - options.textStatus = textStatus; - if (jqXHRorError && jqXHRorError.always) { - options.jqXHR = jqXHRorError; - options.result = jqXHRorResult; - } else { - options.jqXHR = jqXHRorResult; - options.errorThrown = jqXHRorError; - } - this._trigger('always', null, options); - if (this._active === 0) { - // The stop callback is triggered when all uploads have - // been completed, equivalent to the global ajaxStop event: - this._trigger('stop'); - // Reset the global progress values: - this._loaded = this._total = 0; - this._bitrateTimer = null; - } - }, - - _onSend: function (e, data) { - var that = this, - jqXHR, - slot, - pipe, - options = that._getAJAXSettings(data), - send = function (resolve, args) { - that._sending += 1; - // Set timer for bitrate progress calculation: - options._bitrateTimer = new that._BitrateTimer(); - jqXHR = jqXHR || ( - (resolve !== false && - that._trigger('send', e, options) !== false && - (that._chunkedUpload(options) || $.ajax(options))) || - that._getXHRPromise(false, options.context, args) - ).done(function (result, textStatus, jqXHR) { - that._onDone(result, textStatus, jqXHR, options); - }).fail(function (jqXHR, textStatus, errorThrown) { - that._onFail(jqXHR, textStatus, errorThrown, options); - }).always(function (jqXHRorResult, textStatus, jqXHRorError) { - that._sending -= 1; - that._onAlways( - jqXHRorResult, - textStatus, - jqXHRorError, - options - ); - if (options.limitConcurrentUploads && - options.limitConcurrentUploads > that._sending) { - // Start the next queued upload, - // that has not been aborted: - var nextSlot = that._slots.shift(); - while (nextSlot) { - if (!nextSlot.isRejected()) { - nextSlot.resolve(); - break; - } - nextSlot = that._slots.shift(); - } - } - }); - return jqXHR; - }; - this._beforeSend(e, options); - if (this.options.sequentialUploads || - (this.options.limitConcurrentUploads && - this.options.limitConcurrentUploads <= this._sending)) { - if (this.options.limitConcurrentUploads > 1) { - slot = $.Deferred(); - this._slots.push(slot); - pipe = slot.pipe(send); - } else { - pipe = (this._sequence = this._sequence.pipe(send, send)); - } - // Return the piped Promise object, enhanced with an abort method, - // which is delegated to the jqXHR object of the current upload, - // and jqXHR callbacks mapped to the equivalent Promise methods: - pipe.abort = function () { - var args = [undefined, 'abort', 'abort']; - if (!jqXHR) { - if (slot) { - slot.rejectWith(args); - } - return send(false, args); - } - return jqXHR.abort(); - }; - return this._enhancePromise(pipe); - } - return send(); - }, - - _onAdd: function (e, data) { - var that = this, - result = true, - options = $.extend({}, this.options, data), - limit = options.limitMultiFileUploads, - paramName = this._getParamName(options), - paramNameSet, - paramNameSlice, - fileSet, - i; - if (!(options.singleFileUploads || limit) || - !this._isXHRUpload(options)) { - fileSet = [data.files]; - paramNameSet = [paramName]; - } else if (!options.singleFileUploads && limit) { - fileSet = []; - paramNameSet = []; - for (i = 0; i < data.files.length; i += limit) { - fileSet.push(data.files.slice(i, i + limit)); - paramNameSlice = paramName.slice(i, i + limit); - if (!paramNameSlice.length) { - paramNameSlice = paramName; - } - paramNameSet.push(paramNameSlice); - } - } else { - paramNameSet = paramName; - } - data.originalFiles = data.files; - $.each(fileSet || data.files, function (index, element) { - var newData = $.extend({}, data); - newData.files = fileSet ? element : [element]; - newData.paramName = paramNameSet[index]; - newData.submit = function () { - newData.jqXHR = this.jqXHR = - (that._trigger('submit', e, this) !== false) && - that._onSend(e, this); - return this.jqXHR; - }; - return (result = that._trigger('add', e, newData)); - }); - return result; - }, - - // File Normalization for Gecko 1.9.1 (Firefox 3.5) support: - _normalizeFile: function (index, file) { - if (file.name === undefined && file.size === undefined) { - file.name = file.fileName; - file.size = file.fileSize; - } - }, - - _replaceFileInput: function (input) { - var inputClone = input.clone(true); - $('
    ').append(inputClone)[0].reset(); - // Detaching allows to insert the fileInput on another form - // without loosing the file input value: - input.after(inputClone).detach(); - // Avoid memory leaks with the detached file input: - $.cleanData(input.unbind('remove')); - // Replace the original file input element in the fileInput - // collection with the clone, which has been copied including - // event handlers: - this.options.fileInput = this.options.fileInput.map(function (i, el) { - if (el === input[0]) { - return inputClone[0]; - } - return el; - }); - // If the widget has been initialized on the file input itself, - // override this.element with the file input clone: - if (input[0] === this.element[0]) { - this.element = inputClone; - } - }, - - _getFileInputFiles: function (fileInput) { - fileInput = $(fileInput); - var files = $.each($.makeArray(fileInput.prop('files')), this._normalizeFile), - value; - if (!files.length) { - value = fileInput.prop('value'); - if (!value) { - return []; - } - // If the files property is not available, the browser does not - // support the File API and we add a pseudo File object with - // the input value as name with path information removed: - files = [{name: value.replace(/^.*\\/, '')}]; - } - return files; - }, - - _onChange: function (e) { - var that = e.data.fileupload, - data = { - fileInput: $(e.target), - form: $(e.target.form) - }; - data.files = that._getFileInputFiles(data.fileInput); - if (that.options.replaceFileInput) { - that._replaceFileInput(data.fileInput); - } - if (that._trigger('change', e, data) === false || - that._onAdd(e, data) === false) { - return false; - } - }, - - _onPaste: function (e) { - var that = e.data.fileupload, - cbd = e.originalEvent.clipboardData, - items = (cbd && cbd.items) || [], - data = {files: []}; - $.each(items, function (index, item) { - var file = item.getAsFile && item.getAsFile(); - if (file) { - data.files.push(file); - } - }); - if (that._trigger('paste', e, data) === false || - that._onAdd(e, data) === false) { - return false; - } - }, - - _onDrop: function (e) { - var that = e.data.fileupload, - dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer, - data = { - files: $.each( - $.makeArray(dataTransfer && dataTransfer.files), - that._normalizeFile - ) - }; - if (that._trigger('drop', e, data) === false || - that._onAdd(e, data) === false) { - return false; - } - e.preventDefault(); - }, - - _onDragOver: function (e) { - var that = e.data.fileupload, - dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer; - if (that._trigger('dragover', e) === false) { - return false; - } - if (dataTransfer) { - dataTransfer.dropEffect = 'copy'; - } - e.preventDefault(); - }, - - _initEventHandlers: function () { - var ns = this.options.namespace; - if (this._isXHRUpload(this.options)) { - this.options.dropZone - .bind('dragover.' + ns, {fileupload: this}, this._onDragOver) - .bind('drop.' + ns, {fileupload: this}, this._onDrop) - .bind('paste.' + ns, {fileupload: this}, this._onPaste); - } - this.options.fileInput - .bind('change.' + ns, {fileupload: this}, this._onChange); - }, - - _destroyEventHandlers: function () { - var ns = this.options.namespace; - this.options.dropZone - .unbind('dragover.' + ns, this._onDragOver) - .unbind('drop.' + ns, this._onDrop) - .unbind('paste.' + ns, this._onPaste); - this.options.fileInput - .unbind('change.' + ns, this._onChange); - }, - - _setOption: function (key, value) { - var refresh = $.inArray(key, this._refreshOptionsList) !== -1; - if (refresh) { - this._destroyEventHandlers(); - } - $.Widget.prototype._setOption.call(this, key, value); - if (refresh) { - this._initSpecialOptions(); - this._initEventHandlers(); - } - }, - - _initSpecialOptions: function () { - var options = this.options; - if (options.fileInput === undefined) { - options.fileInput = this.element.is('input:file') ? - this.element : this.element.find('input:file'); - } else if (!(options.fileInput instanceof $)) { - options.fileInput = $(options.fileInput); - } - if (!(options.dropZone instanceof $)) { - options.dropZone = $(options.dropZone); - } - }, - - _create: function () { - var options = this.options; - // Initialize options set via HTML5 data-attributes: - $.extend(options, $(this.element[0].cloneNode(false)).data()); - options.namespace = options.namespace || this.widgetName; - this._initSpecialOptions(); - this._slots = []; - this._sequence = this._getXHRPromise(true); - this._sending = this._active = this._loaded = this._total = 0; - this._initEventHandlers(); - }, - - destroy: function () { - this._destroyEventHandlers(); - $.Widget.prototype.destroy.call(this); - }, - - enable: function () { - $.Widget.prototype.enable.call(this); - this._initEventHandlers(); - }, - - disable: function () { - this._destroyEventHandlers(); - $.Widget.prototype.disable.call(this); - }, - - // This method is exposed to the widget API and allows adding files - // using the fileupload API. The data parameter accepts an object which - // must have a files property and can contain additional options: - // .fileupload('add', {files: filesList}); - add: function (data) { - if (!data || this.options.disabled) { - return; - } - if (data.fileInput && !data.files) { - data.files = this._getFileInputFiles(data.fileInput); - } else { - data.files = $.each($.makeArray(data.files), this._normalizeFile); - } - this._onAdd(null, data); - }, - - // This method is exposed to the widget API and allows sending files - // using the fileupload API. The data parameter accepts an object which - // must have a files property and can contain additional options: - // .fileupload('send', {files: filesList}); - // The method returns a Promise object for the file upload call. - send: function (data) { - if (data && !this.options.disabled) { - if (data.fileInput && !data.files) { - data.files = this._getFileInputFiles(data.fileInput); - } else { - data.files = $.each($.makeArray(data.files), this._normalizeFile); - } - if (data.files.length) { - return this._onSend(null, data); - } - } - return this._getXHRPromise(false, data && data.context); - } - - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/jquery.iframe-transport.js b/htdocs/includes/jquery/plugins/fileupload/js/jquery.iframe-transport.js deleted file mode 100644 index 04a56623085..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/jquery.iframe-transport.js +++ /dev/null @@ -1,171 +0,0 @@ -/* - * jQuery Iframe Transport Plugin 1.4 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint unparam: true, nomen: true */ -/*global define, window, document */ - -(function (factory) { - 'use strict'; - if (typeof define === 'function' && define.amd) { - // Register as an anonymous AMD module: - define(['jquery'], factory); - } else { - // Browser globals: - factory(window.jQuery); - } -}(function ($) { - 'use strict'; - - // Helper variable to create unique names for the transport iframes: - var counter = 0; - - // The iframe transport accepts three additional options: - // options.fileInput: a jQuery collection of file input fields - // options.paramName: the parameter name for the file form data, - // overrides the name property of the file input field(s), - // can be a string or an array of strings. - // options.formData: an array of objects with name and value properties, - // equivalent to the return data of .serializeArray(), e.g.: - // [{name: 'a', value: 1}, {name: 'b', value: 2}] - $.ajaxTransport('iframe', function (options) { - if (options.async && (options.type === 'POST' || options.type === 'GET')) { - var form, - iframe; - return { - send: function (_, completeCallback) { - form = $('
    '); - // javascript:false as initial iframe src - // prevents warning popups on HTTPS in IE6. - // IE versions below IE8 cannot set the name property of - // elements that have already been added to the DOM, - // so we set the name along with the iframe HTML markup: - iframe = $( - '' - ).bind('load', function () { - var fileInputClones, - paramNames = $.isArray(options.paramName) ? - options.paramName : [options.paramName]; - iframe - .unbind('load') - .bind('load', function () { - var response; - // Wrap in a try/catch block to catch exceptions thrown - // when trying to access cross-domain iframe contents: - try { - response = iframe.contents(); - // Google Chrome and Firefox do not throw an - // exception when calling iframe.contents() on - // cross-domain requests, so we unify the response: - if (!response.length || !response[0].firstChild) { - throw new Error(); - } - } catch (e) { - response = undefined; - } - // The complete callback returns the - // iframe content document as response object: - completeCallback( - 200, - 'success', - {'iframe': response} - ); - // Fix for IE endless progress bar activity bug - // (happens on form submits to iframe targets): - $('') - .appendTo(form); - form.remove(); - }); - form - .prop('target', iframe.prop('name')) - .prop('action', options.url) - .prop('method', options.type); - if (options.formData) { - $.each(options.formData, function (index, field) { - $('') - .prop('name', field.name) - .val(field.value) - .appendTo(form); - }); - } - if (options.fileInput && options.fileInput.length && - options.type === 'POST') { - fileInputClones = options.fileInput.clone(); - // Insert a clone for each file input field: - options.fileInput.after(function (index) { - return fileInputClones[index]; - }); - if (options.paramName) { - options.fileInput.each(function (index) { - $(this).prop( - 'name', - paramNames[index] || options.paramName - ); - }); - } - // Appending the file input fields to the hidden form - // removes them from their original location: - form - .append(options.fileInput) - .prop('enctype', 'multipart/form-data') - // enctype must be set as encoding for IE: - .prop('encoding', 'multipart/form-data'); - } - form.submit(); - // Insert the file input fields at their original location - // by replacing the clones with the originals: - if (fileInputClones && fileInputClones.length) { - options.fileInput.each(function (index, input) { - var clone = $(fileInputClones[index]); - $(input).prop('name', clone.prop('name')); - clone.replaceWith(input); - }); - } - }); - form.append(iframe).appendTo(document.body); - }, - abort: function () { - if (iframe) { - // javascript:false as iframe src aborts the request - // and prevents warning popups on HTTPS in IE6. - // concat is used to avoid the "Script URL" JSLint error: - iframe - .unbind('load') - .prop('src', 'javascript'.concat(':false;')); - } - if (form) { - form.remove(); - } - } - }; - } - }); - - // The iframe transport returns the iframe content document as response. - // The following adds converters from iframe to text, json, html, and script: - $.ajaxSetup({ - converters: { - 'iframe text': function (iframe) { - return $(iframe[0].body).text(); - }, - 'iframe json': function (iframe) { - return $.parseJSON($(iframe[0].body).text()); - }, - 'iframe html': function (iframe) { - return $(iframe[0].body).html(); - }, - 'iframe script': function (iframe) { - return $.globalEval($(iframe[0].body).text()); - } - } - }); - -})); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/locale.js b/htdocs/includes/jquery/plugins/fileupload/js/locale.js deleted file mode 100644 index ea64b0a870f..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/locale.js +++ /dev/null @@ -1,29 +0,0 @@ -/* - * jQuery File Upload Plugin Localization Example 6.5.1 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2012, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*global window */ - -window.locale = { - "fileupload": { - "errors": { - "maxFileSize": "File is too big", - "minFileSize": "File is too small", - "acceptFileTypes": "Filetype not allowed", - "maxNumberOfFiles": "Max number of files exceeded", - "uploadedBytes": "Uploaded bytes exceed file size", - "emptyResult": "Empty file upload result" - }, - "error": "Error", - "start": "Start", - "cancel": "Cancel", - "destroy": "Delete" - } -}; diff --git a/htdocs/includes/jquery/plugins/fileupload/js/main.js b/htdocs/includes/jquery/plugins/fileupload/js/main.js deleted file mode 100644 index 67109588de3..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/main.js +++ /dev/null @@ -1,93 +0,0 @@ -/* - * jQuery File Upload Plugin JS Example 6.7 - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2010, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ - -/*jslint nomen: true, unparam: true, regexp: true */ -/*global $, window, document */ - -$(function () { - 'use strict'; - - // Initialize the jQuery File Upload widget: - $('#fileupload').fileupload(); - - // Enable iframe cross-domain access via redirect option: - $('#fileupload').fileupload( - 'option', - 'redirect', - window.location.href.replace( - /\/[^\/]*$/, - '/cors/result.html?%s' - ) - ); - - if (window.location.hostname === 'blueimp.github.com') { - // Demo settings: - $('#fileupload').fileupload('option', { - url: '//jquery-file-upload.appspot.com/', - maxFileSize: 5000000, - acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, - process: [ - { - action: 'load', - fileTypes: /^image\/(gif|jpeg|png)$/, - maxFileSize: 20000000 // 20MB - }, - { - action: 'resize', - maxWidth: 1440, - maxHeight: 900 - }, - { - action: 'save' - } - ] - }); - // Upload server status check for browsers with CORS support: - if ($.support.cors) { - $.ajax({ - url: '//jquery-file-upload.appspot.com/', - type: 'HEAD' - }).fail(function () { - $('') - .text('Upload server currently unavailable - ' + - new Date()) - .appendTo('#fileupload'); - }); - } - } else { - // Load existing files: - $('#fileupload').each(function () { - var that = this; - $.getJSON(this.action, function (result) { - if (result && result.length) { - $(that).fileupload('option', 'done') - .call(that, null, {result: result}); - } - }); - }); - } - - // Initialize the Image Gallery widget: - $('#fileupload .files').imagegallery(); - - // Initialize the theme switcher: - $('#theme-switcher').change(function () { - var theme = $('#theme'); - theme.prop( - 'href', - theme.prop('href').replace( - /[\w\-]+\/jquery-ui.css/, - $(this).val() + '/jquery-ui.css' - ) - ); - }); - -}); diff --git a/htdocs/includes/jquery/plugins/fileupload/js/vendor/jquery.ui.widget.js b/htdocs/includes/jquery/plugins/fileupload/js/vendor/jquery.ui.widget.js deleted file mode 100644 index 9da8673a58b..00000000000 --- a/htdocs/includes/jquery/plugins/fileupload/js/vendor/jquery.ui.widget.js +++ /dev/null @@ -1,282 +0,0 @@ -/* - * jQuery UI Widget 1.8.18+amd - * https://github.com/blueimp/jQuery-File-Upload - * - * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * http://docs.jquery.com/UI/Widget - */ - -(function (factory) { - if (typeof define === "function" && define.amd) { - // Register as an anonymous AMD module: - define(["jquery"], factory); - } else { - // Browser globals: - factory(jQuery); - } -}(function( $, undefined ) { - -// jQuery 1.4+ -if ( $.cleanData ) { - var _cleanData = $.cleanData; - $.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); - }; -} else { - var _remove = $.fn.remove; - $.fn.remove = function( selector, keepData ) { - return this.each(function() { - if ( !keepData ) { - if ( !selector || $.filter( selector, [ this ] ).length ) { - $( "*", this ).add( [ this ] ).each(function() { - try { - $( this ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - }); - } - } - return _remove.call( $(this), selector, keepData ); - }); - }; -} - -$.widget = function( name, base, prototype ) { - var namespace = name.split( "." )[ 0 ], - fullName; - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName ] = function( elem ) { - return !!$.data( elem, name ); - }; - - $[ namespace ] = $[ namespace ] || {}; - $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - - var basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from -// $.each( basePrototype, function( key, val ) { -// if ( $.isPlainObject(val) ) { -// basePrototype[ key ] = $.extend( {}, val ); -// } -// }); - basePrototype.options = $.extend( true, {}, basePrototype.options ); - $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { - namespace: namespace, - widgetName: name, - widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, - widgetBaseClass: fullName - }, prototype ); - - $.widget.bridge( name, $[ namespace ][ name ] ); -}; - -$.widget.bridge = function( name, object ) { - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = Array.prototype.slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.extend.apply( null, [ true, options ].concat(args) ) : - options; - - // prevent calls to internal methods - if ( isMethodCall && options.charAt( 0 ) === "_" ) { - return returnValue; - } - - if ( isMethodCall ) { - this.each(function() { - var instance = $.data( this, name ), - methodValue = instance && $.isFunction( instance[options] ) ? - instance[ options ].apply( instance, args ) : - instance; - // TODO: add this back in 1.9 and use $.error() (see #5972) -// if ( !instance ) { -// throw "cannot call methods on " + name + " prior to initialization; " + -// "attempted to call method '" + options + "'"; -// } -// if ( !$.isFunction( instance[options] ) ) { -// throw "no such method '" + options + "' for " + name + " widget instance"; -// } -// var methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, name ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, name, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( options, element ) { - // allow instantiation without initializing for simple inheritance - if ( arguments.length ) { - this._createWidget( options, element ); - } -}; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - options: { - disabled: false - }, - _createWidget: function( options, element ) { - // $.widget.bridge stores the plugin instance, but we do it anyway - // so that it's stored even before the _create function runs - $.data( element, this.widgetName, this ); - this.element = $( element ); - this.options = $.extend( true, {}, - this.options, - this._getCreateOptions(), - options ); - - var self = this; - this.element.bind( "remove." + this.widgetName, function() { - self.destroy(); - }); - - this._create(); - this._trigger( "create" ); - this._init(); - }, - _getCreateOptions: function() { - return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; - }, - _create: function() {}, - _init: function() {}, - - destroy: function() { - this.element - .unbind( "." + this.widgetName ) - .removeData( this.widgetName ); - this.widget() - .unbind( "." + this.widgetName ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetBaseClass + "-disabled " + - "ui-state-disabled" ); - }, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.extend( {}, this.options ); - } - - if (typeof key === "string" ) { - if ( value === undefined ) { - return this.options[ key ]; - } - options = {}; - options[ key ] = value; - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var self = this; - $.each( options, function( key, value ) { - self._setOption( key, value ); - }); - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - [ value ? "addClass" : "removeClass"]( - this.widgetBaseClass + "-disabled" + " " + - "ui-state-disabled" ) - .attr( "aria-disabled", value ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - - return !( $.isFunction(callback) && - callback.call( this.element[0], event, data ) === false || - event.isDefaultPrevented() ); - } -}; - -})); diff --git a/htdocs/includes/jquery/plugins/select2/.gitignore b/htdocs/includes/jquery/plugins/select2/.gitignore deleted file mode 100644 index c6ef2182bdc..00000000000 --- a/htdocs/includes/jquery/plugins/select2/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.idea - diff --git a/htdocs/includes/jquery/plugins/select2/CHANGELOG.md b/htdocs/includes/jquery/plugins/select2/CHANGELOG.md new file mode 100644 index 00000000000..3ae60aff255 --- /dev/null +++ b/htdocs/includes/jquery/plugins/select2/CHANGELOG.md @@ -0,0 +1,254 @@ +# Change Log + +## 4.0.4 + +### New features / Improvements +- Make tag matching case insensitive [https://github.com/select2/select2/commit/cb9a90457867ffb14c7b1550bb67e872e0a5c2dd, https://github.com/select2/select2/commit/1167bace78cd3b1a918c1b04f3bac54674eab62b] +- Support selecting options with blank or `0` option values [https://github.com/select2/select2/commit/16b4840c0e2df0461998e3b464ee0a546173950d, https://github.com/select2/select2/commit/0358ee528765157234643d289bce6b8ca5889c72] + +### Bug fixes +- Fix issue with entire form losing focus when tabbing away from a Select2 control (#4419) +- Fix UMD support for CommonJS [https://github.com/select2/select2/commit/45a877345482956021161203ac789c25f40a7d5e] + +### Documentation +- Github Pages documentation has been deprecated, replaced with https://github.com/select2/docs +- Add django-autocomplete-light to integrations [https://github.com/select2/select2/pull/4597] +- Correct typo in options page [https://github.com/select2/select2/pull/4389] +- Correct misspelling in AJAX query parameters example [https://github.com/select2/select2/pull/4435] +- "highlight" should be "focus" in focus example [https://github.com/select2/select2/pull/4441] +- Correct misspelling in `` is now handled [https://github.com/select2/select2/commit/31e7a1d4c52ed7477769fcad5d15166ae3c9b4d0] +- Adding and removing options now refreshes the selection automatically [https://github.com/select2/select2/commit/ea79a197e0ffe55aa600eed6d18cbd1c804c3176] + +### Bug fixes +- `select2('option')` no longer mutate the arguments when working on multiple elements [https://github.com/select2/select2/commit/c2c1aeef31c95c6df5545c900a4e1782d712497c] +- Better detect aborted requests [https://github.com/select2/select2/commit/cfb66f5e4f71a56c46a6890c5dde4b7f24f11fa8] +- New options are now properly created during tokenization [https://github.com/select2/select2/commit/3b8cd2e36990e695e4cb4b966c8658e7ca1574dc] +- Fix positioning bug with non-static parents for the dropdown [https://github.com/select2/select2/pull/4267] +- Infinite scrolling no longer resets the keyboard focus [https://github.com/select2/select2/commit/e897d008a672da262ba84cee2a144578696ada29, https://github.com/select2/select2/commit/9f581285d88128b29a01fc1e5fd2d445d610b553] +- `selectOnClose` now works properly with `closeOnSelect` [https://github.com/select2/select2/commit/481c43883e23874e9c35879d173eb8cc5b994b12] +- Apply `ajax.delay` to empty search terms as well [https://github.com/select2/select2/commit/4b9e02f02211248be25ac4c16d4635cf38237bb9] + +### Documentation +- Added example for attaching event listeners [https://github.com/select2/select2/commit/84d6b5d840f7f4e6b7a2fb3f08424bf5495c876d] +- Correct link to the [Select2 Bootstrap Theme](https://github.com/select2/select2-bootstrap-theme) [https://github.com/select2/select2/pull/4318] +- Added example for using a `