diff --git a/.travis.yml b/.travis.yml index 8e1aa2aa10b..718356e8075 100644 --- a/.travis.yml +++ b/.travis.yml @@ -257,7 +257,7 @@ script: # Ensure we catch errors set -e # Exclusions are defined in the ruleset.xml file - phpcs -s -n -p -d memory_limit=-1 --colors --tab-width=4 --standard=dev/codesniffer/ruleset.xml --encoding=utf-8 . + phpcs -s -n -p -d memory_limit=-1 --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 . set +e echo diff --git a/COPYRIGHT b/COPYRIGHT index 1daa86d3f38..4fbff121147 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -38,7 +38,6 @@ jQuery UI 1.11.4 GPL and MIT License Yes jQuery select2 3.5.2 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 DataTables 1.9.4 BSD Yes JS library for tables output 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) diff --git a/ChangeLog b/ChangeLog index f4b13d1e3ed..7f210c6fab1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -22,13 +22,86 @@ WARNING: Following changes may create regression for some external modules, but were necessary to make Dolibarr better: - Function delete of class Facture (invoice) need the object $user as first parameter. Also you must -check you make a fetch on object before calling the delete. + check you make a fetch on object before calling the delete. - The old driver of "mysql" has been removed. Dolibarr use the new one (mysqli) by default. - Remove not used function calculate_byte(). Use dol_print_size() instead. - Function pdf_getTotalQty is now deprecated. Not used by Dolibarr core. +- Method expensereport->delete(id, user) has been replaced with ->delete(user) + Method warehouse->delete(id) has been replace with ->delete(user) + This is to follow good practice to make a fetch on object before deleting it. +- The form to add a product to a draft proposal/order/invoice from the product card is hidden by default. + It was not commonly used and usage generates some problems (cost price for margin calculation not entered, vat setting). + Set constant PRODUCT_ADD_FORM_ADD_TO to retrieve it. +- The javascript "datatables" library was used to be provided into Dolibarr sources, but it was not used by application. + So there is no reason to maintain its compatibility with other dolibarr components. If an external module need this + library, this external module must embed hte library in his own sources/packages. +- Trigger name SUPPLIER_PROPOSAL_CREATE has been renamed into PROPOSAL_SUPPLIER_CREATE +- A new paramater sqlfilters was introduced to allow filter on any fields int the REST API. Few old parameters + no more required were also removed. Use this new one if you ware using one of them. +- Method commande->deleteline($lindeid) has been replaced with commande->deleteline($user, $lineid). +***** ChangeLog for 4.0.2 compared to 4.0.1 ***** +FIX: #5340 +FIX: #5779 +FIX: #5849 +FIX: #5866 +FIX: #5907 +FIX: Addline if $txlocaltax1 is empty +FIX: Avoid error 500 if phpexcel is disabled +FIX: Avoid errors on debian +FIX: Can edit the customer ref even if order is not draft. +FIX: Documents not moved in new directory if we change reference of the task. +FIX: Error when CATEGORIE_RECURSIV_ADD is enabled and new category is child of an already linked to object +FIX: Extra fields of task not copied on project cloning +FIX: Hidden option PRODUCT_MAX_VISIBLE_PHOTO +FIX: Link on supplier invoice in widget was not clickable +FIX: margin tab on customer card must filter on current entity invoices +FIX: missing column into SQL on thirdparty list +FIX: Nber of attached files were not reported in event report of email sent +FIX: only show projects of related third if external user +FIX: Search provider by price +FIX: Solve backup when using mysqldump that return warning +FIX: Sql error in widget of product for stock alerts +FIX: updateligne if $txlocaltax1 is null + +***** ChangeLog for 4.0.1 compared to 4.0.0 ***** +FIX: #2853 +FIX: #2991 +FIX: #3128 +FIX: #5699 +FIX: #5734 +FIX: #5742 error on project list if an extra field separator is added. +FIX: #5746 chrome php Try a fix. Not sure it solved all problems reported +FIX: #5748 Bug: Error updating to 4.0.1 with Postgresql. Field must be varchar. +FIX: #5750 Bug: CmailFile::server_parse enters an infinite loop if $server_response is false +FIX: #5752 Bug VAT NPR not propagated during proposal cloning +FIX: #5763 Bug: Cannot Create Supplier Price Request +FIX: #5770 Dolibarr doesn't modify correctly the hour of a task +FIX: #5776 +FIX: #5802 Incoterms not set +FIX: #5813 Bug: Incoterms not being read correctly +FIX: #5818 +FIX: alignement of intervention status +FIX: Clean of search fields +FIX: Creation of donation should go back on card after creation +FIX: Date visible on project overview +FIX: Execute a dedicated job from its id may results of launching other jobs too. +FIX: Failed to export contact categories with contact extra fields +FIX: inversion customer/supplier price +FIX: link "back to list" was not visible. +FIX: Lost filter on opportunities +FIX: Mandatory field payment term was not css highlighted. +FIX: Menu users not visible on dolidroid. +FIX: SEC for HTB23302 +FIX: The email test sender in email setup was broken +FIX: Translation of "Name" is not a good choice for floow-up. +FIX: Update of maxnbrun on job list failed. +FIX: Value of payment term and project are not set on correct default value when invoice generated from template. +FIX: vat dictionary should allow enter and edit multiple values for localtaxes, separated by: (ex -19:-15) +FIX: Vat not visible in dictionnary + ***** ChangeLog for 4.0.0 compared to 3.9.* ***** For users: NEW: Add recurring invoice feature and automatic generation of invoices. diff --git a/Dockerfile b/Dockerfile index 982cc29fc34..00a5d0ef567 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,7 +3,7 @@ FROM php:5.6-apache RUN apt-get update && apt-get install -y libpng12-dev libjpeg-dev libldap2-dev \ && rm -rf /var/lib/apt/lists/* \ && docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr \ - && docker-php-ext-install gd + && docker-php-ext-install gd \ && docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ \ && docker-php-ext-install ldap \ && docker-php-ext-install mysqli \ diff --git a/README.md b/README.md index 64579486985..dddf387cab9 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ These are features that Dolibarr does **not** yet fully support: ## DOCUMENTATION -Administrator, user, developer and translator's documentations are available along with other community resources on the [Wiki](http://wiki.dolibarr.org). +Administrator, user, developer and translator's documentations are available along with other community resources on the [Wiki](https://wiki.dolibarr.org). ## CONTRIBUTING diff --git a/build/README-FR b/build/README-FR deleted file mode 100644 index b677e545595..00000000000 --- a/build/README-FR +++ /dev/null @@ -1,78 +0,0 @@ -README (French) -################################ -Building packages -################################ - -Les sous repertoires du repertoire "build" contiennent tous les fichiers -requis pour packager Dolibarr de maniere automatisee. -On trouve plusieurs outils: - -- Pour construire un package Dolibarr complet, il suffit de -> Editer la version dans le fichier makepack-dolibarr.pl -> Lancer la commande perl makepack-dolibarr.pl - -- Pour construire un package d'une traduction, il suffit de lancer le script -> perl makepack-dolibarrlang.pl - -- Pour construire un package d'un theme, il suffit de lancer le script -> perl makepack-dolibarrtheme.pl - -- Pour construire un package d'un module, il suffit de lancer le script -> perl makepack-dolibarrmodule.pl - -- Pour construire un package DoliWamp autoexe: -> Installer InnoSetup (http://www.jrsoftware.org) -> Installer WampServer dans "C:\Program Files\Wamp" (http://www.wampserver.com) -> Installer les addon WampServer afin d'y mettre les versions: - Apache2.2.6, Mysql5.0.45, Php5.2.5 -> Modifier dans le fichier build/exe/doliwamp.iss la variable SourceDir - afin d'y mettre le repository Dolibarr. -> Modifier AppVerName et OutputBaseFilename. -> Lancer innosetup, ouvrir le fichier build/exe/doliwamp.iss et cliquer sur - le bouton "Compile". Le fichier .exe sera fabrique dans le repertoire build. - -- Pour generer la documentation developpeur, lancer le script -> perl dolybarr-doxygen-build.pl - - -Note: - -Le repertoire build et tout ce qu'il contient n'est absolument pas requis -pour faire fonctionner Dolibarr. Ils ne servent qu'a la generation des -packages. Certains packages, une fois construit, n'incluent par le repertoire -"build". - -On trouve dans le repertoire "build", les sous-repertoires utilises par -l'outil makepack-dolibarr.pl: - -* deb: -Fichier de config pour construire un package Debian. - -* rpm: -Fichier de config pour construire un package Redhat ou Mandrake. - -* tgz: -Fichier de config pour construire un package tgz. - -* exe: -Fichier de config pour construire un package exe pour Windows des sources -ou pour construire l'assistant d'installation complet DoliWamp. - -* zip: -Fichier de config pour construire un package zip. - -* live: -Fichier pour fabriquer un live CD de demo de Dolibarr. - -* patch: -Fichier exemple de generation de fichier patch pour diffusion d'une -modification de Dolibarr. - -* doap: -Fichier descriptif DOAP pour promouvoir/decrire la version de Dolibarr. - -* pad: -Fichier descriptif PAD pour promouvoir/decrire la version de Dolibarr. - -* dmg: -Fichier de config pour construire un package dmg DoliMamp pour Mac OS X diff --git a/build/debian/README.howto b/build/debian/README.howto index 6f57894a960..cd7cd93c24e 100644 --- a/build/debian/README.howto +++ b/build/debian/README.howto @@ -154,8 +154,10 @@ tag 729538 -moreinfo ##### Testing a package into unstable env Check you have a mysql server available from another interface than "localhost". -Comment line in /etc/mysql/my.cnf if required and restart mysql -#bind-address = 127.0.0.1 +Set line in /etc/mysql/my.cnf if required and restart mysql + +[mysqld] +bind-address = * Create a chroot called "unstable-amd64-sbuild". Chroot env is stored into /srv/chroot directory. @@ -170,6 +172,8 @@ Puis pour se connecter et préparer l'environnement > schroot -c name_of_chroot > cat /etc/debian_chroot to check which debian branch we are into > vi /usr/sbin/policy-rc.d and replace return code 101 (not allowed) into 0 (ok) +> apt-get update +> apt-get upgrade > apt-get install links mysql-client To test a package @@ -185,7 +189,7 @@ To test a package If there is a problem launching apache, because port is already used, change it into your chroot install with > vi /etc/apache2/ports.conf Then restart. -Then you can call/test dolibarr with http://localhost:port/dolibarr/ (It can be also called from host). +Then you can call/test dolibarr with http://localhost:port/dolibarr/ . It can be also called FROM HOST (port must be a not used port on host). @@ -291,13 +295,18 @@ If script fails with error Bad certificate, you can set "export PERL_LWP_SSL_VER * Edit orig.tar.gz file to remove - debian - htdocs/includes/ckeditor +- htdocs/includes/jszip +- htdocs/includes/jquery/plugins/datatables +- htdocs/includes/mike42 - htdocs/includes/phpexcel or htdocs/includes/phpoffice -- htdocs/includes/tcpdf or htdocs/includes/tecnickom +- htdocs/includes/swiftmailer +- htdocs/includes/restler/framework/Luracast/Restler/explorer +- htdocs/includes/tcpdf or htdocs/includes/tecnickcom And rename file into dolibarr-x.y.z+dfsgw.tgz (x.y.z = version, w start from 1 and is increased for each new git-import-orig already done) -* Staying into git root directory, run +* Staying into projet gitted root directory, run > git-import-orig -vv ../dolibarr-x.y.z+dfsgw.tgz --debian-branch=[master|jessie] --upstream-branch=[upstream|upstream-3.5.x] and enter version when requested with format x.y.z+dfsgw @@ -324,7 +333,7 @@ To update dolibarr debian package when only files into debian has changed: To update dolibarr debian package when only files not into debian has changed: * Manually, add patches into debian/patches and update file debian/series, or do the 2 steps with "quilt import filepatch.patch" -* You can test patching of serie with "quilt push" (autant de fois que de patch). Avec "quilt pop -a", on revien a l'état du upstream sans les patch. +* You can test patching of serie with "quilt push" (autant de fois que de patch). Avec "quilt pop -a", on revient a l'état du upstream sans les patch. Once files has been prepared, it's time to test: @@ -341,7 +350,7 @@ Note: Package is built into directory ../build-area Note: To compare 2 packages: debdiff package1.dsc package2.dsc * Test package (see dedicated chapter to test it with debian unstable env) -> cp ../build-area/* /srv/chroot/unstable/tmp +> sudo rm /srv/chroot/unstable/tmp/* >/dev/null 2>&1; cp ../build-area/* /srv/chroot/unstable/tmp See rest of process into dedicated chapter "To test a package" to test it with debian unstable env * If package .deb is ok: diff --git a/build/debian/control b/build/debian/control index d5c4a913713..37689ef9bcc 100755 --- a/build/debian/control +++ b/build/debian/control @@ -16,7 +16,7 @@ Depends: libapache2-mod-php5 | libapache2-mod-php5filter | php5-cgi | php5-fpm | php5-mysql | php5-mysqli, php5-curl, php5-gd, php5-ldap, # Required PHP libraries php-pear, php-mail-mime, -# php-tcpdf, libfpdi-php, +# php-tcpdf, # libfpdf-tpl-php, php-fpdf, # libphp-adodb, # libnusoap-php, diff --git a/build/debian/copyright b/build/debian/copyright index e568996551e..8207df4b6d7 100644 --- a/build/debian/copyright +++ b/build/debian/copyright @@ -1,7 +1,7 @@ Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: Dolibarr Upstream-Contact: Laurent Destailleur -Source: http://www.dolibarr.org/files/stable/standard/ +Source: https://www.dolibarr.org/files/stable/standard/ Files: * Copyright: 2002-2009, Rodolphe Quiedeville @@ -197,9 +197,6 @@ License: GPL-2+ On Debian systems, the full text of the GNU General Public License version 2 can be found in the file `/usr/share/common-licenses/GPL-2'. -Comment: - Those files are not shipped in the binary package as we - configure Dolibarr to use the library packaged in "libfpdi-php". Files: htdocs/includes/geoip/* Copyright: 2007 MaxMind LLC diff --git a/build/debian/dolibarr.postinst b/build/debian/dolibarr.postinst index 5f61ffe2083..4b946fda433 100644 --- a/build/debian/dolibarr.postinst +++ b/build/debian/dolibarr.postinst @@ -147,7 +147,6 @@ case "$1" in # File already exist. We add params not found. #echo Add new params to overwrite path to use shared libraries/fonts #grep -q -c "dolibarr_lib_ADODB_PATH" $config || [ ! -d "/usr/share/php/adodb" ] || echo "" >> $config - #grep -q -c "dolibarr_lib_FPDI_PATH" $config || [ ! -d "/usr/share/php/fpdi" ] || echo "" >> $config ##grep -q -c "dolibarr_lib_GEOIP_PATH" $config || echo "" >> $config #grep -q -c "dolibarr_lib_NUSOAP_PATH" $config || [ ! -d "/usr/share/php/nusoap" ] || echo "" >> $config #grep -q -c "dolibarr_lib_ODTPHP_PATHTOPCLZIP" $config || [ ! -d "/usr/share/php/libphp-pclzip" ] || echo "" >> $config diff --git a/build/debian/install.forced.php.install b/build/debian/install.forced.php.install index 57ab33464bc..56eef3287a6 100644 --- a/build/debian/install.forced.php.install +++ b/build/debian/install.forced.php.install @@ -30,8 +30,6 @@ $force_install_lockinstall='444'; // - not removed from package (see rm in rules file), // - declared into dependencies (see Depends in control file) //$force_dolibarr_lib_TCPDF_PATH=''; -//$force_dolibarr_lib_FPDF_PATH='/usr/share/php/fpdf'; -//$force_dolibarr_lib_FPDI_PATH='/usr/share/php/fpdi'; //$force_dolibarr_lib_ADODB_PATH='/usr/share/php/adodb'; //$force_dolibarr_lib_GEOIP_PATH=''; //$force_dolibarr_lib_NUSOAP_PATH='/usr/share/php/nusoap'; diff --git a/build/debian/rules b/build/debian/rules index bd3a9badb09..50866c03e68 100755 --- a/build/debian/rules +++ b/build/debian/rules @@ -79,7 +79,6 @@ override_dh_install: # clean from all PHP embedded libraries (we use package dependencies instead) # rm -fr htdocs/includes/adodbtime -# rm -fr htdocs/includes/fpdfi # rm -fr htdocs/includes/geoip # rm -fr htdocs/includes/nusoap # rm -fr htdocs/includes/odtphp/zip/pclzip diff --git a/build/generate_filecheck_xml.php b/build/generate_filelist_xml.php similarity index 85% rename from build/generate_filecheck_xml.php rename to build/generate_filelist_xml.php index 665bb3a65d1..1bc0e2b6620 100644 --- a/build/generate_filecheck_xml.php +++ b/build/generate_filelist_xml.php @@ -32,11 +32,33 @@ if (substr($sapi_type, 0, 3) == 'cgi') { exit; } +require_once($path."../htdocs/master.inc.php"); +require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"); -// Main + +/* + * Main + */ + +if (empty($argv[1])) +{ + print "Usage: ".$script_file." release=x.y.z\n"; + exit -1; +} parse_str($argv[1]); + +if ($release != DOL_VERSION) +{ + print 'Error: release is not version declared into filefunc.in.php.'."\n"; + exit -1; +} + //$outputfile=dirname(__FILE__).'/../htdocs/install/filelist-'.$release.'.xml'; -$outputfile=dirname(__FILE__).'/../htdocs/install/filelist.xml'; +$outputdir=dirname(__FILE__).'/../htdocs/install'; +print 'Delete current files '.$outputdir.'/filelist*.xml'."\n"; +dol_delete_file($outputdir.'/filelist*.xml',0,1,1); + +$outputfile=$outputdir.'/filelist-'.$release.'.xml'; $fp = fopen($outputfile,'w'); fputs($fp, ''."\n"); fputs($fp, ''."\n"); diff --git a/build/launchpad/README b/build/launchpad/README index 7ab1b15b81c..fc284e70b20 100644 --- a/build/launchpad/README +++ b/build/launchpad/README @@ -73,6 +73,8 @@ If you want to build/test package locally: bzr commit -m "Upstream version x.y" bzr push + + # Init debian dir repository into launchpad (when repository for sources does not exist) #---------------------------------- - Create debian directory and upload it onto bzr branch lp:~yourlogin/+junk/debian-[dev|stable] @@ -104,12 +106,13 @@ If you want to build/test package locally: bzr push lp:~yourlogin/+junk/debian-[dev|stable] + # Define a recipe into launchpad (a rule to build packages into a PPA) #---------------------------------- -- Create a file dolibarr.recipe with content +- Create a file dolibarr-[beta|stable].recipe with content cd bzr - vi dolibarr.recipe - For dev: + vi dolibarr-[beta|stable].recipe + For beta/dev: # bzr-builder format 0.3 deb-version {debupstream}-0~{revno} lp:dolibarr merge packaging lp:~yourlogin/+junk/debian-dev @@ -119,7 +122,7 @@ If you want to build/test package locally: merge packaging lp:~yourlogin/+junk/debian-stable - Run command cd bzr - bzr dailydeb dolibarr.recipe working-dir + bzr dailydeb dolibarr-[beta|stable].recipe working-dir This will create a directory "working-dir" with dolibarr sources and will add sources from ~yourlogin/+junk/debian-[dev|stable] - Test package sources sudo pbuilder build /_.dsc diff --git a/build/live/Howto.txt b/build/live/Howto.txt deleted file mode 100644 index 0715645e308..00000000000 --- a/build/live/Howto.txt +++ /dev/null @@ -1,74 +0,0 @@ -Howto (English) -################################################## -Building a live CD/USB -################################################## - -This is all steps to follow to build a live CD/USB demo of Dolibarr using -SLAX distribution. - -1) Download SLAX (www.slax.org) as a zip file. - -2) Unzip file on a directory on any USB key with at least 512Mo free (even -if you want to build a CD live). - -3) Download following modules from SLAX web sites and put files -into the /slax/modules directory: -apr-1.2.12-i486-1.lzm -apr-util-1.2.12-i486-1.lzm -cairomm-1.4.8-i686.lzm -cli-ftp-pack.lzm -codecs-essential-20071007.lzm -firefox-2.0.0.14.lzm -ghostscript-8.62-i486-5.lzm -gimp-2.4.5-i486-1sl.lzm -gparted-0.3.7-i486-1as.lzm -grsync.lzm -httpd-2.2.8-i486-1.lzm -libsigc++-2.0.18-i686.lzm -mysql-5.0.51b-i486-1.lzm -php-5.2.6-i486-1.lzm -printmodule-s6.lzm -Save_by_Pastrugno-0.1.lzm -telnet-1.5.lzm - -4) Copy dolibarr files into path -\slax\changes\var\www\htdocs\dolibarr - -5) Run the script -> /boot/bootinst.bat -or -> /boot/bootinst.sh -and answer yes to overwrite the MBR of the disk of your USB key. - -6) Boot on USB key (Change your BIOS setup if required). - -7) After boot, run the script -> mysql_install_db --user=mysql -This will create mysql empty system database. - -8) Edit the file /etc/httpd/httpd.conf to uncomment the line -with PHP activation. -Include /etc/httpd/mod_php.conf - -9) Edit \slax\changes\etc\httpd\php.ini file to disabled features where librairies does not -exists. You can comment lines: -;extension=gd.so -;extension=mhash.so -;extension=snmp.so - -10) Personalized your desktop. -Add a link to application -"firefox http://localhost/dolibarr/htdocs/index.php" -Add a link to application -"/var/www/htdocs/dolibarr/dev/initdemo/initdemo.sh" -Add a link to application -"/var/www/htdocs/dolibarr/dev/initdemo/removedemo.sh" - -11) Reboot again on your USB key. - -12) Now you can run Dolibarr install process -http://localhost/dolibarr/htdocs/install/index.php -or copy USB key content to build another one quickly. -or build a CD with command (TODO). - - diff --git a/build/live/README b/build/live/README deleted file mode 100644 index a279878d521..00000000000 --- a/build/live/README +++ /dev/null @@ -1,7 +0,0 @@ -README (English) -################################################## -Building a live CD/USB -################################################## - -This directory contains files and docs used to build -a live CD or USB demo of Dolibarr. \ No newline at end of file diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index ac735c59e0d..fb3b39feca3 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -159,6 +159,7 @@ $REL1 = $newbuild; $REL1 =~ s/-.*$//gi; if ($RPMSUBVERSION eq 'auto') { $RPMSUBVERSION = $newbuild; $RPMSUBVERSION =~ s/^.*-//gi; } $FILENAMETGZ2="$PROJECT-$MAJOR.$MINOR.$REL1"; $FILENAMERPM=$FILENAMETGZ2."-".$RPMSUBVERSION.".".$ARCH.".rpm"; +$FILENAMERPMSRC=$FILENAMETGZ2."-".$RPMSUBVERSION.".src.rpm"; # For Deb $newbuild = $BUILD; $newbuild =~ s/(dev|alpha)/1/gi; # dev @@ -317,8 +318,13 @@ print "\n"; if ($CHOOSEDTARGET{'-CHKSUM'}) { print 'Create xml check file with md5 checksum with command php '.$SOURCE.'/build/generate_filecheck_xml.php release='.$MAJOR.'.'.$MINOR.'.'.$BUILD."\n"; - $ret=`php $SOURCE/build/generate_filecheck_xml.php release=$MAJOR.$MINOR.$BUILD`; + $ret=`php $SOURCE/build/generate_filelist_xml.php release=$MAJOR.$MINOR.$BUILD`; print $ret."\n"; + # Copy to final dir + $NEWDESTI=$DESTI; + print "Copy \"$SOURCE/htdocs/install/filelist-$MAJOR.$MINOR.$BUILD.xml\" to $NEWDESTI/signatures/filelist-$MAJOR.$MINOR.$BUILD.xml\n"; + use File::Copy qw(copy); + copy "$SOURCE/htdocs/install/filelist-$MAJOR.$MINOR.$BUILD.xml", "$NEWDESTI/signatures/filelist-$MAJOR.$MINOR.$BUILD.xml"; } @@ -363,20 +369,23 @@ if ($nboftargetok) { if (! $ret) { print "Error: The ChangeLogFile was not updated. Run the following command before building package for $MAJOR.$MINOR.$BUILD:\n"; - if (! $BUILD || $BUILD eq '0-rc') # For a major version - { - print 'cd ~/git/dolibarr_'.$MAJOR.'.'.$MINOR.'; git log `git rev-list --boundary '.$MAJOR.'.'.$MINOR.'..origin/develop | grep ^- | cut -c2- | head -n 1`.. --no-merges --pretty=short --oneline | sed -e "s/^[0-9a-z]* //" | grep -e \'^FIX\|NEW\' | sort -u | sed \'s/FIXED:/FIX:/g\' | sed \'s/FIXED :/FIX:/g\' | sed \'s/FIX :/FIX:/g\' | sed \'s/FIX /FIX: /g\' | sed \'s/NEW :/NEW:/g\' | sed \'s/NEW /NEW: /g\' > /tmp/aaa'; - } - else # For a maintenance release - { - print 'cd ~/git/dolibarr_'.$MAJOR.'.'.$MINOR.'; git log '.$MAJOR.'.'.$MINOR.'.'.($BUILD-1).'.. --no-merges --pretty=short --oneline | sed -e "s/^[0-9a-z]* //" | grep -e \'^FIX\|NEW\' | sort -u | sed \'s/FIXED:/FIX:/g\' | sed \'s/FIXED :/FIX:/g\' | sed \'s/FIX :/FIX:/g\' | sed \'s/FIX /FIX: /g\' | sed \'s/NEW :/NEW:/g\' | sed \'s/NEW /NEW: /g\' > /tmp/aaa'; - } - print "\n"; - exit; } else { - print "ChangeLog for $MAJOR.$MINOR\.$BUILD was found into '$SOURCE/ChangeLog'\n"; + print "ChangeLog for $MAJOR.$MINOR\.$BUILD was found into '$SOURCE/ChangeLog. But you can regenerate it with commande:'\n"; + } + if (! $BUILD || $BUILD eq '0-rc') # For a major version + { + print 'cd ~/git/dolibarr_'.$MAJOR.'.'.$MINOR.'; git log `git rev-list --boundary '.$MAJOR.'.'.$MINOR.'..origin/develop | grep ^- | cut -c2- | head -n 1`.. --no-merges --pretty=short --oneline | sed -e "s/^[0-9a-z]* //" | grep -e \'^FIX\|NEW\' | sort -u | sed \'s/FIXED:/FIX:/g\' | sed \'s/FIXED :/FIX:/g\' | sed \'s/FIX :/FIX:/g\' | sed \'s/FIX /FIX: /g\' | sed \'s/NEW :/NEW:/g\' | sed \'s/NEW /NEW: /g\' > /tmp/aaa'; + } + else # For a maintenance release + { + print 'cd ~/git/dolibarr_'.$MAJOR.'.'.$MINOR.'; git log '.$MAJOR.'.'.$MINOR.'.'.($BUILD-1).'.. --no-merges --pretty=short --oneline | sed -e "s/^[0-9a-z]* //" | grep -e \'^FIX\|NEW\' | sort -u | sed \'s/FIXED:/FIX:/g\' | sed \'s/FIXED :/FIX:/g\' | sed \'s/FIX :/FIX:/g\' | sed \'s/FIX /FIX: /g\' | sed \'s/NEW :/NEW:/g\' | sed \'s/NEW /NEW: /g\' > /tmp/aaa'; + } + print "\n"; + if (! $ret) + { + exit; } print 'Run git tag -a -m "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'" "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'"'."\n"; @@ -725,8 +734,8 @@ if ($nboftargetok) { print "Remove target ".$FILENAMERPM."...\n"; unlink("$NEWDESTI/".$FILENAMERPM); - print "Remove target ".$FILENAMETGZ2."-".$RPMSUBVERSION.".src.rpm...\n"; - unlink("$NEWDESTI/".$FILENAMETGZ2."-".$RPMSUBVERSION.".src.rpm"); + print "Remove target ".$FILENAMERPMSRC."...\n"; + unlink("$NEWDESTI/".$FILENAMERPMSRC); print "Create directory $BUILDROOT/$FILENAMETGZ2\n"; $ret=`rm -fr $BUILDROOT/$FILENAMETGZ2`; @@ -1132,15 +1141,19 @@ if ($nboftargetok) { print "\nList of files to publish (BUILD=$BUILD)\n"; %filestoscansf=( + "$DESTI/signatures/filelist-$MAJOR.$MINOR.$BUILD.xml"=>'none', # none means it won't be published on SF "$DESTI/package_rpm_generic/$FILENAMERPM"=>'Dolibarr installer for Fedora-Redhat-Mandriva-Opensuse (DoliRpm)', + "$DESTI/package_rpm_generic/$FILENAMERPMSRC"=>'none', # none means it won't be published on SF "$DESTI/package_debian-ubuntu/${FILENAMEDEB}_all.deb"=>'Dolibarr installer for Debian-Ubuntu (DoliDeb)', - "$DESTI/package_debian-ubuntu/${FILENAMEDEBSHORT}.orig.tar.gz"=>'none', + "$DESTI/package_debian-ubuntu/${FILENAMEDEBSHORT}.orig.tar.gz"=>'none', # none means it won't be published on SF "$DESTI/package_windows/$FILENAMEEXEDOLIWAMP.exe"=>'Dolibarr installer for Windows (DoliWamp)', "$DESTI/standard/$FILENAMETGZ.tgz"=>'Dolibarr ERP-CRM', "$DESTI/standard/$FILENAMETGZ.zip"=>'Dolibarr ERP-CRM' ); %filestoscanstableasso=( + "$DESTI/signatures/filelist-$MAJOR.$MINOR.$BUILD.xml"=>'signatures', "$DESTI/package_rpm_generic/$FILENAMERPM"=>'package_rpm_generic', + "$DESTI/package_rpm_generic/$FILENAMERPMSRC"=>'package_rpm_generic', "$DESTI/package_debian-ubuntu/${FILENAMEDEB}_all.deb"=>'package_debian-ubuntu', "$DESTI/package_debian-ubuntu/${FILENAMEDEBSHORT}.orig.tar.gz"=>'package_debian-ubuntu', "$DESTI/package_windows/$FILENAMEEXEDOLIWAMP.exe"=>'package_windows', @@ -1202,9 +1215,10 @@ if ($nboftargetok) { my $filesize = -s $file; if (! $filesize) { next; } - print "\n"; - - if ($target eq 'SF' && $filestoscan{$file} ne 'none') { + if ($target eq 'SF') { + if ($filestoscan{$file} eq 'none') { + next; + } $destFolder="$NEWPUBLISH/$filestoscan{$file}/".$MAJOR.'.'.$MINOR.'.'.$BUILD; } elsif ($target eq 'ASSO' and $NEWPUBLISH =~ /stable/) { @@ -1221,6 +1235,8 @@ if ($nboftargetok) { $filenameonly =~ s/.*\/[^\/]+\/([^\/])+$/$1/; $destFolder="$NEWPUBLISH/$dirnameonly"; } + + print "\n"; print "Publish file ".$file." to ".$destFolder."\n"; # mkdir diff --git a/build/obs/README b/build/obs/README index cf312fc0e68..c8a29e1dac4 100644 --- a/build/obs/README +++ b/build/obs/README @@ -36,7 +36,7 @@ Go into project you want to update. It mught be: Once logged, click on "Add file" in section "Source Files", then select mode "Upload From: Remote URL" Keep empty for "Filename", choose "Remote URL" and enter into last field, URL that should looks like this: -http://www.dolibarr.org/files/stable/package_rpm_generic/dolibarr-x.y.v-0.3.src.rpm +http://www.dolibarr.org/files/stable/package_rpm_generic/dolibarr-x.y.v-0.4.src.rpm Then add into Advanded - Attributes OBS:Screenshots http://www.dolibarr.org/images/dolibarr_screenshot1.png diff --git a/build/rpm/dolibarr_fedora.spec b/build/rpm/dolibarr_fedora.spec index 4ad1441104d..e65e6bc3b7d 100755 --- a/build/rpm/dolibarr_fedora.spec +++ b/build/rpm/dolibarr_fedora.spec @@ -34,7 +34,7 @@ AutoReqProv: no %description -An easy to use CRM & ERP open source/free software for small +An easy to use CRM & ERP open source/free software package for small and medium companies, foundations or freelances. It includes different features for Enterprise Resource Planning (ERP) and Customer Relationship Management (CRM) but also for different other activities. diff --git a/build/rpm/dolibarr_generic.spec b/build/rpm/dolibarr_generic.spec index f20b2047225..655ef87f925 100755 --- a/build/rpm/dolibarr_generic.spec +++ b/build/rpm/dolibarr_generic.spec @@ -75,7 +75,7 @@ AutoReqProv: no %description -An easy to use CRM & ERP open source/free software for small +An easy to use CRM & ERP open source/free software package for small and medium companies, foundations or freelances. It includes different features for Enterprise Resource Planning (ERP) and Customer Relationship Management (CRM) but also for different other activities. diff --git a/build/rpm/dolibarr_mandriva.spec b/build/rpm/dolibarr_mandriva.spec index ca836bc47d6..55fb7183734 100755 --- a/build/rpm/dolibarr_mandriva.spec +++ b/build/rpm/dolibarr_mandriva.spec @@ -33,7 +33,7 @@ AutoReqProv: no %description -An easy to use CRM & ERP open source/free software for small +An easy to use CRM & ERP open source/free software package for small and medium companies, foundations or freelances. It includes different features for Enterprise Resource Planning (ERP) and Customer Relationship Management (CRM) but also for different other activities. diff --git a/build/rpm/dolibarr_opensuse.spec b/build/rpm/dolibarr_opensuse.spec index fcff3363213..f7e29927ebb 100755 --- a/build/rpm/dolibarr_opensuse.spec +++ b/build/rpm/dolibarr_opensuse.spec @@ -36,7 +36,7 @@ AutoReqProv: no %description -An easy to use CRM & ERP open source/free software for small +An easy to use CRM & ERP open source/free software package for small and medium companies, foundations or freelances. It includes different features for Enterprise Resource Planning (ERP) and Customer Relationship Management (CRM) but also for different other activities. diff --git a/composer.json b/composer.json index dbe3b9e303f..2aa9dd216d6 100644 --- a/composer.json +++ b/composer.json @@ -55,6 +55,6 @@ "ext-soap": "Native SOAP", "ext-zip": "ODT and Excel support", "ext-xml": "Excel support", - "firephp/firephp-core": "Logging to Firebug console support", + "firephp/firephp-core": "Logging to Firebug console support" } } diff --git a/dev/README b/dev/README index 88011d07509..337928507fc 100644 --- a/dev/README +++ b/dev/README @@ -7,7 +7,7 @@ provided with a standard release. There is also some documentation on Dolibarr Wiki: -http://wiki.dolibarr.org/ +https://wiki.dolibarr.org/ and -http://www.dolibarr.org/html_doxygen/index.html +https://doxygen.dolibarr.org/ diff --git a/dev/examples/README b/dev/examples/code/README similarity index 100% rename from dev/examples/README rename to dev/examples/code/README diff --git a/dev/examples/create_invoice.php b/dev/examples/code/create_invoice.php similarity index 100% rename from dev/examples/create_invoice.php rename to dev/examples/code/create_invoice.php diff --git a/dev/examples/create_order.php b/dev/examples/code/create_order.php similarity index 100% rename from dev/examples/create_order.php rename to dev/examples/code/create_order.php diff --git a/dev/examples/create_product.php b/dev/examples/code/create_product.php similarity index 100% rename from dev/examples/create_product.php rename to dev/examples/code/create_product.php diff --git a/dev/examples/create_user.php b/dev/examples/code/create_user.php similarity index 100% rename from dev/examples/create_user.php rename to dev/examples/code/create_user.php diff --git a/dev/examples/get_contracts.php b/dev/examples/code/get_contracts.php similarity index 100% rename from dev/examples/get_contracts.php rename to dev/examples/code/get_contracts.php diff --git a/dev/ical/event_recu.txt b/dev/examples/ical/event_recu.txt similarity index 100% rename from dev/ical/event_recu.txt rename to dev/examples/ical/event_recu.txt diff --git a/dev/ldap/README b/dev/examples/ldap/README similarity index 100% rename from dev/ldap/README rename to dev/examples/ldap/README diff --git a/dev/ldap/ldapadd_sample1.txt b/dev/examples/ldap/ldapadd_sample1.txt similarity index 100% rename from dev/ldap/ldapadd_sample1.txt rename to dev/examples/ldap/ldapadd_sample1.txt diff --git a/dev/ldap/ldapadd_sample2.txt b/dev/examples/ldap/ldapadd_sample2.txt similarity index 100% rename from dev/ldap/ldapadd_sample2.txt rename to dev/examples/ldap/ldapadd_sample2.txt diff --git a/dev/ldap/ldapadd_sample3.txt b/dev/examples/ldap/ldapadd_sample3.txt similarity index 100% rename from dev/ldap/ldapadd_sample3.txt rename to dev/examples/ldap/ldapadd_sample3.txt diff --git a/dev/ldap/ldapdelete_sample1.txt b/dev/examples/ldap/ldapdelete_sample1.txt similarity index 100% rename from dev/ldap/ldapdelete_sample1.txt rename to dev/examples/ldap/ldapdelete_sample1.txt diff --git a/dev/ldap/ldapdelete_sample3.txt b/dev/examples/ldap/ldapdelete_sample3.txt similarity index 100% rename from dev/ldap/ldapdelete_sample3.txt rename to dev/examples/ldap/ldapdelete_sample3.txt diff --git a/dev/ldap/ldapmodify_sample1.txt b/dev/examples/ldap/ldapmodify_sample1.txt similarity index 100% rename from dev/ldap/ldapmodify_sample1.txt rename to dev/examples/ldap/ldapmodify_sample1.txt diff --git a/dev/ldap/ldapsearch_sample1.txt b/dev/examples/ldap/ldapsearch_sample1.txt similarity index 100% rename from dev/ldap/ldapsearch_sample1.txt rename to dev/examples/ldap/ldapsearch_sample1.txt diff --git a/dev/ldap/setup_example_activedirectory.jpg b/dev/examples/ldap/setup_example_activedirectory.jpg similarity index 100% rename from dev/ldap/setup_example_activedirectory.jpg rename to dev/examples/ldap/setup_example_activedirectory.jpg diff --git a/dev/mail/README b/dev/examples/mail/README similarity index 100% rename from dev/mail/README rename to dev/examples/mail/README diff --git a/dev/mail/dolibarr_mail_attachement.txt b/dev/examples/mail/dolibarr_mail_attachement.txt similarity index 100% rename from dev/mail/dolibarr_mail_attachement.txt rename to dev/examples/mail/dolibarr_mail_attachement.txt diff --git a/dev/mail/dolibarr_mail_attachementHTML.txt b/dev/examples/mail/dolibarr_mail_attachementHTML.txt similarity index 100% rename from dev/mail/dolibarr_mail_attachementHTML.txt rename to dev/examples/mail/dolibarr_mail_attachementHTML.txt diff --git a/dev/mail/dolibarr_mail_attachementwithimageHTML.txt b/dev/examples/mail/dolibarr_mail_attachementwithimageHTML.txt similarity index 100% rename from dev/mail/dolibarr_mail_attachementwithimageHTML.txt rename to dev/examples/mail/dolibarr_mail_attachementwithimageHTML.txt diff --git a/dev/mail/dolibarr_mail_simple.txt b/dev/examples/mail/dolibarr_mail_simple.txt similarity index 100% rename from dev/mail/dolibarr_mail_simple.txt rename to dev/examples/mail/dolibarr_mail_simple.txt diff --git a/dev/mail/dolibarr_mail_simpleHTML.txt b/dev/examples/mail/dolibarr_mail_simpleHTML.txt similarity index 100% rename from dev/mail/dolibarr_mail_simpleHTML.txt rename to dev/examples/mail/dolibarr_mail_simpleHTML.txt diff --git a/dev/mail/dolibarr_mail_universal.txt b/dev/examples/mail/dolibarr_mail_universal.txt similarity index 100% rename from dev/mail/dolibarr_mail_universal.txt rename to dev/examples/mail/dolibarr_mail_universal.txt diff --git a/dev/mail/dolibarr_mail_withimageHTML.txt b/dev/examples/mail/dolibarr_mail_withimageHTML.txt similarity index 100% rename from dev/mail/dolibarr_mail_withimageHTML.txt rename to dev/examples/mail/dolibarr_mail_withimageHTML.txt diff --git a/dev/mail/source_email_from_thirdparty.txt b/dev/examples/mail/source_email_from_thirdparty.txt similarity index 100% rename from dev/mail/source_email_from_thirdparty.txt rename to dev/examples/mail/source_email_from_thirdparty.txt diff --git a/dev/initdemo/removedemo.sh b/dev/initdemo/removeconfdemo.sh similarity index 100% rename from dev/initdemo/removedemo.sh rename to dev/initdemo/removeconfdemo.sh diff --git a/dev/cliparts/commons.svg b/dev/resources/cliparts/commons.svg similarity index 100% rename from dev/cliparts/commons.svg rename to dev/resources/cliparts/commons.svg diff --git a/dev/dbmodel/dolibarr.uml b/dev/resources/dbmodel/dolibarr.uml similarity index 100% rename from dev/dbmodel/dolibarr.uml rename to dev/resources/dbmodel/dolibarr.uml diff --git a/dev/dbmodel/dolibarr.umldi b/dev/resources/dbmodel/dolibarr.umldi similarity index 100% rename from dev/dbmodel/dolibarr.umldi rename to dev/resources/dbmodel/dolibarr.umldi diff --git a/dev/dbmodel/dolibarr_schema.mwb b/dev/resources/dbmodel/dolibarr_schema.mwb similarity index 100% rename from dev/dbmodel/dolibarr_schema.mwb rename to dev/resources/dbmodel/dolibarr_schema.mwb diff --git a/dev/iso-normes/GURULABS-RPM-GUIDE-v1.0.PDF b/dev/resources/iso-normes/GURULABS-RPM-GUIDE-v1.0.PDF similarity index 100% rename from dev/iso-normes/GURULABS-RPM-GUIDE-v1.0.PDF rename to dev/resources/iso-normes/GURULABS-RPM-GUIDE-v1.0.PDF diff --git a/dev/iso-normes/address_format.txt b/dev/resources/iso-normes/address_format.txt similarity index 100% rename from dev/iso-normes/address_format.txt rename to dev/resources/iso-normes/address_format.txt diff --git a/dev/iso-normes/banknumber_format.txt b/dev/resources/iso-normes/banknumber_format.txt similarity index 100% rename from dev/iso-normes/banknumber_format.txt rename to dev/resources/iso-normes/banknumber_format.txt diff --git a/dev/iso-normes/barcode_EAN13.txt b/dev/resources/iso-normes/barcode_EAN13.txt similarity index 100% rename from dev/iso-normes/barcode_EAN13.txt rename to dev/resources/iso-normes/barcode_EAN13.txt diff --git a/dev/iso-normes/countries_iso-3166_en.txt b/dev/resources/iso-normes/countries_iso-3166_en.txt similarity index 100% rename from dev/iso-normes/countries_iso-3166_en.txt rename to dev/resources/iso-normes/countries_iso-3166_en.txt diff --git a/dev/iso-normes/countries_iso-3166_fr.txt b/dev/resources/iso-normes/countries_iso-3166_fr.txt similarity index 100% rename from dev/iso-normes/countries_iso-3166_fr.txt rename to dev/resources/iso-normes/countries_iso-3166_fr.txt diff --git a/dev/iso-normes/currencies_iso-4217.txt b/dev/resources/iso-normes/currencies_iso-4217.txt similarity index 100% rename from dev/iso-normes/currencies_iso-4217.txt rename to dev/resources/iso-normes/currencies_iso-4217.txt diff --git a/dev/iso-normes/fichier_norme_AFB-CFONB.pdf b/dev/resources/iso-normes/fichier_norme_AFB-CFONB.pdf similarity index 100% rename from dev/iso-normes/fichier_norme_AFB-CFONB.pdf rename to dev/resources/iso-normes/fichier_norme_AFB-CFONB.pdf diff --git a/dev/iso-normes/format_FEC-Lien_outil_de_test_agréé.pdf b/dev/resources/iso-normes/format_FEC-Lien_outil_de_test_agréé.pdf similarity index 100% rename from dev/iso-normes/format_FEC-Lien_outil_de_test_agréé.pdf rename to dev/resources/iso-normes/format_FEC-Lien_outil_de_test_agréé.pdf diff --git a/dev/iso-normes/format_FEC.pdf b/dev/resources/iso-normes/format_FEC.pdf similarity index 100% rename from dev/iso-normes/format_FEC.pdf rename to dev/resources/iso-normes/format_FEC.pdf diff --git a/dev/iso-normes/iban_iso-13616.txt b/dev/resources/iso-normes/iban_iso-13616.txt similarity index 100% rename from dev/iso-normes/iban_iso-13616.txt rename to dev/resources/iso-normes/iban_iso-13616.txt diff --git a/dev/iso-normes/languages_iso-639.txt b/dev/resources/iso-normes/languages_iso-639.txt similarity index 100% rename from dev/iso-normes/languages_iso-639.txt rename to dev/resources/iso-normes/languages_iso-639.txt diff --git a/dev/iso-normes/locales.txt b/dev/resources/iso-normes/locales.txt similarity index 100% rename from dev/iso-normes/locales.txt rename to dev/resources/iso-normes/locales.txt diff --git a/dev/iso-normes/vat_number_names.txt b/dev/resources/iso-normes/vat_number_names.txt similarity index 100% rename from dev/iso-normes/vat_number_names.txt rename to dev/resources/iso-normes/vat_number_names.txt diff --git a/dev/iso-normes/world_tax_rates.txt b/dev/resources/iso-normes/world_tax_rates.txt similarity index 100% rename from dev/iso-normes/world_tax_rates.txt rename to dev/resources/iso-normes/world_tax_rates.txt diff --git a/dev/iso-normes/xmlexport.txt b/dev/resources/iso-normes/xmlexport.txt similarity index 100% rename from dev/iso-normes/xmlexport.txt rename to dev/resources/iso-normes/xmlexport.txt diff --git a/dev/licence/Links on GPL.txt b/dev/resources/licence/Links on GPL.txt similarity index 100% rename from dev/licence/Links on GPL.txt rename to dev/resources/licence/Links on GPL.txt diff --git a/dev/licence/quick-guide-gplv3-compatibility.png b/dev/resources/licence/quick-guide-gplv3-compatibility.png similarity index 100% rename from dev/licence/quick-guide-gplv3-compatibility.png rename to dev/resources/licence/quick-guide-gplv3-compatibility.png diff --git a/dev/codesniffer/README b/dev/setup/codesniffer/README similarity index 100% rename from dev/codesniffer/README rename to dev/setup/codesniffer/README diff --git a/dev/codesniffer/php.ini b/dev/setup/codesniffer/php.ini similarity index 100% rename from dev/codesniffer/php.ini rename to dev/setup/codesniffer/php.ini diff --git a/dev/codesniffer/ruleset.dtd b/dev/setup/codesniffer/ruleset.dtd similarity index 100% rename from dev/codesniffer/ruleset.dtd rename to dev/setup/codesniffer/ruleset.dtd diff --git a/dev/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml similarity index 99% rename from dev/codesniffer/ruleset.xml rename to dev/setup/codesniffer/ruleset.xml index 2a58094717f..32a938662e6 100644 --- a/dev/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -9,6 +9,7 @@ htdocs/includes htdocs/conf.php */nltechno* + */htdocs/includes diff --git a/dev/codetemplates/README b/dev/setup/codetemplates/README similarity index 100% rename from dev/codetemplates/README rename to dev/setup/codetemplates/README diff --git a/dev/codetemplates/codetemplates.dtd b/dev/setup/codetemplates/codetemplates.dtd similarity index 100% rename from dev/codetemplates/codetemplates.dtd rename to dev/setup/codetemplates/codetemplates.dtd diff --git a/dev/codetemplates/codetemplates.xml b/dev/setup/codetemplates/codetemplates.xml similarity index 100% rename from dev/codetemplates/codetemplates.xml rename to dev/setup/codetemplates/codetemplates.xml diff --git a/dev/multitail/.multitailrc b/dev/setup/multitail/.multitailrc similarity index 100% rename from dev/multitail/.multitailrc rename to dev/setup/multitail/.multitailrc diff --git a/dev/phpunit/README b/dev/setup/phpunit/README similarity index 100% rename from dev/phpunit/README rename to dev/setup/phpunit/README diff --git a/dev/phpunit/eclipse_setup_for_pti_phpunit.png b/dev/setup/phpunit/eclipse_setup_for_pti_phpunit.png similarity index 100% rename from dev/phpunit/eclipse_setup_for_pti_phpunit.png rename to dev/setup/phpunit/eclipse_setup_for_pti_phpunit.png diff --git a/dev/security/README b/dev/setup/security/README similarity index 100% rename from dev/security/README rename to dev/setup/security/README diff --git a/dev/security/htaccess.txt b/dev/setup/security/htaccess.txt similarity index 100% rename from dev/security/htaccess.txt rename to dev/setup/security/htaccess.txt diff --git a/dev/xdebug/README b/dev/setup/xdebug/README similarity index 100% rename from dev/xdebug/README rename to dev/setup/xdebug/README diff --git a/dev/xdebug/eclipse_setup_for_xdebug.jpg b/dev/setup/xdebug/eclipse_setup_for_xdebug.jpg similarity index 100% rename from dev/xdebug/eclipse_setup_for_xdebug.jpg rename to dev/setup/xdebug/eclipse_setup_for_xdebug.jpg diff --git a/dev/skeletons/README b/dev/skeletons/README index 02a760a53dc..5b5b992d91e 100644 --- a/dev/skeletons/README +++ b/dev/skeletons/README @@ -2,24 +2,32 @@ README (English) -------------------------------- This directory contains PHP script samples that can be used to start a development on Dolibarr. -build_class_from_table.php: + +*** build_class_from_table.php: + This is the script to use to generate PHP code of a PHP POJO class object, a PHP script that use this POJO. This script use the files skeleton_*.php to build its generated code. -modMyModule.class.php: +*** modMyModule.class.php: + Is a sample of module descriptor that you can use if you want to build a new module/plugin for Dolibarr. -skeleton_script.php: +*** skeleton_script.php: + Is a sample you can use as an example if you need to build a script to run on command line -skeleton_page.php: + +*** skeleton_page.php: + Is a sample you can use as an example if you need to build an HTML page to include in Dolibarr GUI. -skeleton_class.class.php: + +*** skeleton_class.class.php: + Is a sample you can use as an example if you need to build a class file to access a new table required by a Dolibarr development. However it is better to run the build_class_from_table.php script that accepts a table name as a parameter and will uses the description table within database and the skeleton_class.class.php file to generate full code for your class file. After running this script, the class to access your table (insert a record, update, delete and select) is directly finished and can be used by your module's code. diff --git a/dev/skeletons/modMyModule.class.php b/dev/skeletons/modMyModule.class.php index 22432433334..64890b9d9cf 100644 --- a/dev/skeletons/modMyModule.class.php +++ b/dev/skeletons/modMyModule.class.php @@ -62,7 +62,7 @@ class modMyModule extends DolibarrModules $this->name = preg_replace('/^mod/i','',get_class($this)); // Module description, used if translation string 'ModuleXXXDesc' not found (where XXX is value of numeric property 'numero' of module) $this->description = "Description of module MyModule"; - $this->descriptionlong = "A very lon description. Can be a full HTML content"; + $this->descriptionlong = "A very long description. Can be a full HTML content"; $this->editor_name = 'Editor name'; $this->editor_url = 'http://www.dolibarr.org'; @@ -105,9 +105,9 @@ class modMyModule extends DolibarrModules // Dependencies $this->hidden = false; // A condition to hide module - $this->depends = array(); // List of modules id that must be enabled if this module is enabled - $this->requiredby = array(); // List of modules id to disable if this one is disabled - $this->conflictwith = array(); // List of modules id this module is in conflict with + $this->depends = array(); // List of module class names as string that must be enabled if this module is enabled + $this->requiredby = array(); // List of module ids to disable if this one is disabled + $this->conflictwith = array(); // List of module class names as string this module is in conflict with $this->phpmin = array(5,0); // Minimum version of PHP required by module $this->need_dolibarr_version = array(3,0); // Minimum version of Dolibarr required by module $this->langfiles = array("mylangfile@mymodule"); diff --git a/dev/skeletons/skeleton_api_class.class.php b/dev/skeletons/skeleton_api_class.class.php index 9cc8de2bc5e..a40b00af72c 100644 --- a/dev/skeletons/skeleton_api_class.class.php +++ b/dev/skeletons/skeleton_api_class.class.php @@ -93,12 +93,12 @@ class SkeletonApi extends DolibarrApi * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101') or (t.import_key:=:'20160101')" * @return array Array of skeleton objects * * @url GET /skeletons/ */ - function getList($mode, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { + function index($mode, $sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -124,18 +124,19 @@ class SkeletonApi extends DolibarrApi 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 - // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + if ($sqlfilters) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + 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); diff --git a/dev/skeletons/skeleton_card.php b/dev/skeletons/skeleton_card.php index 53cacc2b10f..9adcdba87de 100644 --- a/dev/skeletons/skeleton_card.php +++ b/dev/skeletons/skeleton_card.php @@ -59,25 +59,27 @@ $myparam = GETPOST('myparam','alpha'); $search_field1=GETPOST("search_field1"); $search_field2=GETPOST("search_field2"); +if (empty($action) && empty($id) && empty($ref)) $action='view'; + // Protection if external user if ($user->societe_id > 0) { //accessforbidden(); } +//$result = restrictedArea($user, 'mymodule', $id); -if (empty($action) && empty($id) && empty($ref)) $action='list'; -// Load object if id or ref is provided as parameter -$object=new Skeleton_Class($db); -if (($id > 0 || ! empty($ref)) && $action != 'add') -{ - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); -} +$object = new Skeleton_Class($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals // Initialize technical object to manage hooks of modules. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('skeleton')); -$extrafields = new ExtraFields($db); @@ -281,8 +283,13 @@ if (($id || $ref) && $action == 'edit') // Part to show record -if ($id && (empty($action) || $action == 'view' || $action == 'delete')) +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + $res = $object->fetch_optionals($object->id, $extralabels); + + $head = commande_prepare_head($object); + dol_fiche_head($head, 'order', $langs->trans("CustomerOrder"), 0, 'order'); + print load_fiche_titre($langs->trans("MyModule")); dol_fiche_head(); @@ -293,7 +300,7 @@ if ($id && (empty($action) || $action == 'view' || $action == 'delete')) } print ''."\n"; - // print ''; + // print ''; // LIST_OF_TD_LABEL_FIELDS_VIEW print '
'.$langs->trans("Label").'
'.$langs->trans("Label").''.$object->label.'
'; diff --git a/dev/skeletons/skeleton_class.class.php b/dev/skeletons/skeleton_class.class.php index 3e4c2701896..4f725fa2dbe 100644 --- a/dev/skeletons/skeleton_class.class.php +++ b/dev/skeletons/skeleton_class.class.php @@ -164,10 +164,14 @@ class Skeleton_Class extends CommonObject $sql .= ' t.field2'; //... $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql.= ' WHERE 1 = 1'; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("skeleton", 1) . ")"; + } if (null !== $ref) { - $sql .= ' WHERE t.ref = ' . '\'' . $ref . '\''; + $sql .= ' AND t.ref = ' . '\'' . $ref . '\''; } else { - $sql .= ' WHERE t.rowid = ' . $id; + $sql .= ' AND t.rowid = ' . $id; } $resql = $this->db->query($sql); @@ -181,6 +185,16 @@ class Skeleton_Class extends CommonObject $this->prop2 = $obj->field2; //... } + + // Retrieve all extrafields for invoice + // fetch optionals attributes and labels + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); + + // $this->fetch_lines(); + $this->db->free($resql); if ($numrows) { @@ -226,16 +240,20 @@ class Skeleton_Class extends CommonObject $sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; } } - if (count($sqlwhere) > 0) { - $sql .= ' WHERE ' . implode(' '.$filtermode.' ', $sqlwhere); + $sql.= ' WHERE 1 = 1'; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("skeleton", 1) . ")"; + } + if (count($sqlwhere) > 0) { + $sql .= ' AND ' . implode(' '.$filtermode.' ', $sqlwhere); } - if (!empty($sortfield)) { $sql .= $this->db->order($sortfield,$sortorder); } if (!empty($limit)) { $sql .= ' ' . $this->db->plimit($limit + 1, $offset); } + $this->lines = array(); $resql = $this->db->query($sql); @@ -355,6 +373,8 @@ class Skeleton_Class extends CommonObject } } + // If you need to delete child tables to, you can insert them here + if (!$error) { $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element; $sql .= ' WHERE rowid=' . $this->id; @@ -427,41 +447,55 @@ class Skeleton_Class extends CommonObject } /** - * Return a link to the user card (with optionaly the picto) - * Use this->id,this->lastname, this->firstname + * Return a link to the object card (with optionaly the picto) * * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) * @param string $option On what the link point to - * @param integer $notooltip 1=Disable tooltip + * @param int $notooltip 1=Disable tooltip * @param int $maxlen Max length of visible user name * @param string $morecss Add more css on link * @return string String with URL */ function getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='') { - global $langs, $conf, $db; + global $db, $conf, $langs; global $dolibarr_main_authentication, $dolibarr_main_demo; global $menumanager; - + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + $result = ''; $companylink = ''; $label = '' . $langs->trans("MyModule") . ''; - $label.= '
'; + $label.= '
'; $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; - $link = 'table_name.'_card.php?id='.$this->id; + + $linkclose=''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowProject"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + } + else $linkclose = ($morecss?' class="'.$morecss.'"':''); + + $linkstart = ''; $linkend=''; if ($withpicto) { - $result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); + $result.=($linkstart.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); if ($withpicto != 2) $result.=' '; } - $result.= $link . $this->ref . $linkend; + $result.= $linkstart . $this->ref . $linkend; return $result; } @@ -477,13 +511,13 @@ class Skeleton_Class extends CommonObject } /** - * Renvoi le libelle d'un status donne + * Return the status * * @param int $status Id status - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto * @return string Label of status */ - function LibStatut($status,$mode=0) + static function LibStatut($status,$mode=0) { global $langs; @@ -518,6 +552,11 @@ class Skeleton_Class extends CommonObject if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); } + if ($mode == 6) + { + if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } } diff --git a/dev/skeletons/skeleton_list.php b/dev/skeletons/skeleton_list.php index 1facee1306e..c47a87a8033 100644 --- a/dev/skeletons/skeleton_list.php +++ b/dev/skeletons/skeleton_list.php @@ -58,6 +58,7 @@ $action = GETPOST('action','alpha'); $backtopage = GETPOST('backtopage'); $myparam = GETPOST('myparam','alpha'); +$search_all=trim(GETPOST("sall")); $search_field1=GETPOST("search_field1"); $search_field2=GETPOST("search_field2"); $search_myfield=GETPOST('search_myfield'); @@ -141,22 +142,23 @@ $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - -// Purge search criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All test are required to be compatible with all browsers -{ - $search_field1=''; - $search_field2=''; - $search_date_creation=''; - $search_date_update=''; - $toselect=''; - $search_array_options=array(); -} - - if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers + { + $search_field1=''; + $search_field2=''; + $search_date_creation=''; + $search_date_update=''; + $toselect=''; + $search_array_options=array(); + } + + // Mass actions $objectclass='Skeleton'; $objectlabel='Skeleton'; $permtoread = $user->rights->skeleton->read; @@ -180,7 +182,6 @@ $form=new Form($db); //$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; $help_url=''; $title = $langs->trans('MyModuleListTitle'); -llxHeader('', $title, $help_url); // Put here content of your page @@ -247,305 +248,308 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql.= $db->plimit($limit+1, $offset); - dol_syslog($script_file, LOG_DEBUG); $resql=$db->query($sql); -if ($resql) +if (! $resql) { - $num = $db->num_rows($resql); - - $arrayofselected=is_array($toselect)?$toselect:array(); - - $params=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($search_field1 != '') $params.= '&search_field1='.urlencode($search_field1); - if ($search_field2 != '') $params.= '&search_field2='.urlencode($search_field2); - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + +// Direct jump if only one record found +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +{ + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/skeleton/card.php?id='.$id); + exit; +} + +llxHeader('', $title, $help_url); + +$arrayofselected=is_array($toselect)?$toselect:array(); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($search_field1 != '') $param.= '&search_field1='.urlencode($search_field1); +if ($search_field2 != '') $param.= '&search_field2='.urlencode($search_field2); +if ($optioncss != '') $param.='&optioncss='.$optioncss; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +$arrayofmassactions = array( + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->mymodule->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); +if ($massaction == 'presend') $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + +print '
'; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); +} + +$moreforfilter = ''; +$moreforfilter.='
'; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
'; + +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook +if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; +else $moreforfilter = $hookmanager->resPrint; + +if (! empty($moreforfilter)) +{ + print '
'; + print $moreforfilter; + print '
'; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print ''."\n"; + +// Fields title +print ''; +// LIST_OF_TD_TITLE_FIELDS +//if (! empty($arrayfields['t.field1']['checked'])) print_liste_field_titre($arrayfields['t.field1']['label'],$_SERVER['PHP_SELF'],'t.field1','',$param,'',$sortfield,$sortorder); +//if (! empty($arrayfields['t.field2']['checked'])) print_liste_field_titre($arrayfields['t.field2']['label'],$_SERVER['PHP_SELF'],'t.field2','',$param,'',$sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'],$_SERVER["PHP_SELF"],"t.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'],$_SERVER["PHP_SELF"],"t.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +//if (! empty($arrayfields['t.status']['checked'])) print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"t.status","",$param,'align="center"',$sortfield,$sortorder); +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); +print ''."\n"; + +// Fields title search +print ''; +// LIST_OF_TD_TITLE_SEARCH +//if (! empty($arrayfields['t.field1']['checked'])) print ''; +//if (! empty($arrayfields['t.field2']['checked'])) print ''; +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->mymodule->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend') $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); - - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } - - $moreforfilter = ''; - $moreforfilter.='
'; - $moreforfilter.= $langs->trans('MyFilter') . ': '; - $moreforfilter.= '
'; - - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; - else $moreforfilter = $hookmanager->resPrint; - - if (! empty($moreforfilter)) - { - print '
'; - print $moreforfilter; - print '
'; - } - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '
'."\n"; - - // Fields title - print ''; - // LIST_OF_TD_TITLE_FIELDS - //if (! empty($arrayfields['t.field1']['checked'])) print_liste_field_titre($arrayfields['t.field1']['label'],$_SERVER['PHP_SELF'],'t.field1','',$params,'',$sortfield,$sortorder); - //if (! empty($arrayfields['t.field2']['checked'])) print_liste_field_titre($arrayfields['t.field2']['label'],$_SERVER['PHP_SELF'],'t.field2','',$params,'',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'],$_SERVER["PHP_SELF"],"t.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'],$_SERVER["PHP_SELF"],"t.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - //if (! empty($arrayfields['t.status']['checked'])) print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"t.status","",$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); - print ''."\n"; - - // Fields title search - print ''; - // LIST_OF_TD_TITLE_SEARCH - //if (! empty($arrayfields['t.field1']['checked'])) print ''; - //if (! empty($arrayfields['t.field2']['checked'])) print ''; - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) + if (! empty($arrayfields["ef.".$key]['checked'])) { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['t.datec']['checked'])) - { - // Date creation - print ''; } - if (! empty($arrayfields['t.tms']['checked'])) - { - // Date modification - print ''; - } - /*if (! empty($arrayfields['u.statut']['checked'])) - { - // Status - print ''; - }*/ - // Action column - print ''; - print ''."\n"; - +} +if (! empty($arrayfields['t.tms']['checked'])) +{ + // Date modification + print ''; +} +/*if (! empty($arrayfields['u.statut']['checked'])) +{ + // Status + print ''; +}*/ +// Action column +print ''; +print ''."\n"; - $i=0; - $var=true; - $totalarray=array(); - while ($i < min($num, $limit)) + +$i=0; +$var=true; +$totalarray=array(); +while ($i < min($num, $limit)) +{ + $obj = $db->fetch_object($resql); + if ($obj) { - $obj = $db->fetch_object($resql); - if ($obj) + $var = !$var; + + // Show here line of result + print ''; + // LIST_OF_TD_FIELDS_LIST + /* + if (! empty($arrayfields['t.field1']['checked'])) { - $var = !$var; - - // Show here line of result - print ''; - // LIST_OF_TD_FIELDS_LIST - /* - if (! empty($arrayfields['t.field1']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['t.field2']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - }*/ - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['t.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['t.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - /* - if (! empty($arrayfields['u.statut']['checked'])) - { - $userstatic->statut=$obj->statut; - print ''; - }*/ - - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; - - print ''; + print ''; + if (! $i) $totalarray['nbfield']++; } - $i++; + if (! empty($arrayfields['t.field2']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + }*/ + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['t.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['t.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + /* + if (! empty($arrayfields['u.statut']['checked'])) + { + $userstatic->statut=$obj->statut; + print ''; + }*/ + + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print ''; } - - // Show total line - if (isset($totalarray['totalhtfield'])) - { - print ''; - $i=0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit) print ''; - else print ''; - } - elseif ($totalarray['totalhtfield'] == $i) print ''; - elseif ($totalarray['totalvatfield'] == $i) print ''; - elseif ($totalarray['totalttcfield'] == $i) print ''; - else print ''; - } - print ''; - } - - $db->free($resql); + $i++; +} - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; +// Show total line +if (isset($totalarray['totalhtfield'])) +{ + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''; + elseif ($totalarray['totalvatfield'] == $i) print ''; + elseif ($totalarray['totalttcfield'] == $i) print ''; + else print ''; + } + print ''; +} - print '
'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; - print ''; - print ''; - print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); - print ''; - $searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); - print $searchpitco; +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['t.datec']['checked'])) +{ + // Date creation + print ''; print '
'; + print ''; + print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); + print ''; +$searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); +print $searchpitco; +print '
'.$obj->field1.''.$obj->field2.''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$userstatic->getLibStatut(3).''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; - } - print '
'.$obj->field1.''.$obj->field2.''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour'); + print ''.$userstatic->getLibStatut(3).''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalht']).''.price($totalarray['totalvat']).''.price($totalarray['totalttc']).'
'."\n"; +$db->free($resql); - print '
'."\n"; - - - 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->facture->lire; - $delallowed=$user->rights->facture->lire; - - print '
'; - $paramwithoutshowfiles=preg_replace('/show_files=1&?/','',$param); - $title=$langs->trans("MassFilesArea").' ('.$langs->trans("Hide").')'; - - print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
'.$langs->trans("ShowTempMassFilesArea").''; - } - +$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print ''."\n"; + +print ''."\n"; + + +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->facture->lire; + $delallowed=$user->rights->facture->lire; + + print $formfile->showdocuments('massfilesarea_mymodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else { - $error++; - dol_print_error($db); + print '
'.$langs->trans("ShowTempMassFilesArea").''; } diff --git a/dev/detectnotabfiles.sh b/dev/tools/detectnotabfiles.sh similarity index 100% rename from dev/detectnotabfiles.sh rename to dev/tools/detectnotabfiles.sh diff --git a/dev/fixaltlanguages.sh b/dev/tools/fixaltlanguages.sh similarity index 100% rename from dev/fixaltlanguages.sh rename to dev/tools/fixaltlanguages.sh diff --git a/dev/fixdosfiles.sh b/dev/tools/fixdosfiles.sh similarity index 100% rename from dev/fixdosfiles.sh rename to dev/tools/fixdosfiles.sh diff --git a/dev/fixduplicatelangkey.sh b/dev/tools/fixduplicatelangkey.sh similarity index 92% rename from dev/fixduplicatelangkey.sh rename to dev/tools/fixduplicatelangkey.sh index ae0be750646..2090f8a3504 100755 --- a/dev/fixduplicatelangkey.sh +++ b/dev/tools/fixduplicatelangkey.sh @@ -14,6 +14,7 @@ fi if [ "x$1" = "xlist" ] then + echo "Search duplicate keys into en_US lang files (there is no cross file check)" for file in `find htdocs/langs/en_US -name *.lang -type f` do dupes=$( diff --git a/dev/fixduplicatelines.sh b/dev/tools/fixduplicatelanglines.sh similarity index 90% rename from dev/fixduplicatelines.sh rename to dev/tools/fixduplicatelanglines.sh index 18f9707169e..0c0e2eecb4b 100755 --- a/dev/fixduplicatelines.sh +++ b/dev/tools/fixduplicatelanglines.sh @@ -16,6 +16,7 @@ fi # To detect if [ "x$1" = "xlist" ] then + echo "Search duplicate line for lang en_US" for file in `find htdocs/langs/en_US -type f -name *.lang` do if [ `sort "$file" | grep -v '^$' | uniq -d | wc -l` -gt 0 ] @@ -29,6 +30,7 @@ fi # To fix if [ "x$1" = "xfix" ] then + echo "Fix duplicate line for lang en_US" for file in `find htdocs/langs/en_US -type f -name *.lang` do awk -i inplace ' !x[$0]++' "$file" diff --git a/dev/fixperms.sh b/dev/tools/fixperms.sh similarity index 100% rename from dev/fixperms.sh rename to dev/tools/fixperms.sh diff --git a/dev/fixutf8bomfiles.sh b/dev/tools/fixutf8bomfiles.sh similarity index 100% rename from dev/fixutf8bomfiles.sh rename to dev/tools/fixutf8bomfiles.sh diff --git a/dev/optimize_images.sh b/dev/tools/optimize_images.sh similarity index 100% rename from dev/optimize_images.sh rename to dev/tools/optimize_images.sh diff --git a/dev/resize_window.sh b/dev/tools/resize_window.sh similarity index 100% rename from dev/resize_window.sh rename to dev/tools/resize_window.sh diff --git a/dev/rmphpclosingtag.sh b/dev/tools/rmphpclosingtag.sh similarity index 100% rename from dev/rmphpclosingtag.sh rename to dev/tools/rmphpclosingtag.sh diff --git a/dev/test/testdiv.php b/dev/tools/test/testdiv.php similarity index 100% rename from dev/test/testdiv.php rename to dev/tools/test/testdiv.php diff --git a/dev/test/testtcpdf.php b/dev/tools/test/testtcpdf.php similarity index 100% rename from dev/test/testtcpdf.php rename to dev/tools/test/testtcpdf.php diff --git a/dev/test/testutf.php b/dev/tools/test/testutf.php similarity index 100% rename from dev/test/testutf.php rename to dev/tools/test/testutf.php diff --git a/dev/translation/txpull.sh b/dev/translation/txpull.sh index 71e03cf522e..4156daf7674 100755 --- a/dev/translation/txpull.sh +++ b/dev/translation/txpull.sh @@ -42,4 +42,4 @@ else fi echo Think to launch also: -echo "> dev/fixaltlanguages.sh fix all" +echo "> dev/tools/fixaltlanguages.sh fix all" diff --git a/doc/images/dolibarr_screenshot4_1280x800.png b/doc/images/dolibarr_screenshot4_1280x800.png index f76c6f07522..c00c3ea92e0 100644 Binary files a/doc/images/dolibarr_screenshot4_1280x800.png and b/doc/images/dolibarr_screenshot4_1280x800.png differ diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 2f7228eb9d4..cb3255f981d 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -19,22 +19,26 @@ /** * \file htdocs/accountancy/admin/account.php - * \ingroup Advanced accountancy + * \ingroup Advanced accountancy * \brief List accounting account */ -require '../../main.inc.php'; -// Class +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT . '/accountancy/class/html.formventilation.class.php'; // Langs $langs->load("compta"); +$langs->load("bills"); +$langs->load("admin"); $langs->load("accountancy"); +$langs->load("salaries"); $mesg = ''; $action = GETPOST('action'); +$cancel = GETPOST('cancel'); $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); $search_account = GETPOST("search_account"); @@ -44,10 +48,8 @@ $search_pcgtype = GETPOST("search_pcgtype"); $search_pcgsubtype = GETPOST("search_pcgsubtype"); // Security check -if ($user->societe_id > 0) - accessforbidden(); -if (! $user->rights->accounting->chartofaccount) - accessforbidden(); +if ($user->societe_id > 0) accessforbidden(); +if (! $user->rights->accounting->chartofaccount) accessforbidden(); // Load variable for pagination $limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit; @@ -80,34 +82,53 @@ $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +if (empty($reshook)) { - $search_account = ""; - $search_label = ""; - $search_accountparent = ""; - $search_pcgtype = ""; - $search_pcgsubtype = ""; -} - -if ($action == 'disable') { - if ($accounting->fetch($id)) { - $result = $accounting->account_desactivate($id); - } - - $action = 'update'; - if ($result < 0) { - setEventMessages($accounting->error, $accounting->errors, 'errors'); - } -} else if ($action == 'enable') { - if ($accounting->fetch($id)) { - $result = $accounting->account_activate($id); - } - $action = 'update'; - if ($result < 0) { - setEventMessages($accounting->error, $accounting->errors, 'errors'); - } + if (! empty($cancel)) $action = ''; + + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All test are required to be compatible with all browsers + { + $search_account = ""; + $search_label = ""; + $search_accountparent = ""; + $search_pcgtype = ""; + $search_pcgsubtype = ""; + } + + if (GETPOST('change_chart')) + { + $chartofaccounts = GETPOST('chartofaccounts', 'int'); + + if (! empty($chartofaccounts)) { + + if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } else { + $error ++; + } + } + + if ($action == 'disable') { + if ($accounting->fetch($id)) { + $result = $accounting->account_desactivate($id); + } + + $action = 'update'; + if ($result < 0) { + setEventMessages($accounting->error, $accounting->errors, 'errors'); + } + } else if ($action == 'enable') { + if ($accounting->fetch($id)) { + $result = $accounting->account_activate($id); + } + $action = 'update'; + if ($result < 0) { + setEventMessages($accounting->error, $accounting->errors, 'errors'); + } + } } @@ -124,6 +145,8 @@ if ($action == 'delete') { $pcgver = $conf->global->CHARTOFACCOUNTS; + + $sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.account_number, aa.account_parent , aa.label, aa.active, "; $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa"; @@ -152,17 +175,18 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = 0; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + $resql = $db->query($sql); + $nbtotalofrecords = $db->num_rows($resql); } $sql .= $db->plimit($limit + 1, $offset); dol_syslog('accountancy/admin/account.php:: $sql=' . $sql); -$result = $db->query($sql); +$resql = $db->query($sql); -if ($result) { - $num = $db->num_rows($result); +if ($resql) { + + $num = $db->num_rows($resql); $params=''; if ($search_account != "") $params.= '&search_account='.urlencode($search_account); @@ -172,13 +196,40 @@ if ($result) { if ($search_pcgsubtype != "") $params.= '&search_pcgsubtype='.urlencode($search_pcgsubtype); if ($optioncss != '') $param.='&optioncss='.$optioncss; - print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords); + print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy'); $i = 0; print '
'; - print '
'; + // Box to select active chart of accoun + $var = ! $var; + print $langs->trans("Selectchartofaccounts") . " : "; + print '"; + print ''; + print '
'; + print "
\n"; print '' . $langs->trans("Addanaccount") . ''; print '' . $langs->trans("ApplyMassCategories") . ''; @@ -194,7 +245,7 @@ if ($result) { print_liste_field_titre($langs->trans("Pcgtype"), $_SERVER["PHP_SELF"], "aa.pcg_type", "", $params, "", $sortfield, $sortorder); print_liste_field_titre($langs->trans("Pcgsubtype"), $_SERVER["PHP_SELF"], "aa.pcg_subtype", "", $params, "", $sortfield, $sortorder); print_liste_field_titre($langs->trans("Activated"), $_SERVER["PHP_SELF"], "aa.active", "", $params, "", $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Action"), $_SERVER["PHP_SELF"], "", $params, "", 'width="60" align="center"', $sortfield, $sortorder); + print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $params, "", 'width="60" align="center"', $sortfield, $sortorder); print ''; print ''; @@ -205,9 +256,8 @@ if ($result) { print ''; print ' '; print ''; - print ''; - print ' '; - print ''; + $searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + print $searchpitco; print ''; print ''; diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php new file mode 100644 index 00000000000..461bfbe3394 --- /dev/null +++ b/htdocs/accountancy/admin/accountmodel.php @@ -0,0 +1,1429 @@ + + * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2010-2016 Juanjo Menent + * Copyright (C) 2011-2015 Philippe Grand + * Copyright (C) 2011 Remy Younes + * Copyright (C) 2012-2015 Marcos García + * Copyright (C) 2012 Christophe Battarel + * Copyright (C) 2011-2016 Alexandre Spangaro + * Copyright (C) 2015 Ferran Marcet + * Copyright (C) 2016 Raphaël Doursenaud + * + * 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/accountancy/admin/accountmodel.php + * \ingroup Advanced accountancy + * \brief Page to administer model of chart of accounts + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +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 . '/accountancy/class/html.formventilation.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"); + +$action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; +$confirm=GETPOST('confirm','alpha'); +$id=GETPOST('id','int'); +$rowid=GETPOST('rowid','alpha'); + +$acts[0] = "activate"; +$acts[1] = "disable"; +$actl[0] = img_picto($langs->trans("Disabled"),'switch_off'); +$actl[1] = img_picto($langs->trans("Activated"),'switch_on'); + +$listoffset=GETPOST('listoffset'); +$listlimit=GETPOST('listlimit')>0?GETPOST('listlimit'):1000; +$active = 1; + +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if ($page == -1) { $page = 0 ; } +$offset = $listlimit * $page ; +$pageprev = $page - 1; +$pagenext = $page + 1; + +$search_country_id = GETPOST('search_country_id','int'); + + +// Security check +if ($user->societe_id > 0) accessforbidden(); +if (! $user->rights->accounting->chartofaccount) accessforbidden(); + + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('admin')); + +// This page is a generic page to edit dictionaries +// Put here declaration of dictionaries properties + +// Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. +$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,17,24,28,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,25,0,26,0,31,32,0); + +// Name of SQL tables of dictionaries +$tabname=array(); + +$tabname[31]= MAIN_DB_PREFIX."accounting_system"; +$tabname[32]= MAIN_DB_PREFIX."c_accounting_category"; + +// Dictionary labels +$tablib=array(); +$tablib[31]= "Pcg_version"; +$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[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 +$tabsqlsort=array(); +$tabsqlsort[31]="pcg_version ASC"; +$tabsqlsort[32]="position ASC"; + +// Nom des champs en resultat de select pour affichage du dictionnaire +$tabfield=array(); +$tabfield[31]= "pcg_version,label"; +$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[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[32]= "code,label,range_account,sens,category_type,formula,position,fk_country"; + +// Nom du rowid si le champ n'est pas de type autoincrement +// Example: "" if id field is "rowid" and has autoincrement on +// "nameoffield" if id field is not "rowid" or has not autoincrement on +$tabrowid=array(); +$tabrowid[31]= ""; +$tabrowid[32]= ""; + +// Condition to show dictionary in setup page +$tabcond=array(); +$tabcond[31]= ! empty($conf->accounting->enabled); +$tabcond[32]= ! empty($conf->accounting->enabled); + +// List of help for fields +$tabhelp=array(); +$tabhelp[31] = array('pcg_version'=>$langs->trans("EnterAnyCode")); +$tabhelp[32] = array('code'=>$langs->trans("EnterAnyCode")); + +// List of check for fields (NOT USED YET) +$tabfieldcheck=array(); +$tabfieldcheck[31] = array(); +$tabfieldcheck[32] = array(); + +// Complete all arrays with entries found into modules +complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort,$tabfield,$tabfieldvalue,$tabfieldinsert,$tabrowid,$tabcond,$tabhelp,$tabfieldcheck); + + +// Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") +$elementList = array(); +$sourceList=array(); +if ($id == 11) +{ + $langs->load("orders"); + $langs->load("contracts"); + $langs->load("projects"); + $langs->load("propal"); + $langs->load("bills"); + $langs->load("interventions"); + $elementList = array( + '' => '', + 'societe' => $langs->trans('ThirdParty'), +// 'proposal' => $langs->trans('Proposal'), +// 'order' => $langs->trans('Order'), +// 'invoice' => $langs->trans('Bill'), + 'invoice_supplier' => $langs->trans('SupplierBill'), + 'order_supplier' => $langs->trans('SupplierOrder'), +// 'intervention' => $langs->trans('InterventionCard'), +// 'contract' => $langs->trans('Contract'), + 'project' => $langs->trans('Project'), + 'project_task' => $langs->trans('Task'), + 'agenda' => $langs->trans('Agenda'), + // old deprecated + 'contrat' => $langs->trans('Contract'), + 'propal' => $langs->trans('Proposal'), + 'commande' => $langs->trans('Order'), + 'facture' => $langs->trans('Bill'), + 'resource' => $langs->trans('Resource'), +// 'facture_fourn' => $langs->trans('SupplierBill'), + 'fichinter' => $langs->trans('InterventionCard') + ); + if (! empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) $elementList["societe"] = $langs->trans('ThirdParty'); + + complete_elementList_with_modules($elementList); + + asort($elementList); + $sourceList = array( + 'internal' => $langs->trans('Internal'), + 'external' => $langs->trans('External') + ); +} +if ($id == 25) +{ + // We save list of template email Dolibarr can manage. This list can found by a grep into code on "->param['models']" + $elementList = array(); + if ($conf->propal->enabled) $elementList['propal_send']=$langs->trans('MailToSendProposal'); + if ($conf->commande->enabled) $elementList['order_send']=$langs->trans('MailToSendOrder'); + if ($conf->facture->enabled) $elementList['facture_send']=$langs->trans('MailToSendInvoice'); + if ($conf->expedition->enabled) $elementList['shipping_send']=$langs->trans('MailToSendShipment'); + if ($conf->ficheinter->enabled) $elementList['fichinter_send']=$langs->trans('MailToSendIntervention'); + if ($conf->supplier_proposal->enabled) $elementList['supplier_proposal_send']=$langs->trans('MailToSendSupplierRequestForQuotation'); + if ($conf->fournisseur->enabled) $elementList['order_supplier_send']=$langs->trans('MailToSendSupplierOrder'); + if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send']=$langs->trans('MailToSendSupplierInvoice'); + if ($conf->societe->enabled) $elementList['thirdparty']=$langs->trans('MailToThirdparty'); + + $parameters=array('elementList'=>$elementList); + $reshook=$hookmanager->executeHooks('emailElementlist',$parameters); // Note that $action and $object may have been modified by some hooks + if ($reshook == 0) { + foreach ($hookmanager->resArray as $item => $value) { + $elementList[$item] = $value; + } + } +} + +// Define localtax_typeList (used for dictionary "llx_c_tva") +$localtax_typeList = array(); +if ($id == 10) +{ + $localtax_typeList = array( + "0" => $langs->trans("No"), + "1" => $langs->trans("Yes").' ('.$langs->trans("Type")." 1)", //$langs->trans("%ageOnAllWithoutVAT"), + "2" => $langs->trans("Yes").' ('.$langs->trans("Type")." 2)", //$langs->trans("%ageOnAllBeforeVAT"), + "3" => $langs->trans("Yes").' ('.$langs->trans("Type")." 3)", //$langs->trans("%ageOnProductsWithoutVAT"), + "4" => $langs->trans("Yes").' ('.$langs->trans("Type")." 4)", //$langs->trans("%ageOnProductsBeforeVAT"), + "5" => $langs->trans("Yes").' ('.$langs->trans("Type")." 5)", //$langs->trans("%ageOnServiceWithoutVAT"), + "6" => $langs->trans("Yes").' ('.$langs->trans("Type")." 6)" //$langs->trans("%ageOnServiceBeforeVAT"), + ); +} + + + +/* + * Actions + */ + +if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x')) +{ + $search_country_id = ''; +} + +// Actions add or modify an entry into a dictionary +if (GETPOST('actionadd') || GETPOST('actionmodify')) +{ + $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); + $listfieldinsert=explode(',',$tabfieldinsert[$id]); + $listfieldmodify=explode(',',$tabfieldinsert[$id]); + $listfieldvalue=explode(',',$tabfieldvalue[$id]); + + // Check that all fields are filled + $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' && 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; + if ($value == 'color' && empty($_POST['color'])) continue; + if ($value == 'formula' && empty($_POST['formula'])) continue; + if ((! isset($_POST[$value]) || $_POST[$value]=='') + && (! in_array($listfield[$f], array('decalage','module','accountancy_code','accountancy_code_sell','accountancy_code_buy')) // Fields that are not mandatory + && (! ($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 + ) + ) + { + $ok=0; + $fieldnamekey=$listfield[$f]; + // We take translate key of field + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; + if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; + if ($fieldnamekey == 'nbjour') $fieldnamekey='NbOfDays'; + if ($fieldnamekey == 'decalage') $fieldnamekey='Offset'; + if ($fieldnamekey == 'module') $fieldnamekey='Module'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; + if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; + if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; + if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; + if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; + if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; + if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; + if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated'; + + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + } + } + // Other checks + if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"],array('system','systemauto'))) { + $ok=0; + setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); + } + if (isset($_POST["code"])) + { + if ($_POST["code"]=='0') + { + $ok=0; + setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); + } + /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base + { + $ok = 0; + $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; + }*/ + } + if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2)) + { + if (in_array($tablib[$id],array('DictionaryCompanyType','DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries + { + $_POST["country"]=''; + } + else + { + $ok=0; + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors'); + } + } + if ($id == 3 && ! is_numeric($_POST["code"])) + { + $ok=0; + setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric",$langs->transnoentities("Code")), null, 'errors'); + } + + // Clean some parameters + if (isset($_POST["localtax1"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0'; // If empty, we force to 0 + if (isset($_POST["localtax2"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0'; // If empty, we force to 0 + if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null + if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null + if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null + + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd')) + { + if ($tabrowid[$id]) + { + // Recupere id libre pour insertion + $newid=0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid=($obj->newid + 1); + + } else { + dol_print_error($db); + } + } + + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $tabrowid[$id].","; + $sql.= $tabfieldinsert[$id]; + $sql.=",active)"; + $sql.= " VALUES("; + + // List of values + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert)) + $sql.= $newid.","; + $i=0; + foreach ($listfieldinsert as $f => $value) + { + if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($value == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.=",1)"; + + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST=array('id'=>$id); // Clean $_POST array, we keep only + } + else + { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } + else { + dol_print_error($db); + } + } + } + + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify')) + { + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } + + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify)) + { + $sql.= $tabrowid[$id]."="; + $sql.= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { + $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); + } + else if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql.=","; + $sql.= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if (! $resql) + { + setEventMessages($db->error(), null, 'errors'); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition +} + +if (GETPOST('actioncancel')) +{ + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition +} + +if ($action == 'confirm_delete' && $confirm == 'yes') // delete +{ + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } + + $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; + + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (! $result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } + else + { + dol_print_error($db); + } + } +} + +// activate +if ($action == $acts[0]) +{ + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } + + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($_GET["code"]) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$_GET["code"]."'"; + } + + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } +} + +// disable +if ($action == $acts[1]) +{ + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } + + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($_GET["code"]) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$_GET["code"]."'"; + } + + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } +} + +// favorite +if ($action == 'activate_favorite') +{ + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } + + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($_GET["code"]) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$_GET["code"]."'"; + } + + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } +} + +// disable favorite +if ($action == 'disable_favorite') +{ + if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } + else { $rowidcol="rowid"; } + + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; + } + elseif ($_GET["code"]) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$_GET["code"]."'"; + } + + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } +} + + +/* + * View + */ + +$form = new Form($db); +$formadmin=new FormAdmin($db); + +llxHeader(); + +$titre=$langs->trans($tablib[$id]); +$linkback=''; + +print load_fiche_titre($titre,$linkback,'title_accountancy'); + +if (empty($id)) +{ + print $langs->trans("DictionaryDesc"); + print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; +} +print "
\n"; + + +// Confirmation de la suppression de la ligne +if ($action == 'delete') +{ + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$_GET["code"].'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1); +} +//var_dump($elementList); + +/* + * Show a dictionary + */ +if ($id) +{ + // Complete requete recherche valeurs avec critere de tri + $sql=$tabsql[$id]; + + if ($search_country_id > 0) + { + if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; + else $sql.=" WHERE "; + $sql.= " c.rowid = ".$search_country_id; + } + + if ($sortfield) + { + // If sort order is "country", we use country_code instead + if ($sortfield == 'country') $sortfield='country_code'; + $sql.= " ORDER BY ".$sortfield; + if ($sortorder) + { + $sql.=" ".strtoupper($sortorder); + } + $sql.=", "; + // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]); + $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]); + } + else { + $sql.=" ORDER BY "; + } + $sql.=$tabsqlsort[$id]; + $sql.=$db->plimit($listlimit+1,$offset); + //print $sql; + + $fieldlist=explode(',',$tabfield[$id]); + + print ''; + print ''; + + print ''; + + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused=0; + $var=false; + + $fieldlist=explode(',',$tabfield[$id]); + + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + $align="left"; + if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } + if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } + if ($fieldlist[$field]=='taux') { + if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); + else $valuetoshow=$langs->trans("Amount"); + $align='right'; + } + if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2";} + if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3";} + if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } + if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='type') { + if ($tabname[$id] == MAIN_DB_PREFIX."c_paiement") $valuetoshow=$form->textwithtooltip($langs->trans("Type"),$langs->trans("TypePaymentDesc"),2,1,img_help(1,'')); + else $valuetoshow=$langs->trans("Type"); + } + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + if ($id != 25) $valuetoshow.="*"; + } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='country') { + if (in_array('region_id',$fieldlist)) { print ''; continue; } // For region page, we do not show the country input + $valuetoshow=$langs->trans("Country"); + } + if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } + if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } + if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } + if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } + if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } + if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $valuetoshow=''; } + if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } + if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); } + if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); } + if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } + if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountparent"); } + if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } + if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } + if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } + if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } + if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } + if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } + if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } + if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } + + if ($id == 2) // Special cas for state page + { + if ($fieldlist[$field]=='region_id') { $valuetoshow=' '; $showfield=1; } + if ($fieldlist[$field]=='region') { $valuetoshow=$langs->trans("Country").'/'.$langs->trans("Region"); $showfield=1; } + } + + if ($valuetoshow != '') + { + print ''; + } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + } + + if ($id == 4) print ''; + print ''; + print ''; + print ''; + print ''; + + // Line to enter new values + print ""; + + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val)) + $obj->$val=GETPOST($val); + } + } + + $tmpaction = 'create'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; + + if ($id == 3) unset($fieldlist[2]); + + if (empty($reshook)) + { + if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates' && $action == 'edit') + { + fieldList($fieldlist,$obj,$tabname[$id],'hide'); + } + else + { + fieldList($fieldlist,$obj,$tabname[$id],'add'); + } + } + + if ($id == 4) print ''; + print ''; + print ""; + + if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates') + { + print ''; + } + + $colspan=count($fieldlist)+3; + if ($id == 4) $colspan++; + + if (! empty($alabelisused) && $id != 25) // If there is one label among fields, we show legend of * + { + print ''; + } + print ''; // Keep   to have a line with enough height + } + + + + // List of available values in database + dol_syslog("htdocs/admin/dict", LOG_DEBUG); + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + $var=true; + + $param = '&id='.$id; + if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + $paramwithsearch = $param; + if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; + + // There is several pages + if ($num > $listlimit) + { + print ''; + } + + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield=1; // By defaut + $align="left"; + $sortable=1; + $valuetoshow=''; + /* + $tmparray=getLabelOfField($fieldlist[$field]); + $showfield=$tmp['showfield']; + $valuetoshow=$tmp['valuetoshow']; + $align=$tmp['align']; + $sortable=$tmp['sortable']; + */ + $valuetoshow=ucfirst($fieldlist[$field]); // By defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } + if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } + if ($fieldlist[$field]=='taux') { + if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); + else $valuetoshow=$langs->trans("Amount"); + $align='right'; + } + if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $sortable=0; } + if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $sortable=0; } + if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } + if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + if ($id != 25) $valuetoshow.="*"; + } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='country') { $valuetoshow=$langs->trans("Country"); } + if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } + if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } + if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } + if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } + if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } + if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } + if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); $sortable=0; } + if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); $sortable=0; } + if ($fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } + if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountsparent"); } + if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } + if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } + if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } + if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } + if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } + if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } + if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } + if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } + + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); + } + } + // Favorite - Only activated on country dictionary + if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); + + print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; + + // Title line with search boxes + print ''; + foreach ($fieldlist as $field => $value) + { + $showfield=1; // By defaut + + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + + if ($showfield) + { + if ($value == 'country') + { + print ''; + } + else + { + print ''; + } + } + } + if ($id == 4) print ''; + print ''; + print ''; + print ''; + + if ($num) + { + // Lines with values + while ($i < $num) + { + $var = ! $var; + + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + { + print ''; + print ''; + print ''; + print ''; + + $tmpaction='edit'; + $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error=$hookmanager->error; $errors=$hookmanager->errors; + + if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit'); + + print ''; + } + else + { + $tmpaction = 'view'; + $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + + $error=$hookmanager->error; $errors=$hookmanager->errors; + + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { + + $showfield=1; + $align="left"; + $valuetoshow=$obj->{$fieldlist[$field]}; + if ($value == 'type_template') + { + $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + } + if ($value == 'element') + { + $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + } + else if ($value == 'source') + { + $valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow; + } + else if ($valuetoshow=='all') { + $valuetoshow=$langs->trans('All'); + } + else if ($fieldlist[$field]=='country') { + if (empty($obj->country_code)) + { + $valuetoshow='-'; + } + else + { + $key=$langs->trans("Country".strtoupper($obj->country_code)); + $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); + } + } + else if ($fieldlist[$field]=='recuperableonly' || $fieldlist[$field]=='type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + if(empty($valuetoshow)) $valuetoshow = $langs->trans('None'); + elseif($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); + elseif($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); + $align="center"; + } + else if ($fieldlist[$field]=='price' || preg_match('/^amount/i',$fieldlist[$field])) { + $valuetoshow=price($valuetoshow); + } + else if ($fieldlist[$field]=='libelle_facture') { + $langs->load("bills"); + $key=$langs->trans("PaymentCondition".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentCondition".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + $valuetoshow=nl2br($valuetoshow); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_country') { + $key=$langs->trans("Country".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Country".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_availability') { + $langs->load("propal"); + $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_actioncomm') { + $key=$langs->trans("Action".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Action".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if (! empty($obj->code_iso) && $fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_currencies') { + $key=$langs->trans("Currency".strtoupper($obj->code_iso)); + $valuetoshow=($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_typent') { + $key=$langs->trans(strtoupper($obj->code)); + $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_prospectlevel') { + $key=$langs->trans(strtoupper($obj->code)); + $valuetoshow=($key != strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_civility') { + $key=$langs->trans("Civility".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "Civility".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_type_contact') { + $langs->load('agenda'); + $key=$langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_payment_term') { + $langs->load("bills"); + $key=$langs->trans("PaymentConditionShort".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paiement') { + $langs->load("bills"); + $key=$langs->trans("PaymentType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "PaymentType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_reason') { + $key=$langs->trans("DemandReasonType".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "DemandReasonType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_input_method') { + $langs->load("orders"); + $key=$langs->trans($obj->code); + $valuetoshow=($obj->code && $key != $obj->code)?$key:$obj->{$fieldlist[$field]}; + } + else if ($fieldlist[$field]=='libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_shipment_mode') { + $langs->load("sendings"); + $key=$langs->trans("SendingMethod".strtoupper($obj->code)); + $valuetoshow=($obj->code && $key != "SendingMethod".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field] == 'libelle' && $tabname[$id]==MAIN_DB_PREFIX.'c_paper_format') + { + $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') + { + $langs->load('trips'); + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { + $showfield=0; + } + else if ($fieldlist[$field]=='unicode') { + $valuetoshow = $langs->getCurrencySymbol($obj->code,1); + } + else if ($fieldlist[$field]=='label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow=$langs->trans($obj->{$fieldlist[$field]}); + } + else if ($fieldlist[$field]=='short_label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); + } + else if (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) + { + $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); + $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); + } + + else if ($fieldlist[$field]=='localtax1_type') { + if ($obj->localtax1 != 0) + $valuetoshow=$localtax_typeList[$valuetoshow]; + else + $valuetoshow = ''; + $align="right"; + } + else if ($fieldlist[$field]=='localtax2_type') { + if ($obj->localtax2 != 0) + $valuetoshow=$localtax_typeList[$valuetoshow]; + else + $valuetoshow = ''; + $align="right"; + } + else if ($fieldlist[$field]=='taux') { + $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); + $align="right"; + } + else if (in_array($fieldlist[$field],array('recuperableonly'))) + { + $align="center"; + } + else if ($fieldlist[$field]=='accountancy_code' || $fieldlist[$field]=='accountancy_code_sell' || $fieldlist[$field]=='accountancy_code_buy') { + $valuetoshow = length_accountg($valuetoshow); + } + + $class='tddict'; + if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto'; + // Show value for field + if ($showfield) print ''; + } + } + + // Can an entry be erased or disabled ? + $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + if (isset($obj->code) && $id != 10) + { + if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } + else if ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } + } + + if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable=0; } + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled=0; $canbedisabled = 0; } + $canbemodified=$iserasable; + if ($obj->code == 'RECEP') $canbemodified=1; + + $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + if ($param) $url .= '&'.$param; + $url.='&'; + + // Favorite + // Only activated on country dictionary + if ($id == 4) + { + print ''; + } + + // Active + print '"; + + // Modify link + if ($canbemodified) print ''; + else print ''; + + // Delete link + if ($iserasable) print ''; + else print ''; + + print "\n"; + } + $i++; + } + } + } + else { + dol_print_error($db); + } + + print '
 '; + if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1,$valuetoshow).''; + else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]); + else print $valuetoshow; + print ''; + print ''; + print '
'; + if ($tabname[$id] != MAIN_DB_PREFIX.'c_email_templates' || $action != 'edit') + { + print ''; + } + print '
* '.$langs->trans("AvailableVariables").": "; + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; + $formmail=new FormMail($db); + $tmp=$formmail->getAvailableSubstitKey('form'); + print implode(', ', $tmp); + print '
* '.$langs->trans("LabelUsedByDefault").'.
 
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone'); + print ''; + $searchpitco=$form->showFilterAndCheckAddButtons(0); + print $searchpitco; + print '
 '; + print ' '.$valuetoshow.''; + if ($iserasable) print ''.$actl[$obj->favorite].''; + else print $langs->trans("AlwaysActive"); + print ''; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else + { + if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); + else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); + else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); + else print $langs->trans("AlwaysActive"); + } + print "'.img_edit().' '.img_delete().' 
'; + + print ''; +} +else +{ + /* + * Show list of dictionary to show + */ + + $var=true; + $lastlineisempty=false; + print ''; + print ''; + //print ''; + print ''; + print ''; + print ''; + + $showemptyline=''; + foreach ($taborder as $i) + { + if (isset($tabname[$i]) && empty($tabcond[$i])) continue; + + if ($i) + { + if ($showemptyline) + { + $var=!$var; + print ''; + $showemptyline=0; + } + + $var=!$var; + $value=$tabname[$i]; + print ''; + print ''; + print ''; + $lastlineisempty=false; + } + else + { + if (! $lastlineisempty) + { + $showemptyline=1; + $lastlineisempty=true; + } + } + } + print '
'.$langs->trans("Module").''.$langs->trans("Dictionary").''.$langs->trans("Table").'
   
'; + if (! empty($tabcond[$i])) + { + print ''.$langs->trans($tablib[$i]).''; + } + else + { + print $langs->trans($tablib[$i]); + } + print ''; + /*if (empty($tabcond[$i])) + { + print info_admin($langs->trans("DictionaryDisabledSinceNoModuleNeedIt"),1); + }*/ + print ''.$tabname[$i].'
'; +} + +print '
'; + + +llxFooter(); +$db->close(); + + +/** + * Show fields in insert/edit mode + * + * @param array $fieldlist Array of fields + * @param Object $obj If we show a particular record, obj is filled with record fields + * @param string $tabname Name of SQL table + * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered + * @return void + */ +function fieldList($fieldlist, $obj='', $tabname='', $context='') +{ + global $conf,$langs,$db; + global $form; + global $region_id; + global $elementList,$sourceList,$localtax_typeList; + global $bc; + + $formadmin = new FormAdmin($db); + $formcompany = new FormCompany($db); + if (! empty($conf->accounting->enabled)) $formaccountancy = new FormVentilation($db); + + foreach ($fieldlist as $field => $value) + { + if ($fieldlist[$field] == 'country') + { + if (in_array('region_id',$fieldlist)) + { + print ''; + //print join(',',$fieldlist); + print ''; + continue; + } // For state page, we do not show the country input (we link to region, not country) + print ''; + $fieldname='country'; + print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:'')), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); + print ''; + } + elseif ($fieldlist[$field] == 'country_id') + { + if (! in_array('country',$fieldlist)) // If there is already a field country, we don't show country_id (avoid duplicate) + { + $country_id = (! empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0); + print ''; + print ''; + print ''; + } + } + elseif ($fieldlist[$field] == 'region') + { + print ''; + $formcompany->select_region($region_id,'region'); + print ''; + } + elseif ($fieldlist[$field] == 'region_id') + { + $region_id = (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:0); + print ''; + print ''; + print ''; + } + elseif ($fieldlist[$field] == 'lang') + { + print ''; + print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT,'lang'); + print ''; + } + // Le type de template + elseif ($fieldlist[$field] == 'type_template') + { + print ''; + print $form->selectarray('type_template', $elementList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + print ''; + } + // Le type de l'element (pour les type de contact) + elseif ($fieldlist[$field] == 'element') + { + print ''; + print $form->selectarray('element', $elementList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + print ''; + } + // La source de l'element (pour les type de contact) + elseif ($fieldlist[$field] == 'source') + { + print ''; + print $form->selectarray('source', $sourceList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + print ''; + } + elseif ($fieldlist[$field] == 'type' && $tabname == MAIN_DB_PREFIX."c_actioncomm") + { + print ''; + print 'user'; + print ''; + } + elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + if ($fieldlist[$field] == 'type_cdr') print ''; + else print ''; + if ($fieldlist[$field] == 'type_cdr') { + print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + } else { + print $form->selectyesno($fieldlist[$field],(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''),1); + } + print ''; + } + elseif (in_array($fieldlist[$field],array('nbjour','decalage','taux','localtax1','localtax2'))) { + $align="left"; + if (in_array($fieldlist[$field],array('taux','localtax1','localtax2'))) $align="right"; // Fields aligned on right + print ''; + print ''; + print ''; + } + elseif (in_array($fieldlist[$field], array('libelle_facture'))) { + print ''; + } + elseif (in_array($fieldlist[$field], array('content'))) + { + if ($tabname == MAIN_DB_PREFIX.'c_email_templates') + { + print ''; // To create an artificial CR for the current tr we are on + } + else print ''; + if ($context != 'hide') + { + //print ''; + $okforextended=true; + if ($tabname == MAIN_DB_PREFIX.'c_email_templates' && empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended=false; + $doleditor = new DolEditor($fieldlist[$field], (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_5, '90%'); + print $doleditor->Create(1); + } + else print ' '; + print ''; + } + elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i',$fieldlist[$field])) { + print ''; + } + elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) { + print ''; + } + elseif ($fieldlist[$field]=='unit') { + print ''; + $units = array( + 'mm' => $langs->trans('SizeUnitmm'), + 'cm' => $langs->trans('SizeUnitcm'), + 'point' => $langs->trans('SizeUnitpoint'), + 'inch' => $langs->trans('SizeUnitinch') + ); + print $form->selectarray('unit', $units, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 0, 0, 0); + print ''; + } + // Le type de taxe locale + elseif ($fieldlist[$field] == 'localtax1_type' || $fieldlist[$field] == 'localtax2_type') + { + print ''; + print $form->selectarray($fieldlist[$field], $localtax_typeList, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + print ''; + } + elseif ($fieldlist[$field] == 'accountancy_code' || $fieldlist[$field] == 'accountancy_code_sell' || $fieldlist[$field] == 'accountancy_code_buy') + { + print ''; + if (! empty($conf->accounting->enabled)) + { + $accountancy_account = (! empty($obj->$fieldlist[$field]) ? $obj->$fieldlist[$field] : 0); + print $formaccountancy->select_account($accountancy_account, $fieldlist[$field], 1, '', 1, 1, 'maxwidth200 maxwidthonsmartphone'); + } + else + { + print ''; + } + print ''; + } + else + { + print ''; + $size=''; $class=''; + if ($fieldlist[$field]=='code') $size='size="8" '; + if ($fieldlist[$field]=='position') $size='size="4" '; + if ($fieldlist[$field]=='libelle') $size='centpercent'; + if ($fieldlist[$field]=='tracking') $class='centpercent'; + if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" '; + print ''; + print ''; + } + } +} + diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index 057e2f0484c..822a4d19bcd 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -19,12 +19,11 @@ /** * \file htdocs/accountancy/admin/card.php - * \ingroup Advanced accountancy + * \ingroup Advanced accountancy * \brief Card of accounting account */ -require '../../main.inc.php'; -// Class +require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT . '/accountancy/class/html.formventilation.class.php'; @@ -38,18 +37,30 @@ $langs->load("accountancy"); $mesg = ''; $action = GETPOST('action'); +$backtopage = GETPOST('backtopage'); $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); $cancel = GETPOST('cancel'); // Security check -if (! $user->admin) - accessforbidden(); + $object = new AccountingAccount($db); -// Action -if ($action == 'add') { + +/* + * Action + */ + +if (GETPOST('cancel')) +{ + $urltogo=$backtopage?$backtopage:dol_buildpath('/accountancy/admin/account.php',1); + header("Location: ".$urltogo); + exit; +} + +if ($action == 'add' && $user->rights->accounting->chartofaccount) +{ if (! $cancel) { $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; @@ -85,19 +96,31 @@ if ($action == 'add') { $object->active = 1; $res = $object->create($user); - if ($res == - 3) { $error = 1; $action = "create"; + setEventMessages($object->error, $object->errors, 'errors'); } - if ($res == - 4) { + elseif ($res == - 4) { $error = 2; $action = "create"; + setEventMessages($object->error, $object->errors, 'errors'); + } + elseif ($res < 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } + if (! $error) + { + setEventMessages("RecordCreatedSuccessfully",null,'mesgs'); + $urltogo=$backtopage?$backtopage:dol_buildpath('/accountancy/admin/account.php',1); + header("Location: ".$urltogo); + exit; } } - header("Location: account.php"); - exit; -} else if ($action == 'edit') { +} else if ($action == 'edit' && $user->rights->accounting->chartofaccount) { if (! $cancel) { $result = $object->fetch($id); @@ -145,7 +168,7 @@ if ($action == 'add') { header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); exit(); } -} else if ($action == 'delete') { +} else if ($action == 'delete' && $user->rights->accounting->chartofaccount) { $result = $object->fetch($id); if (! empty($object->id)) { @@ -175,7 +198,7 @@ $formaccounting = new FormAccounting($db); // Create mode if ($action == 'create') { - print load_fiche_titre($langs->trans('NewAccount')); + print load_fiche_titre($langs->trans('NewAccountingAccount')); print '
' . "\n"; print ''; @@ -329,14 +352,14 @@ if ($action == 'create') { print '' . $object->pcg_subtype . ''; // Active - print '' . $langs->trans("Activated") . ''; + print '' . $langs->trans("Status") . ''; print ''; - - if (empty($object->active)) { + print $object->getLibStatut(4); + /*if (empty($object->active)) { print img_picto($langs->trans("Disabled"), 'switch_off'); } else { print img_picto($langs->trans("Activated"), 'switch_on'); - } + }*/ print ''; @@ -350,13 +373,13 @@ if ($action == 'create') { print '
'; - if ($user->admin) { + if (! empty($user->rights->accounting->chartofaccount)) { print '' . $langs->trans('Modify') . ''; } else { print '' . $langs->trans('Modify') . ''; } - if ($user->admin) { + if (! empty($user->rights->accounting->chartofaccount)) { print '' . $langs->trans('Delete') . ''; } else { print '' . $langs->trans('Delete') . ''; diff --git a/htdocs/accountancy/admin/categories.php b/htdocs/accountancy/admin/categories.php index e1a0e3fe052..12d9a707cbd 100644 --- a/htdocs/accountancy/admin/categories.php +++ b/htdocs/accountancy/admin/categories.php @@ -79,9 +79,11 @@ if ($action == 'delete') { } } + /* * View */ + llxheader('', $langs->trans('AccountAccounting')); $formaccounting = new FormAccounting($db); @@ -126,6 +128,7 @@ dol_fiche_end(); print ''; + if ($action == 'display' || $action == 'delete') { print ''; diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php new file mode 100644 index 00000000000..6854c8a45ff --- /dev/null +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -0,0 +1,156 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2016 Alexandre Spangaro + * Copyright (C) 2014-2015 Ari Elbaz (elarifr) + * Copyright (C) 2014 Marcos García + * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2015 Jean-François Ferry + * + * 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/accountancy/admin/index.php + * \ingroup Advanced accountancy + * \brief Setup page to configure accounting expert module + */ +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/html.formventilation.class.php'; + +$langs->load("compta"); +$langs->load("bills"); +$langs->load("admin"); +$langs->load("accountancy"); +$langs->load("salaries"); + +// Security check +if (! empty($user->rights->accountancy->chartofaccount)) +{ + accessforbidden(); +} + +$action = GETPOST('action', 'alpha'); + + +$list_account = array ( + 'ACCOUNTING_ACCOUNT_SUPPLIER', + 'ACCOUNTING_ACCOUNT_CUSTOMER', + 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', + 'ACCOUNTING_PRODUCT_BUY_ACCOUNT', + 'ACCOUNTING_PRODUCT_SOLD_ACCOUNT', + 'ACCOUNTING_SERVICE_BUY_ACCOUNT', + 'ACCOUNTING_SERVICE_SOLD_ACCOUNT', + 'ACCOUNTING_VAT_BUY_ACCOUNT', + 'ACCOUNTING_VAT_SOLD_ACCOUNT', + 'ACCOUNTING_VAT_PAY_ACCOUNT', + 'ACCOUNTING_ACCOUNT_SUSPENSE', + 'ACCOUNTING_ACCOUNT_TRANSFER_CASH', + 'DONATION_ACCOUNTINGACCOUNT' +); + + +/* + * Actions + */ + +$accounting_mode = defined('ACCOUNTING_MODE') ? ACCOUNTING_MODE : 'RECETTES-DEPENSES'; + + +if (GETPOST('change_chart')) +{ + $chartofaccounts = GETPOST('chartofaccounts', 'int'); + + if (! empty($chartofaccounts)) { + + if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } else { + $error ++; + } +} + +if ($action == 'update') { + $error = 0; + + foreach ( $list_account as $constname ) { + $constvalue = GETPOST($constname, 'alpha'); + + if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } + + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } +} + + +/* + * View + */ + +llxHeader(); + +$form = new Form($db); +$formaccountancy = new FormVentilation($db); + +$linkback = ''; +print load_fiche_titre($langs->trans('MenuDefaultAccounts'), $linkback, 'title_accountancy'); + +print '
'; +print $langs->trans("DefaultBindingDesc").'
'; +print '
'; + +print '
'; +print ''; +print ''; + +// Define Chart of accounts + +print '
'; + +foreach ( $list_account as $key ) { + $var = ! $var; + + print ''; + // Param + $label = $langs->trans($key); + print ''; + // Value + print ''; + print ''; +} + + +print "
' . $label . ''; // Do not force align=right, or it align also the content of the select box + print $formaccountancy->select_account($conf->global->$key, $key, 1, '', 1, 1); + print '
\n"; + + +print '
'; + +print ''; + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/admin/export.php b/htdocs/accountancy/admin/export.php index 3cb9f407ce6..9e57830b94d 100644 --- a/htdocs/accountancy/admin/export.php +++ b/htdocs/accountancy/admin/export.php @@ -38,8 +38,10 @@ $langs->load("admin"); $langs->load("accountancy"); // Security check -if (! $user->admin) - accessforbidden(); +if (empty($user->admin) || ! empty($user->rights->accountancy->chartofaccount)) +{ + accessforbidden(); +} $action = GETPOST('action', 'alpha'); @@ -135,31 +137,14 @@ $var = true; /* * Main Options */ + print ''; print ''; -print ''; +print ''; print "\n"; $var = ! $var; -print ''; -print ''; -if (! $conf->use_javascript_ajax) { - print '"; -} else { - print ''; -} -print ""; - $num = count($main_option); if ($num) { foreach ( $main_option as $key ) { @@ -221,8 +206,29 @@ if ($num2) { print ''; print ''; print "\n"; + if ($conf->global->ACCOUNTING_EXPORT_MODELCSV > 1) + { print ''; + } + + print ''; + print ''; + if (! $conf->use_javascript_ajax) { + print '"; + } else { + print ''; + } + print ""; foreach ( $model_option as $key ) { $var = ! $var; diff --git a/htdocs/accountancy/admin/fiscalyear.php b/htdocs/accountancy/admin/fiscalyear.php index 638e9794fe8..4127f5e4ee2 100644 --- a/htdocs/accountancy/admin/fiscalyear.php +++ b/htdocs/accountancy/admin/fiscalyear.php @@ -16,12 +16,12 @@ */ /** - * \file htdocs/accountancy/admin/fiscalyear.php - * \ingroup fiscal year - * \brief Setup page to configure fiscal year + * \file htdocs/accountancy/admin/fiscalyear.php + * \ingroup Advanced accountancy + * \brief Setup page to configure fiscal year */ -require '../../main.inc.php'; +require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/fiscalyear.class.php'; @@ -45,9 +45,9 @@ $langs->load("compta"); // Security check if ($user->societe_id > 0) accessforbidden(); -if (! $user->rights->accounting->fiscalyear) - accessforbidden(); - +if (! $user->rights->accounting->fiscalyear) // If we can read accounting records, we shoul be able to see fiscal year. + accessforbidden(); + $error = 0; // List of status @@ -65,6 +65,7 @@ $errors = array (); $object = new Fiscalyear($db); + /* * Actions */ @@ -79,9 +80,9 @@ $max = 100; $form = new Form($db); -$title = $langs->trans('FiscalYears'); - -llxHeader('', $title, LOG_ERR); +$title = $langs->trans('AccountingPeriods'); +$helpurl = ""; +llxHeader('', $title, $helpurl); $sql = "SELECT f.rowid, f.label, f.date_start, f.date_end, f.statut, f.entity"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_fiscalyear as f"; @@ -94,7 +95,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); -} +} $sql.= $db->plimit($limit+1, $offset); @@ -102,12 +103,12 @@ $result = $db->query($sql); if ($result) { $var = false; $num = $db->num_rows($result); - + $i = 0; - $title = $langs->trans('FiscalYears'); - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic', 0, '', '', $limit, 1); - + $title = $langs->trans('AccountingPeriods'); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit, 1); + // Load attribute_label print '
' . $langs->trans('MainOptions') . '' . $langs->trans('Options') . '
' . $langs->trans("Selectformat") . ''; - print $langs->trans("NotAvailableWhenAjaxDisabled"); - print "'; - $listformat = array ( - 'csv' => $langs->trans("csv"), - 'txt' => $langs->trans("txt") - ); - print $form->selectarray("format", $listformat, $conf->global->ACCOUNTING_EXPORT_FORMAT, 0); - - print '
' . $langs->trans('OtherOptions') . '
' . $langs->trans('OptionsDeactivatedForThisExportModel') . '
' . $langs->trans("Selectformat") . ''; + print $langs->trans("NotAvailableWhenAjaxDisabled"); + print "'; + $listformat = array ( + 'csv' => $langs->trans("csv"), + 'txt' => $langs->trans("txt") + ); + print $form->selectarray("format", $listformat, $conf->global->ACCOUNTING_EXPORT_FORMAT, 0); + + print '
'; print ''; @@ -117,10 +118,10 @@ if ($result) { print ''; print ''; print ''; - + if ($num) { $fiscalyearstatic = new Fiscalyear($db); - + while ( $i < $num && $i < $max ) { $obj = $db->fetch_object($result); $fiscalyearstatic->id = $obj->rowid; @@ -137,7 +138,6 @@ if ($result) { } else { print ''; } - print '
' . $langs->trans("DateEnd") . '' . $langs->trans("Statut") . '
' . $langs->trans("None") . '
'; } else { dol_print_error($db); @@ -147,7 +147,14 @@ dol_fiche_end(); // Buttons print '
'; -print '' . $langs->trans("NewFiscalYear") . ''; +if (! empty($user->rights->accounting->fiscalyear)) +{ + print '' . $langs->trans("NewFiscalYear") . ''; +} +else +{ + print '' . $langs->trans("NewFiscalYear") . ''; +} print '
'; llxFooter(); diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php index c45700ce4f5..7c5c6d08c73 100644 --- a/htdocs/accountancy/admin/fiscalyear_card.php +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -16,8 +16,9 @@ */ /** - * \file htdocs/accountancy/admin/fiscalyear_card.php - * \brief Page to show a fiscal year + * \file htdocs/accountancy/admin/fiscalyear_card.php + * \ingroup Advanced accountancy + * \brief Page to show a fiscal year */ require '../../main.inc.php'; @@ -28,7 +29,9 @@ $langs->load("admin"); $langs->load("compta"); // Security check -if (! $user->admin) +if ($user->societe_id > 0) + accessforbidden(); +if (empty($user->rights->accounting->fiscalyear)) accessforbidden(); $error = 0; @@ -71,13 +74,13 @@ if ($action == 'confirm_delete' && $confirm == "yes") { else if ($action == 'add') { if (! GETPOST('cancel', 'alpha')) { $error = 0; - + $object->date_start = $date_start; $object->date_end = $date_end; $object->label = GETPOST('label', 'alpha'); $object->statut = GETPOST('statut', 'int'); $object->datec = dol_now(); - + if (empty($object->date_start) && empty($object->date_end)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); $error ++; @@ -86,20 +89,20 @@ else if ($action == 'add') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); $error ++; } - + if (! $error) { $db->begin(); - + $id = $object->create($user); - + if ($id > 0) { $db->commit(); - + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); exit(); } else { $db->rollback(); - + setEventMessages($object->error, $object->errors, 'errors'); $action = 'create'; } @@ -116,12 +119,12 @@ else if ($action == 'add') { else if ($action == 'update') { if (! GETPOST('cancel', 'alpha')) { $result = $object->fetch($id); - + $object->date_start = empty($_POST["fiscalyear"]) ? '' : $date_start; $object->date_end = empty($_POST["fiscalyearend"]) ? '' : $date_end; $object->label = GETPOST('label', 'alpha'); $object->statut = GETPOST('statut', 'int'); - + $result = $object->update($user); if ($result > 0) { @@ -136,108 +139,112 @@ else if ($action == 'update') { } } + + /* * View */ -llxHeader(); +$title = $langs->trans("Fiscalyear") . " - " . $langs->trans("Card"); +$helpurl = ""; +llxHeader("",$title,$helpurl); $form = new Form($db); if ($action == 'create') { print load_fiche_titre($langs->trans("NewFiscalYear")); - + print '
'; print ''; print ''; - + dol_fiche_head(); - + print ''; - + // Label - print ''; - + print ''; + // Date start print ''; - + // Date end print ''; - + // Statut print ''; print ''; print ''; - + print '
' . $langs->trans("Label") . '
' . $langs->trans("Label") . '
' . $langs->trans("DateStart") . ''; print $form->select_date(($date_start ? $date_start : ''), 'fiscalyear'); print '
' . $langs->trans("DateEnd") . ''; print $form->select_date(($date_end ? $date_end : - 1), 'fiscalyearend'); print '
' . $langs->trans("Status") . ''; print $form->selectarray('statut', $statut2label, GETPOST('statut')); print '
'; - + dol_fiche_end(); - + print '
'; print ''; print '     '; print ''; print '
'; - + print '
'; } else if ($id) { $result = $object->fetch($id); if ($result > 0) { $head = fiscalyear_prepare_head($object); - + if ($action == 'edit') { - dol_fiche_head($head, 'card', $langs->trans("FiscalYearCard"), 0, 'cron'); - + dol_fiche_head($head, 'card', $langs->trans("Fiscalyear"), 0, 'cron'); + print '
' . "\n"; print ''; print ''; print ''; - + print ''; - + // Ref print ""; - print ''; - + // Label print ''; - + // Date start print ''; - + // Date end print ''; - + // Statut print ''; - + print '
' . $langs->trans("Ref") . ''; + print '' . $langs->trans("Ref") . ''; print $object->ref; print '
' . $langs->trans("Label") . ''; print ''; print '
' . $langs->trans("DateStart") . ''; print $form->select_date($object->date_start ? $object->date_start : - 1, 'fiscalyear'); print '
' . $langs->trans("DateEnd") . ''; print $form->select_date($object->date_end ? $object->date_end : - 1, 'fiscalyearend'); print '
' . $langs->trans("Statut") . ''; print $form->selectarray('statut', $statut2label, $object->statut); print '
'; - + print '
'; print ''; print '     '; print ''; print '
'; - + print '
'; - + dol_fiche_end(); } else { /* @@ -246,59 +253,61 @@ if ($action == 'create') if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"] . "?id=" . $id, $langs->trans("DeleteFiscalYear"), $langs->trans("ConfirmDeleteFiscalYear"), "confirm_delete"); } - - dol_fiche_head($head, 'card', $langs->trans("FiscalYearCard"), 0, 'cron'); - + + dol_fiche_head($head, 'card', $langs->trans("Fiscalyear"), 0, 'cron'); + print ''; - + $linkback = '' . $langs->trans("BackToList") . ''; - + // Ref - print ''; - + // Label print '"; - + // Date start print ''; - + // Date end print ''; - + // Statut print ''; - + print "
' . $langs->trans("Ref") . ''; + print '
' . $langs->trans("Ref") . ''; print $object->ref; - print ''; + print ''; print $linkback; print '
'; print $form->editfieldkey("Label", 'label', $object->label, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'alpha:32'); print ''; print $form->editfieldval("Label", 'label', $object->label, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'alpha:32'); print "
'; print $form->editfieldkey("DateStart", 'date_start', $object->date_start, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'datepicker'); print ''; print $form->editfieldval("DateStart", 'date_start', $object->date_start, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'datepicker'); print '
'; print $form->editfieldkey("DateEnd", 'date_end', $object->date_end, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'datepicker'); print ''; print $form->editfieldval("DateEnd", 'date_end', $object->date_end, $object, $conf->global->MAIN_EDIT_ALSO_INLINE, 'datepicker'); print '
' . $langs->trans("Status") . '' . $object->getLibStatut(4) . '
"; - + dol_fiche_end(); + + if (! empty($user->rights->accounting->fiscalyear)) + { + /* + * Barre d'actions + */ + print '
'; + + print '' . $langs->trans('Modify') . ''; + + print '' . $langs->trans('Delete') . ''; - /* - * Barre d'actions - */ - - print '
'; - - print '' . $langs->trans('Modify') . ''; - - print '' . $langs->trans('Delete') . ''; - - print '
'; + print '
'; + } } } else { dol_print_error($db); diff --git a/htdocs/accountancy/admin/fiscalyear_info.php b/htdocs/accountancy/admin/fiscalyear_info.php index f1f61a1f8d5..3596d73d751 100644 --- a/htdocs/accountancy/admin/fiscalyear_info.php +++ b/htdocs/accountancy/admin/fiscalyear_info.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2014-2016 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 @@ -16,11 +16,12 @@ */ /** - * \file htdocs/accountancy/admin/fiscalyear_card.php - * \brief Page to show info of a fiscal year + * \file htdocs/accountancy/admin/fiscalyear_info.php + * \ingroup Advanced accountancy + * \brief Page to show info of a fiscal year */ -require '../../main.inc.php'; +require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/fiscalyear.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/fiscalyear.class.php'; @@ -29,27 +30,31 @@ $langs->load("admin"); $langs->load("compta"); // Security check -if (! $user->admin) +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->fiscalyear) accessforbidden(); $id = GETPOST('id', 'int'); // View -llxHeader(); +$title = $langs->trans("Fiscalyear") . " - " . $langs->trans("Info"); +$helpurl = ""; +llxHeader("",$title,$helpurl); if ($id) { $object = new Fiscalyear($db); $object->fetch($id); $object->info($id); - + $head = fiscalyear_prepare_head($object); - - dol_fiche_head($head, 'info', $langs->trans("FiscalYearCard"), 0, 'cron'); - + + dol_fiche_head($head, 'info', $langs->trans("Fiscalyear"), 0, 'cron'); + print '
'; dol_print_object_info($object); print '
'; - + print '
'; } diff --git a/htdocs/accountancy/admin/importaccounts.php b/htdocs/accountancy/admin/importaccounts.php index 720f3a4f012..99b491688cb 100644 --- a/htdocs/accountancy/admin/importaccounts.php +++ b/htdocs/accountancy/admin/importaccounts.php @@ -40,6 +40,22 @@ $langs->load("accountancy"); if (! $user->admin) accessforbidden(); +$limit = GETPOST("limit")?GETPOST("limit","int"):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if ($page == -1) { $page = 0; } +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + + + + +/* + * View + */ + llxHeader('', $langs->trans("ImportAccount")); $to_import = GETPOST("mesCasesCochees"); @@ -90,15 +106,7 @@ if ($_POST["action"] == 'import') { print '
' . $langs->trans("EndProcessing") . '
'; } -/* - * list accounting account from product - * - */ -$page = GETPOST("page"); -if ($page < 0) - $page = 0; -$limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; -$offset = $limit * $page; +// list accounting account from product $sql = "(SELECT p.rowid as product_id, p.accountancy_code_sell as accounting "; $sql .= " FROM " . MAIN_DB_PREFIX . "product as p "; diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 0173ac931cc..8f023432727 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -41,35 +41,22 @@ $langs->load("accountancy"); $langs->load("salaries"); // Security check -if (! $user->admin) +if (empty($user->admin)) +{ accessforbidden(); +} $action = GETPOST('action', 'alpha'); // Parameters ACCOUNTING_* and others $list = array ( - 'ACCOUNTING_LIMIT_LIST_VENTILATION', - 'ACCOUNTING_LENGTH_DESCRIPTION', // adjust size displayed for lines description for dol_trunc - 'ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT', // adjust size displayed for select account description for dol_trunc - 'ACCOUNTING_LENGTH_GACCOUNT', - 'ACCOUNTING_LENGTH_AACCOUNT' + 'ACCOUNTING_LENGTH_GACCOUNT', + 'ACCOUNTING_LENGTH_AACCOUNT' , + 'ACCOUNTING_LENGTH_DESCRIPTION', // adjust size displayed for lines description for dol_trunc + 'ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT', // adjust size displayed for select account description for dol_trunc ); -$list_account = array ( - 'ACCOUNTING_ACCOUNT_SUPPLIER', - 'ACCOUNTING_ACCOUNT_CUSTOMER', - 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', - 'ACCOUNTING_PRODUCT_BUY_ACCOUNT', - 'ACCOUNTING_PRODUCT_SOLD_ACCOUNT', - 'ACCOUNTING_SERVICE_BUY_ACCOUNT', - 'ACCOUNTING_SERVICE_SOLD_ACCOUNT', - 'ACCOUNTING_VAT_BUY_ACCOUNT', - 'ACCOUNTING_VAT_SOLD_ACCOUNT', - 'ACCOUNTING_VAT_PAY_ACCOUNT', - 'ACCOUNTING_ACCOUNT_SUSPENSE', - 'ACCOUNTING_ACCOUNT_TRANSFER_CASH', - 'DONATION_ACCOUNTINGACCOUNT' -); + /* * Actions @@ -96,90 +83,76 @@ if ($action == 'update') { $error ++; } - $chartofaccounts = GETPOST('chartofaccounts', 'int'); - - if (! empty($chartofaccounts)) { - - if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { - $error ++; - } - } else { - $error ++; - } - - foreach ( $list as $constname ) { - $constvalue = GETPOST($constname, 'alpha'); - - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error ++; - } - } - - foreach ( $list_account as $constname ) { - $constvalue = GETPOST($constname, 'alpha'); - - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error ++; - } - } - - if (! $error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { + if ($error) { setEventMessages($langs->trans("Error"), null, 'errors'); } + + foreach ($list as $constname) { + $constvalue = GETPOST($constname, 'alpha'); + + if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } + + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } } // TO DO Mutualize code for yes/no constants if ($action == 'setlistsorttodo') { - $setlistsorttodo = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_TODO", $setlistsorttodo, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - - if (! $error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + $setlistsorttodo = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_TODO", $setlistsorttodo, 'yesno', 0, '', $conf->entity); + if (! $res > 0) + $error ++; + + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } if ($action == 'setlistsortdone') { - $setlistsortdone = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_DONE", $setlistsortdone, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + $setlistsortdone = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_DONE", $setlistsortdone, 'yesno', 0, '', $conf->entity); + if (! $res > 0) + $error ++; + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } if ($action == 'setmanagezero') { - $setmanagezero = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "ACCOUNTING_MANAGE_ZERO", $setmanagezero, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + $setmanagezero = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_MANAGE_ZERO", $setmanagezero, 'yesno', 0, '', $conf->entity); + if (! $res > 0) + $error ++; + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } if ($action == 'setdisabledirectinput') { - $setdisabledirectinput = GETPOST('value', 'int'); - $res = dolibarr_set_const($db, "BANK_DISABLE_DIRECT_INPUT", $setdisabledirectinput, 'yesno', 0, '', $conf->entity); - if (! $res > 0) - $error ++; - if (! $error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'mesgs'); - } + $setdisabledirectinput = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "BANK_DISABLE_DIRECT_INPUT", $setdisabledirectinput, 'yesno', 0, '', $conf->entity); + if (! $res > 0) + $error ++; + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } } + /* * View */ @@ -200,9 +173,10 @@ print ''; dol_fiche_head($head, 'general', $langs->trans("Configuration"), 0, 'cron'); -print ''; -// Cas du parametre ACCOUNTING_MODE +// Default mode for calculating turnover (parameter ACCOUNTING_MODE) + +print '
'; print ''; print ''; @@ -226,154 +200,110 @@ print '\n"; -print "
\n"; -/* - * Define Chart of accounts - */ -print '
' . $langs->trans('OptionMode') . '' . $langs->trans('Description') . '' . nl2br($langs->trans('OptionModeVirtualDesc')) . "
'; -$var = true; +print '
'; -print ''; -print ''; -print "\n"; -$var = ! $var; -print ''; -print ""; -print ""; -print "
'; -print $langs->trans("Chartofaccounts") . '
" . $langs->trans("Selectchartofaccounts") . ""; -print '"; -print "
"; - -print "
\n"; - -/* - * Others params - */ print ''; print ''; -print ''; +print ''; print "\n"; -foreach ( $list as $key ) { - $var = ! $var; - - print ''; - - // Param - $label = $langs->trans($key); - print ''; - - // Value - print ''; +if (! empty($user->admin)) +{ + // TO DO Mutualize code for yes/no constants + $var = ! $var; + print ""; + print ''; + if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) { + print ''; + } else { + print ''; + } + print ''; + + $var = ! $var; + print ""; + print ''; + if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) { + print ''; + } else { + print ''; + } + print ''; + + $var = ! $var; + print ""; + print ''; + if (! empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) { + print ''; + } else { + print ''; + } + print ''; + + $var = ! $var; + print ""; + print ''; + if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { + print ''; + } else { + print ''; + } + print ''; } -foreach ( $list_account as $key ) { - $var = ! $var; - - print ''; - - // Param - $label = $langs->trans($key); - print ''; - - // Value - print ''; + +// Param a user $user->rights->accountancy->chartofaccount can access +foreach ($list as $key) +{ + $var = ! $var; + + print ''; + // Param + $label = $langs->trans($key); + print ''; + // Value + print ''; + print ''; } -// TO DO Mutualize code for yes/no constants -$var = ! $var; -print ""; -print ''; -if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) { - print ''; -} else { - print ''; -} -print ''; -$var = ! $var; -print ""; -print ''; -if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) { - print ''; -} else { - print ''; -} -print ''; +print '
' . $langs->trans('OtherOptions') . '' . $langs->trans('OtherOptions') . '
'; - print ''; - print '
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO") . ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE") . ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
' . $langs->trans("BANK_DISABLE_DIRECT_INPUT") . ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
' . $langs->trans("ACCOUNTING_MANAGE_ZERO") . ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
'; - print $formaccountancy->select_account($conf->global->$key, $key, 1, '', 1, 1); - print '
'.$label.''; + print ''; + print '
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO") . ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE") . ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print '
'; -$var = ! $var; -print ""; -print '' . $langs->trans("ACCOUNTING_MANAGE_ZERO") . ''; -if (! empty($conf->global->ACCOUNTING_MANAGE_ZERO)) { - print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; -} else { - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; -} -print ''; -$var = ! $var; -print ""; -print '' . $langs->trans("BANK_DISABLE_DIRECT_INPUT") . ''; -if (! empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) { - print ''; - print img_picto($langs->trans("Activated"), 'switch_on'); - print ''; -} else { - print ''; - print img_picto($langs->trans("Disabled"), 'switch_off'); - print ''; -} -print ''; -print "\n"; dol_fiche_end(); print '
'; +print '
'; +print '
'; + +print $langs->trans("AccountancySetupDoneFromAccountancyMenu", $langs->transnoentitiesnoconv("Home").'-'.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy")); + +print '
'; print ''; llxFooter(); diff --git a/htdocs/accountancy/admin/journal.php b/htdocs/accountancy/admin/journal.php index b511c6dfd1a..0487538a906 100644 --- a/htdocs/accountancy/admin/journal.php +++ b/htdocs/accountancy/admin/journal.php @@ -35,11 +35,17 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; +$langs->load("compta"); +$langs->load("bills"); +$langs->load("admin"); $langs->load("accountancy"); +$langs->load("salaries"); // Security check -if (! $user->admin) - accessforbidden(); +if (empty($user->admin) || ! empty($user->rights->accountancy->chartofaccount)) +{ + accessforbidden(); +} $action = GETPOST('action', 'alpha'); diff --git a/htdocs/accountancy/admin/productaccount.php b/htdocs/accountancy/admin/productaccount.php index 63060e1ed60..5de8be91d20 100644 --- a/htdocs/accountancy/admin/productaccount.php +++ b/htdocs/accountancy/admin/productaccount.php @@ -40,17 +40,17 @@ $langs->load("companies"); $langs->load("compta"); $langs->load("main"); $langs->load("accountancy"); +$langs->load("products"); // Security check -if (! $user->admin) { - accessforbidden(); -} if (empty($conf->accounting->enabled)) { accessforbidden(); } - +if (! $user->rights->accounting->bind->write) + accessforbidden(); + // search & action GETPOST -$action = GETPOST('action'); +$action = GETPOST('action', 'alpha'); $codeventil_buy = GETPOST('codeventil_buy', 'array'); $codeventil_sell = GETPOST('codeventil_sell', 'array'); $chk_prod = GETPOST('chk_prod', 'array'); @@ -62,32 +62,51 @@ $changeaccount_sell = GETPOST('changeaccount_sell', 'array'); $search_ref = GETPOST('search_ref', 'alpha'); $search_label = GETPOST('search_label', 'alpha'); $search_desc = GETPOST('search_desc', 'alpha'); +$search_current_account = GETPOST('search_current_account', 'alpha'); +$search_current_account_valid = GETPOST('search_current_account_valid', 'alpha'); +if ($search_current_account_valid == '') $search_current_account_valid='withoutvalidaccount'; + $accounting_product_mode = GETPOST('accounting_product_mode', 'alpha'); $btn_changeaccount = GETPOST('changeaccount'); $btn_changetype = GETPOST('changetype'); -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); -if ($page < 0) - $page = 0; +$limit = GETPOST("limit")?GETPOST("limit","int"):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if ($page == -1) { $page = 0; } +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -// bug in page limit if ACCOUNTING_LIMIT_LIST_VENTILATION < $conf->liste_limit there is no pagination displayed ! -if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) && $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION >= $conf->liste_limit) { - $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; -} else { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} -$offset = $limit * $page; +if (! $sortfield) $sortfield="p.ref"; +if (! $sortorder) $sortorder="ASC"; -if (! $sortfield) { - $sortfield = "p.ref"; +if (empty($action)) $action='list'; + +$arrayfields=array(); + + +/* + * Actions + */ + +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +{ + $search_ref = ''; + $search_label = ''; + $search_desc = ''; + $search_current_account = ''; + $search_current_account_valid = '-1'; } -if (! $sortorder) { - $sortorder = "ASC"; -} - + // Sales or Purchase mode ? if ($action == 'update') { if (! empty($btn_changetype)) { @@ -111,14 +130,14 @@ if ($action == 'update') { } if (! empty($btn_changeaccount)) { - $msg = '
' . $langs->trans("Processing") . '...
'; + //$msg = '
' . $langs->trans("Processing") . '...
'; if (! empty($chk_prod)) { $accounting = new AccountingAccount($db); - $msg .= '
' . count($chk_prod) . ' ' . $langs->trans("SelectedLines") . '
'; + //$msg .= '
' . count($chk_prod) . ' ' . $langs->trans("SelectedLines") . '
'; - $cpt = 0; + $cpt = 0; $ok = 0; $ko = 0; foreach ( $chk_prod as $productid ) { $accounting_account_id = GETPOST('codeventil_' . $productid); @@ -140,21 +159,31 @@ if ($action == 'update') { dol_syslog("/accountancy/admin/productaccount.php sql=" . $sql, LOG_DEBUG); if ($db->query($sql)) { - $msg .= '
' . $langs->trans("Product") . ' ' . $productid . ' ' . $langs->trans("VentilatedinAccount") . ' : ' . length_accountg($accounting->account_number) . '
'; + $ok++; + //$msg .= '
' . $langs->trans("Product") . ' ' . $productid . ' - ' . $langs->trans("VentilatedinAccount") . ' : ' . length_accountg($accounting->account_number) . '
'; } else { - $msg .= '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Product") . ' ' . $productid . ' ' . $langs->trans("NotVentilatedinAccount") . ' : ' . length_accountg($accounting->account_number) . '
' . $sql . '
'; + $ko++; + //$msg .= '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Product") . ' ' . $productid . ' ' . $langs->trans("NotVentilatedinAccount") . ' : ' . length_accountg($accounting->account_number) . '
' . $sql . '
'; } } $cpt ++; } } else { - $msg .= '
' . $langs->trans("AnyLineVentilate") . '
'; + //$msg .= '
' . $langs->trans("AnyLineVentilate") . '
'; } - $msg .= '
' . $langs->trans("EndProcessing") . '
'; + if ($ko) setEventMessages($langs->trans("XLineFailedToBeBinded", $ko), null, 'errors'); + if ($ok) setEventMessages($langs->trans("XLineSuccessfullyBinded", $ok), null, 'mesgs'); + //$msg .= '
' . $langs->trans("EndProcessing") . '
'; } } + + +/* + * View + */ + $form = new FormVentilation($db); // Defaut AccountingAccount RowId Product / Service @@ -172,141 +201,169 @@ $aacompta_prodbuy = (! empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $c $aacompta_servsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); $aacompta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); -// Purge search criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +llxHeader('', $langs->trans("ProductsBinding")); + +$pcgverid = $conf->global->CHARTOFACCOUNTS; +$pcgvercode = dol_getIdFromCode($db, $pcgverid, 'accounting_system', 'rowid', 'pcg_version'); +if (empty($pcgvercode)) $pcgvercode=$pcgverid; + +$sql = "SELECT p.rowid, p.ref, p.label, p.description, p.tosell, p.tobuy, p.accountancy_code_sell, p.accountancy_code_buy, p.tms, p.fk_product_type as product_type,"; +$sql.= " aa.rowid as aaid"; +$sql.= " FROM " . MAIN_DB_PREFIX . "product as p"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON"; +if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { + $sql.=" p.accountancy_code_buy = aa.account_number AND aa.fk_pcg_version = '" . $pcgvercode . "'"; +} +else { - $search_ref = ''; - $search_label = ''; - $search_desc = ''; + $sql.=" p.accountancy_code_sell = aa.account_number AND aa.fk_pcg_version = '" . $pcgvercode . "'"; } - -/* - * View - */ - -llxHeader('', $langs->trans("InitAccountancy")); - -print ''; - -$sql = "SELECT p.rowid, p.ref , p.label, p.description , p.accountancy_code_sell, p.accountancy_code_buy, p.tms, p.fk_product_type as product_type"; -$sql .= " FROM " . MAIN_DB_PREFIX . "product as p"; -$sql .= " WHERE ("; - -$pcgver = $conf->global->CHARTOFACCOUNTS; - -if ($accounting_product_mode == 'ACCOUNTANCY_BUY' ? ' checked' : '') { - $sql .= " p.accountancy_code_buy ='' OR p.accountancy_code_buy IS NULL"; - $sql .= " OR (p.accountancy_code_buy IS NOT NULL AND p.accountancy_code_buy != '' AND p.accountancy_code_buy NOT IN - (SELECT aa.account_number FROM " . MAIN_DB_PREFIX . "accounting_account as aa , " . MAIN_DB_PREFIX . "accounting_system as asy WHERE fk_pcg_version = asy.pcg_version AND asy.rowid = " . $pcgver . "))"; +$sql.= ' WHERE p.entity IN ('.getEntity('product', 1).')'; +if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { + if (strlen(trim($search_current_account))) { + $sql .= natural_search("p.accountancy_code_buy",$search_current_account); + } } else { - $sql .= " p.accountancy_code_sell ='' OR p.accountancy_code_sell IS NULL "; - $sql .= " OR (p.accountancy_code_sell IS NOT NULL AND p.accountancy_code_sell != '' AND p.accountancy_code_sell NOT IN - (SELECT aa.account_number FROM " . MAIN_DB_PREFIX . "accounting_account as aa , " . MAIN_DB_PREFIX . "accounting_system as asy WHERE fk_pcg_version = asy.pcg_version AND asy.rowid = " . $pcgver . "))"; + if (strlen(trim($search_current_account))) { + $sql .= natural_search("p.accountancy_code_sell",$search_current_account); + } +} +if ($search_current_account_valid == 'withoutvalidaccount') +{ + $sql .= " AND aa.account_number IS NULL"; +} +if ($search_current_account_valid == 'withvalidaccount') +{ + $sql .= " AND aa.account_number IS NOT NULL"; } - -$sql .= ")"; - // Add search filter like if (strlen(trim($search_ref))) { - $sql .= " AND (p.ref like '" . $search_ref . "%')"; + $sql .= natural_search("p.ref",$search_ref); } if (strlen(trim($search_label))) { - $sql .= " AND (p.label like '" . $search_label . "%')"; + $sql .= natural_search("p.label",$search_label); } if (strlen(trim($search_desc))) { - $sql .= " AND (p.description like '%" . $search_desc . "%')"; + $sql .= natural_search("p.description",$search_desc); } $sql .= $db->order($sortfield, $sortorder); +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} $sql .= $db->plimit($limit + 1, $offset); dol_syslog("/accountancy/admin/productaccount.php:: sql=" . $sql, LOG_DEBUG); $result = $db->query($sql); -if ($result) { - $num_lines = $db->num_rows($result); +if ($result) +{ + $num = $db->num_rows($result); $i = 0; - print_barre_liste($langs->trans("ModulesSystemTools"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($search_ref > 0) $param.="&search_desc=".urlencode($search_ref); + if ($search_label > 0) $param.="&search_desc=".urlencode($search_label); + if ($search_desc > 0) $param.="&search_desc=".urlencode($search_desc); + if ($search_current_account > 0) $param.="&search_current_account=".urlencode($search_current_account); + if ($search_current_account_valid && $search_current_account_valid != '-1') $param.="&search_current_account_valid=".urlencode($search_current_account_valid); + + print '
'; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print load_fiche_titre($langs->trans("ProductsBinding"), '', 'title_accountancy'); print '
'; print $langs->trans("InitAccountancyDesc") . '
'; print '
'; - print ''; - print ''; - print ''; - + // Select mode print ''; print ''; print ''; print "\n"; - print ''; - print ''; + print '\n"; - print ''; - print '\n"; - + print ''; + print '\n"; print "
' . $langs->trans('Options') . '' . $langs->trans('Description') . '
' . $langs->trans('OptionModeProductSell') . '' . nl2br($langs->trans('OptionModeProductSellDesc')); + print '
' . $langs->trans('OptionModeProductSell') . ''.$langs->trans('OptionModeProductSellDesc'); print "
' . $langs->trans('OptionModeProductBuy') . '' . nl2br($langs->trans('OptionModeProductBuyDesc')) . "
' . $langs->trans('OptionModeProductBuy') . ''.$langs->trans('OptionModeProductBuyDesc')."
\n"; print '
'; - print "

\n"; + print "
\n"; + - if (! empty($msg)) { - print $msg; - } + // Filter on categories + $moreforfilter=''; + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - print ''; + $texte=$langs->trans("ListOfProductsServices"); + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit); + + print '
'; print ''; print_liste_field_titre($langs->trans("Ref"), $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Label"), $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "l.description", "", $param, '', $sortfield, $sortorder); - /* - if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { - print_liste_field_titre($langs->trans("Accountancy_code_buy")); - } else { - print_liste_field_titre($langs->trans("Accountancy_code_sell")); - } - */ - print_liste_field_titre($langs->trans("AccountAccounting")); - print_liste_field_titre($langs->trans("Modify") . '
/ ', '', '', '', '', 'align="center"'); + if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "p.description", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("OnSell"), $_SERVER["PHP_SELF"], "p.tosell", "", $param, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("OnBuy"), $_SERVER["PHP_SELF"], "p.tobuy", "", $param, 'align="center"', $sortfield, $sortorder); + if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { + $fieldtosortaccount="p.accountancy_code_buy"; + } + else $fieldtosortaccount="p.accountancy_code_sell"; + print_liste_field_titre($langs->trans("CurrentDedicatedAccountingAccount"), $_SERVER["PHP_SELF"], $fieldtosortaccount, "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("AssignDedicatedAccountingAccount")); + print_liste_field_titre('', '', '', '', '', 'align="center"'); print ''; print ''; - print ''; - print ''; - print ''; - + print ''; + print ''; + if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print ''; + // On sell + print ''; + // On buy + print ''; + // Current account + print ''; print ''; - print ''; print ''; - $var = true; + $product_static = new Product($db); - while ( $i < min($num_lines, 250) ) { + $var = true; + $i=0; + while ($i < min($num,$limit)) + { $obj = $db->fetch_object($result); - $var = ! $var; - - $compta_prodsell = $obj->accountancy_code_sell; + + // Ref produit as link + $product_static->ref = $obj->ref; + $product_static->id = $obj->rowid; + $product_static->type = $obj->product_type; + $product_static->label = $obj->label; + $product_static->description = $obj->description; + $product_static->status = $obj->tosell; + $product_static->status_buy = $obj->tobuy; if ($obj->product_type == 0) { $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); @@ -316,8 +373,6 @@ if ($result) { $compta_prodsell_id = $aarowid_servsell; } - $compta_prodbuy = $obj->accountancy_code_buy; - if ($obj->product_type == 0) { $compta_prodbuy = (! empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : $langs->trans("CodeNotDef")); $compta_prodbuy_id = $aarowid_prodbuy; @@ -326,59 +381,101 @@ if ($result) { $compta_prodbuy_id = $aarowid_servbuy; } - $product_static = new Product($db); + $var = ! $var; + print ''; - print ''; - - print ""; - print ''; - // Ref produit as link - $product_static->ref = $obj->ref; - $product_static->id = $obj->rowid; - $product_static->type = $obj->type; print ''; - print ''; - // TODO ADJUST DESCRIPTION SIZE - // print ''; - // TODO: we shoul set a user defined value to adjust user square / wide screen size - $trunclengh = defined('ACCOUNTING_LENGTH_DESCRIPTION') ? ACCOUNTING_LENGTH_DESCRIPTION : 64; - print ''; - // Accounting account buy + print ''; + + if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) + { + // TODO ADJUST DESCRIPTION SIZE + // print ''; + // TODO: we shoul set a user defined value to adjust user square / wide screen size + $trunclengh = defined('ACCOUNTING_LENGTH_DESCRIPTION') ? ACCOUNTING_LENGTH_DESCRIPTION : 64; + print ''; + } + + print ''; + + print ''; + + // Current accounting account + print ''; - // TODO: replace by select - // print ''; - // TODO: we shoul set a user defined value to adjust user square / wide screen size - // $trunclenghform = defined('ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT') ? ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT : 50; + print length_accountg($obj->accountancy_code_buy); + if ($obj->accountancy_code_buy && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount")); + } + else + { + print length_accountg($obj->accountancy_code_sell); + if ($obj->accountancy_code_sell && empty($obj->aaid)) print ' '.img_warning($langs->trans("ValueNotIntoChartOfAccount")); + } + print ''; + + // Dedicated account + $defaultvalue=''; + if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { + // Accounting account buy print ''; } else { // Accounting account sell - // print ''; - // TODO: replace by select - // TODO: we shoul set a user defined value to adjust user square / wide screen size - // $trunclenghform = defined('ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT') ? ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT : 50; print ''; } // Checkbox select - print ''; - + print ''; print ""; $i ++; } print '
'; + print ''; + $listofvals=array('withoutvalidaccount'=>$langs->trans("WithoutValidAccount"), 'withvalidaccount'=>$langs->trans("WithValidAccount")); + print ' '.$langs->trans("or").' '.$form->selectarray('search_current_account_valid', $listofvals, $search_current_account_valid, 1); + print ' '; - print ''; - print ' '; - print ''; + print ''; + $searchpitco=$form->showFilterAndCheckAddButtons(1, 'checkforselect', 1); + print $searchpitco; print '
'; - if ($product_static->id) - print $product_static->getNomUrl(1); - else - print '- '; + print $product_static->getNomUrl(1); print '' . dol_trunc($obj->label, 24) . '' . $obj->description . '' . nl2br(dol_trunc($obj->description, $trunclengh)) . ''.$obj->label.'' . $obj->description . '' . nl2br(dol_trunc($obj->description, $trunclengh)) . ''.$product_static->getLibStatut(3, 0).''.$product_static->getLibStatut(3, 1).''; if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { - // print '' . $obj->accountancy_code_buy . '' . $compta_prodbuy . ''; - print $form->select_account($compta_prodbuy_id, 'codeventil_' . $product_static->id, 1); + //$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha'); This is id and we need a code + if (empty($defaultvalue)) $defaultvalue=$compta_prodbuy; + $codesell=length_accountg($obj->accountancy_code_buy); + if (! empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid + print $form->select_account($defaultvalue, 'codeventil_' . $product_static->id, 1, array(), 1); print '' . $obj->accountancy_code_sell . ''; - print $form->select_account($compta_prodsell_id, 'codeventil_' . $product_static->id, 1); + //$defaultvalue=GETPOST('codeventil_' . $product_static->id,'alpha'); This is id and we need a code + if (empty($defaultvalue)) $defaultvalue=$compta_prodsell; + $codesell=length_accountg($obj->accountancy_code_sell); + //var_dump($defaultvalue.' - '.$codesell.' - '.$compta_prodsell); + if (! empty($obj->aaid)) $defaultvalue = ''; // Do not suggest default new value is code is already valid + print $form->select_account($defaultvalue, 'codeventil_' . $product_static->id, 1, array(), 1); print ''; - print ''; + print '
'; - print '
'; + + // Example : Adding jquery code + print ''; + + + print '
'; + print '
'; $db->free($result); diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 736581e9248..79d642ffcef 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -65,7 +65,7 @@ $formventilation = new FormVentilation($db); $formother = new FormOther($db); $form = new Form($db); -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { $search_accountancy_code_start = ''; $search_accountancy_code_end = ''; @@ -153,7 +153,7 @@ else { setEventMessages($object->error, $object->errors, 'errors'); } - print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, '', $result); + print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, '', $result, 0, 'title_accountancy'); print '
'; print '
' . "\n"; @@ -181,12 +181,12 @@ else { print ''; print ''; - print_liste_field_titre($langs->trans("AccountAccountingShort"), $_SERVER['PHP_SELF'], "t.numero_compte", "", $options, "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("AccountAccounting"), $_SERVER['PHP_SELF'], "t.numero_compte", "", $options, "", $sortfield, $sortorder); print_liste_field_titre($langs->trans("Labelcompte"), $_SERVER['PHP_SELF'], "t.label_compte", "", $options, "", $sortfield, $sortorder); print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "t.debit", "", $options, 'align="right"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "t.credit", "", $options, 'align="right"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Solde"), $_SERVER["PHP_SELF"], "", $options, "", 'align="right"', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Action"), $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder); + print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder); print "\n"; print ''; @@ -241,7 +241,7 @@ else { print ''; } - // Affiche le compte comptable en dbut de ligne + // Affiche le compte comptable en d�but de ligne print ""; print ''; print ''; diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index ba3c37f1997..9d054dc3c2c 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -166,28 +166,39 @@ else if ($action == "confirm_delete") { } else if ($action == "confirm_create") { - $book = new BookKeeping($db); + $error = 0; + + $book = new BookKeeping($db); - $book->label_compte = ''; - $book->debit = 0; - $book->credit = 0; - $book->doc_date = $date_start = dol_mktime(0, 0, 0, GETPOST('doc_datemonth'), GETPOST('doc_dateday'), GETPOST('doc_dateyear')); - $book->doc_type = GETPOST('doc_type'); - $book->piece_num = GETPOST('next_num_mvt'); - $book->doc_ref = GETPOST('doc_ref'); - $book->code_journal = GETPOST('code_journal'); - $book->fk_doc = 0; - $book->fk_docdet = 0; - - $book->montant = 0; - - $result = $book->createStd($user); - if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); - } else { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); - $action = ''; - $piece_num = $book->piece_num; + if (! GETPOST('next_num_mvt')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumPiece")), null, 'errors'); + $error++; + } + + if (! $error) + { + $book->label_compte = ''; + $book->debit = 0; + $book->credit = 0; + $book->doc_date = $date_start = dol_mktime(0, 0, 0, GETPOST('doc_datemonth'), GETPOST('doc_dateday'), GETPOST('doc_dateyear')); + $book->doc_type = GETPOST('doc_type'); + $book->piece_num = GETPOST('next_num_mvt'); + $book->doc_ref = GETPOST('doc_ref'); + $book->code_journal = GETPOST('code_journal'); + $book->fk_doc = 0; + $book->fk_docdet = 0; + + $book->montant = 0; + + $result = $book->createStd($user); + if ($result < 0) { + setEventMessages($book->error, $book->errors, 'errors'); + } else { + setEventMessages($langs->trans('Saved'), null, 'mesgs'); + $action = ''; + $piece_num = $book->piece_num; + } } } @@ -232,6 +243,10 @@ if ($action == 'create') { $book = new BookKeeping($db); $next_num_mvt = $book->getNextNumMvt(); + if (empty($next_num_mvt)) + { + dol_print_error('', 'Failed to get next piece number'); + } print ''; print '' . "\n"; @@ -241,19 +256,19 @@ if ($action == 'create') { print '
'. $root_account_description .'
'; print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -286,9 +301,11 @@ if ($action == 'create') { print load_fiche_titre($langs->trans("UpdateMvts"), '' . $langs->trans('BackToList') . ''); + dol_fiche_head(); + print '
' . $langs->trans("NumMvts") . '' . $langs->trans("NumPiece") . '' . $next_num_mvt . '
' . $langs->trans("Docdate") . '' . $langs->trans("Docdate") . ''; print $html->select_date('', 'doc_date', '', '', '', "create_mvt", 1, 1); print '
' . $langs->trans("Codejournal") . '' . $langs->trans("Codejournal") . '' . $html->selectarray('code_journal', $code_journal_array) . '
'; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -308,14 +325,17 @@ if ($action == 'create') { print ''; print ''; print '
' . $langs->trans("NumMvts") . '' . $langs->trans("NumMvts") . '' . $book->piece_num . '
' . $book->doc_type . '
'; - print '
'; + + dol_fiche_end(); + print '
'; + $result = $book->fetch_all_per_mvt($piece_num); if ($result < 0) { setEventMessages($book->error, $book->errors, 'errors'); } else { - print load_fiche_titre($langs->trans("ListeMvts")); + print load_fiche_titre($langs->trans("ListeMvts"), '', ''); print ''; print '' . "\n"; @@ -390,10 +410,9 @@ if ($action == 'create') { print "\n"; } - if ($total_debit != $total_credit) { - setEventMessages(null, array ( - $langs->trans('MvtNotCorrectlyBalanced', $total_credit, $total_debit) - ), 'errors'); + if ($total_debit != $total_credit) + { + setEventMessages(null, array($langs->trans('MvtNotCorrectlyBalanced', $total_credit, $total_debit)), 'warnings'); } if ($action == "" || $action == 'add') { @@ -410,7 +429,7 @@ if ($action == 'create') { print ''; print ''; print ''; - print ''; + print ''; print ''; } print ''; diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 5eafa920973..f925bf4e4eb 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -1,7 +1,8 @@ - * Copyright (C) 2013-2016 Florian Henry - * Copyright (C) 2013-2016 Alexandre Spangaro +/* Copyright (C) 2013-2016 Olivier Geffroy + * Copyright (C) 2013-2016 Florian Henry + * Copyright (C) 2013-2016 Alexandre Spangaro + * 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 @@ -19,8 +20,8 @@ */ /** - * \file htdocs/accountancy/bookkeeping/list.php - * \ingroup Advanced accountancy + * \file htdocs/accountancy/bookkeeping/list.php + * \ingroup Advanced accountancy * \brief List operation of book keeping */ require '../../main.inc.php'; @@ -77,9 +78,18 @@ $search_mvt_label = GETPOST('search_mvt_label', 'alpha'); $search_direction = GETPOST('search_direction', 'alpha'); $search_ledger_code = GETPOST('search_ledger_code', 'alpha'); -$limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; - +// Load variable for pagination +$limit = GETPOST('limit') ? GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOST('page','int'); +if ($page < 0) { $page = 0; } $offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if ($sortorder == "") $sortorder = "ASC"; +if ($sortfield == "") $sortfield = "t.rowid"; + $object = new BookKeeping($db); @@ -88,86 +98,22 @@ $formother = new FormOther($db); $form = new Form($db); +if ($action != 'export_csv' && ! isset($_POST['begin']) && ! isset($_GET['begin']) && ! isset($_POST['formfilteraction'])) { + $search_date_start = dol_mktime(0, 0, 0, 1, 1, dol_print_date(dol_now(), '%Y')); + $search_date_end = dol_mktime(0, 0, 0, 12, 31, dol_print_date(dol_now(), '%Y')); +} -if (empty($search_date_start)) { - $search_date_start = dol_mktime(0, 0, 0, 1, 1, dol_print_date(dol_now(), '%Y')); - $search_date_end = dol_mktime(0, 0, 0, 12, 31, dol_print_date(dol_now(), '%Y')); -} -if ($sortorder == "") - $sortorder = "ASC"; -if ($sortfield == "") - $sortfield = "t.rowid"; - -$options = ''; -$filter = array (); -if (! empty($search_date_start)) { - $filter['t.doc_date>='] = $search_date_start; - $options .= '&date_startmonth=' . GETPOST('date_startmonth', 'int') . '&date_startday=' . GETPOST('date_startday', 'int') . '&date_startyear=' . GETPOST('date_startyear', 'int'); -} -if (! empty($search_date_end)) { - $filter['t.doc_date<='] = $search_date_end; - $options .= '&date_endmonth=' . GETPOST('date_endmonth', 'int') . '&date_endday=' . GETPOST('date_endday', 'int') . '&date_endyear=' . GETPOST('date_endyear', 'int'); -} -if (! empty($search_doc_type)) { - $filter['t.doc_type'] = $search_doc_type; - $options .= '&search_doc_type=' . $search_doc_type; -} -if (! empty($search_doc_date)) { - $filter['t.doc_date'] = $search_doc_date; - $options .= '&doc_datemonth=' . GETPOST('doc_datemonth', 'int') . '&doc_dateday=' . GETPOST('doc_dateday', 'int') . '&doc_dateyear=' . GETPOST('doc_dateyear', 'int'); -} -if (! empty($search_doc_ref)) { - $filter['t.doc_ref'] = $search_doc_ref; - $options .= '&search_doc_ref=' . $search_doc_ref; -} -if (! empty($search_accountancy_code)) { - $filter['t.numero_compte'] = $search_accountancy_code; - $options .= '&search_accountancy_code=' . $search_accountancy_code; -} -if (! empty($search_accountancy_code_start)) { - $filter['t.numero_compte>='] = $search_accountancy_code_start; - $options .= '&search_accountancy_code_start=' . $search_accountancy_code_start; -} -if (! empty($search_accountancy_code_end)) { - $filter['t.numero_compte<='] = $search_accountancy_code_end; - $options .= '&search_accountancy_code_end=' . $search_accountancy_code_end; -} -if (! empty($search_accountancy_aux_code)) { - $filter['t.code_tiers'] = $search_accountancy_aux_code; - $options .= '&search_accountancy_aux_code=' . $search_accountancy_aux_code; -} -if (! empty($search_accountancy_aux_code_start)) { - $filter['t.code_tiers>='] = $search_accountancy_aux_code_start; - $options .= '&search_accountancy_aux_code_start=' . $search_accountancy_aux_code_start; -} -if (! empty($search_accountancy_aux_code_end)) { - $filter['t.code_tiers<='] = $search_accountancy_aux_code_end; - $options .= '&search_accountancy_aux_code_end=' . $search_accountancy_aux_code_end; -} -if (! empty($search_mvt_label)) { - $filter['t.label_compte'] = $search_mvt_label; - $options .= '&search_mvt_label=' . $search_mvt_label; -} -if (! empty($search_direction)) { - $filter['t.sens'] = $search_direction; - $options .= '&search_direction=' . $search_direction; -} -if (! empty($search_ledger_code)) { - $filter['t.code_journal'] = $search_ledger_code; - $options .= '&search_ledger_code=' . $search_ledger_code; -} -if (! empty($search_mvt_num)) { - $filter['t.piece_num'] = $search_mvt_num; - $options .= '&search_mvt_num=' . $search_mvt_num; -} /* * Action */ -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers { $search_mvt_num = ''; $search_doc_type = ''; @@ -210,15 +156,25 @@ if ($action == 'delbookkeepingyearconfirm') { $deljournal=0; } - - if (! empty($delyear) || ! empty($deljournal)) { + if (! empty($delyear) || ! empty($deljournal)) + { $result = $object->deleteByYearAndJournal($delyear,$deljournal); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } + else + { + setEventMessages("RecordDeleted", null, 'mesgs'); + } Header("Location: list.php"); exit; } + else + { + setEventMessages("NoRecordDeleted", null, 'warnings'); + Header("Location: list.php"); + exit; + } } if ($action == 'delmouvconfirm') { @@ -227,37 +183,112 @@ if ($action == 'delmouvconfirm') { if (! empty($mvt_num)) { $result = $object->deleteMvtNum($mvt_num); if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); + } + else + { + setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); } Header("Location: list.php"); exit; } } -if ($action == 'export_csv') { - include DOL_DOCUMENT_ROOT . '/accountancy/class/accountancyexport.class.php'; - $result = $object->fetchAll($sortorder, $sortfield, 0, 0, $filter); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - } - else - { - $accountancyexport = new AccountancyExport($db); - $accountancyexport->export($object->lines); - if (!empty($accountancyexport->errors)) { - setEventMessages('', $accountancyexport->errors, 'errors'); - } - exit; - } -} /* * View */ -$title_page = $langs->trans("Bookkeeping") . ' ' . dol_print_date($search_date_start) . '-' . dol_print_date($search_date_end); +$param = ''; +$filter = array (); +if (! empty($search_date_start)) { + $filter['t.doc_date>='] = $search_date_start; + $tmp=dol_getdate($search_date_start); + $param .= '&date_startmonth=' . $tmp['mon'] . '&date_startday=' . $tmp['mday'] . '&date_startyear=' . $tmp['year']; +} +if (! empty($search_date_end)) { + $filter['t.doc_date<='] = $search_date_end; + $tmp=dol_getdate($search_date_end); + $param .= '&date_endmonth=' . $tmp['mon'] . '&date_endday=' . $tmp['mday'] . '&date_endyear=' . $tmp['year']; +} +if (! empty($search_doc_date)) { + $filter['t.doc_date'] = $search_doc_date; + $tmp=dol_getdate($search_doc_date); + $param .= '&doc_datemonth=' . $tmp['mon'] . '&doc_dateday=' . $tmp['mday'] . '&doc_dateyear=' . $tmp['year']; +} +if (! empty($search_doc_type)) { + $filter['t.doc_type'] = $search_doc_type; + $param .= '&search_doc_type=' . $search_doc_type; +} +if (! empty($search_doc_ref)) { + $filter['t.doc_ref'] = $search_doc_ref; + $param .= '&search_doc_ref=' . $search_doc_ref; +} +if (! empty($search_accountancy_code)) { + $filter['t.numero_compte'] = $search_accountancy_code; + $param .= '&search_accountancy_code=' . $search_accountancy_code; +} +if (! empty($search_accountancy_code_start)) { + $filter['t.numero_compte>='] = $search_accountancy_code_start; + $param .= '&search_accountancy_code_start=' . $search_accountancy_code_start; +} +if (! empty($search_accountancy_code_end)) { + $filter['t.numero_compte<='] = $search_accountancy_code_end; + $param .= '&search_accountancy_code_end=' . $search_accountancy_code_end; +} +if (! empty($search_accountancy_aux_code)) { + $filter['t.code_tiers'] = $search_accountancy_aux_code; + $param .= '&search_accountancy_aux_code=' . $search_accountancy_aux_code; +} +if (! empty($search_accountancy_aux_code_start)) { + $filter['t.code_tiers>='] = $search_accountancy_aux_code_start; + $param .= '&search_accountancy_aux_code_start=' . $search_accountancy_aux_code_start; +} +if (! empty($search_accountancy_aux_code_end)) { + $filter['t.code_tiers<='] = $search_accountancy_aux_code_end; + $param .= '&search_accountancy_aux_code_end=' . $search_accountancy_aux_code_end; +} +if (! empty($search_mvt_label)) { + $filter['t.label_compte'] = $search_mvt_label; + $param .= '&search_mvt_label=' . $search_mvt_label; +} +if (! empty($search_direction)) { + $filter['t.sens'] = $search_direction; + $param .= '&search_direction=' . $search_direction; +} +if (! empty($search_ledger_code)) { + $filter['t.code_journal'] = $search_ledger_code; + $param .= '&search_ledger_code=' . $search_ledger_code; +} +if (! empty($search_mvt_num)) { + $filter['t.piece_num'] = $search_mvt_num; + $param .= '&search_mvt_num=' . $search_mvt_num; +} + +if ($action == 'export_csv') { + + include DOL_DOCUMENT_ROOT . '/accountancy/class/accountancyexport.class.php'; + + $result = $object->fetchAll($sortorder, $sortfield, 0, 0, $filter); + + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } + else + { + $accountancyexport = new AccountancyExport($db); + $accountancyexport->export($object->lines); + if (!empty($accountancyexport->errors)) { + setEventMessages('', $accountancyexport->errors, 'errors'); + } + exit; + } +} + +$title_page = $langs->trans("Bookkeeping"); +if ($search_date_start || $search_date_end) $title_page .= ' ' . dol_print_date($search_date_start, 'day') . ' - ' . dol_print_date($search_date_end, 'day'); llxHeader('', $title_page); // List @@ -270,13 +301,14 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { } } +// TODO Do not use this $result = $object->fetchAll($sortorder, $sortfield, $limit, $offset, $filter); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } if ($action == 'delmouv') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?mvt_num=' . GETPOST('mvt_num'), $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delmouvconfirm', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?mvt_num=' . GETPOST('mvt_num'), $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvtPartial'), 'delmouvconfirm', '', 0, 1); print $formconfirm; } if ($action == 'delbookkeepingyear') { @@ -306,39 +338,53 @@ if ($action == 'delbookkeepingyear') { 'default' => $deljournal ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, 0, 1, 250); print $formconfirm; } -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, '', $result, $nbtotalofrecords); +//$param=''; param started before +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + +print ''; +print ''; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit); -print ''; print ''; +print ' ' . $langs->trans("GroupByAccountAccounting") . '

'; + print ''; print ''; -print_liste_field_titre($langs->trans("NumPiece"), $_SERVER['PHP_SELF'], "t.piece_num", "", $options, "", $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Docdate"), $_SERVER['PHP_SELF'], "t.doc_date", "", $options, "", $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "t.doc_ref", "", $options, "", $sortfield, $sortorder); -print_liste_field_titre($langs->trans("AccountAccountingShort"), $_SERVER['PHP_SELF'], "t.numero_compte", "", $options, "", $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Code_tiers"), $_SERVER['PHP_SELF'], "t.code_tiers", "", $options, "", $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Labelcompte"), $_SERVER['PHP_SELF'], "bk_label_compte", "", $options, "", $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "t.debit", "", $options, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "t.credit", "", $options, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "t.code_journal", "", $options, 'align="center"', $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Action"), $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder); +print_liste_field_titre($langs->trans("TransactionNumShort"), $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Docdate"), $_SERVER['PHP_SELF'], "t.doc_date", "", $param, 'align="center"', $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre($langs->trans("AccountAccountingShort"), $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Code_tiers"), $_SERVER['PHP_SELF'], "t.code_tiers", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Labelcompte"), $_SERVER['PHP_SELF'], "t.label_compte", "", $param, "", $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "t.debit", "", $param, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "t.credit", "", $param, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "t.code_journal", "", $param, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $param, "", 'width="60" align="center"', $sortfield, $sortorder); print "\n"; print ''; -print ''; print ''; -print ''; - print ''; print ''; print ''; print ''; -print ''; - print ''; $var = True; @@ -379,13 +423,13 @@ $var = True; $total_debit = 0; $total_credit = 0; -foreach ( $object->lines as $line ) { +foreach ($object->lines as $line ) { $var = ! $var; $total_debit += $line->debit; $total_credit += $line->credit; - print ''; + print ''; print ''; print ''; @@ -398,7 +442,7 @@ foreach ( $object->lines as $line ) { print ''; print ''; print "\n"; } @@ -411,13 +455,13 @@ print ''; print ''; -print ''; +print ''; print ''; print "
'; +print ''; print $langs->trans('From') . ': '; print $form->select_date($search_date_start, 'date_start', 0, 0, 1); print '
'; @@ -360,18 +406,16 @@ print '
'; print $langs->trans('to'); print $formventilation->select_auxaccount($search_accountancy_aux_code_end, 'search_accountancy_aux_code_end', 1); print '
'; print ''; print '  '; +print ''; $searchpitco=$form->showFilterAndCheckAddButtons(0); print $searchpitco; print '
' . $line->piece_num . '' . dol_print_date($line->doc_date, 'day') . '' . $line->code_journal . ''; print '' . img_edit() . ' '; - print '' . img_delete() . ''; + print '' . img_delete() . ''; print '
'; print price($total_credit); print '
"; + print ''; llxFooter(); - -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index ce62655465d..3a6a428abed 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -60,11 +60,23 @@ $search_mvt_label = GETPOST('search_mvt_label', 'alpha'); $search_direction = GETPOST('search_direction', 'alpha'); $search_ledger_code = GETPOST('search_ledger_code', 'alpha'); -$limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -if ($page == -1) { $page = 0 ; } -$offset = $limit * $page ; +// Load variable for pagination +$limit = GETPOST('limit') ? GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOST('page','int'); +if ($page < 0) { $page = 0; } +$offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; +if ($sortorder == "") $sortorder = "ASC"; +if ($sortfield == "") $sortfield = "t.rowid"; + +if (empty($search_date_start)) { + $search_date_start = dol_mktime(0, 0, 0, 1, 1, dol_print_date(dol_now(), '%Y')); + $search_date_end = dol_mktime(0, 0, 0, 12, 31, dol_print_date(dol_now(), '%Y')); +} + $object = new BookKeeping($db); @@ -73,18 +85,6 @@ $formother = new FormOther($db); $form = new Form($db); - - -if (empty($search_date_start)) { - $search_date_start = dol_mktime(0, 0, 0, 1, 1, dol_print_date(dol_now(), '%Y')); - $search_date_end = dol_mktime(0, 0, 0, 12, 31, dol_print_date(dol_now(), '%Y')); -} -if ($sortorder == "") - $sortorder = "ASC"; -if ($sortfield == "") - $sortfield = "t.rowid"; - - $options = ''; $filter = array (); @@ -202,7 +202,7 @@ if ($action == 'delbookkeepingyear') { 'default' => $delyear ); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'delbookkeepingyearconfirm', $form_question, 0, 1, 250); print $formconfirm; } @@ -211,7 +211,7 @@ if ($action == 'delbookkeepingyear') { print '
'; -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, '', $result, $nbtotalofrecords,'',0,'','',$limit); +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, '', $result, $nbtotalofrecords,'title_accountancy',0,'','',$limit); // Reverse sort order if ( preg_match('/^asc/i', $sortorder) ) @@ -223,22 +223,26 @@ print ''; +print ' ' . $langs->trans("ViewFlatList") . '

'; + print ''; print ''; print ''; -print_liste_field_titre($langs->trans("Docdate"), $_SERVER['PHP_SELF'], "t.doc_date", "", $options, "", $sortfield, $sortorder); +print_liste_field_titre($langs->trans("TransactionNumShort"), $_SERVER['PHP_SELF'], "t.piece_num", "", $options, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Docdate"), $_SERVER['PHP_SELF'], "t.doc_date", "", $options, 'align="center"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "t.doc_ref", "", $options, "", $sortfield, $sortorder); -print ''; +print_liste_field_titre($langs->trans("SuppliersInvoices") . ' / ' . $langs->trans("CustomersInvoices")); print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "t.debit", "", $options, 'align="right"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "t.credit", "", $options, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "t.code_journal", "", $options, 'align="center"', $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Action"), $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "t.code_journal", "", $options, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder); print "\n"; print ''; print ''; -print ''; -print ''; +print ''; +print ''; - print "\n"; - print ''; + $accountg = length_accountg($line->numero_compte); + //if (empty($accountg)) $accountg = '-'; + + // Is it a break ? + if ($accountg != $displayed_account_number || ! isset($displayed_account_number)) { + + // Affiche un Sous-Total par compte comptable + if (isset($displayed_account_number)) { + print ''; + print "\n"; + print ''; + } + + // Show the break account + $colspan = 9; + print ""; + print ''; + print ''; + + $displayed_account_number = $accountg; + //if (empty($displayed_account_number)) $displayed_account_number='-'; + $sous_total_debit = 0; + $sous_total_credit = 0; } - // Affiche le compte comptable en début de ligne - print ""; - print ''; - print ''; - - $displayed_account_number = length_accountg($line->numero_compte); - $sous_total_debit = 0; - $sous_total_credit = 0; - } - - print ''; + print ''; print ''; + print ''; print ''; print ''; - - // Affiche un lien vers la facture client/fournisseur - $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref); - if ($line->doc_type == 'supplier_invoice') - print strlen(length_accounta($line->code_tiers)) == 0 ? '' : ''; - elseif ($line->doc_type == 'customer_invoice') + + // Affiche un lien vers la facture client/fournisseur + $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref); + if ($line->doc_type == 'supplier_invoice') + print strlen(length_accounta($line->code_tiers)) == 0 ? '' : ''; + elseif ($line->doc_type == 'customer_invoice') print strlen(length_accounta($line->code_tiers)) == 0 ? '' : ''; - else + else print strlen(length_accounta($line->code_tiers)) == 0 ? '' : ''; diff --git a/htdocs/accountancy/bookkeeping/listbyyear.php b/htdocs/accountancy/bookkeeping/listbyyear.php index 23eeb79621a..d8df8eb5007 100644 --- a/htdocs/accountancy/bookkeeping/listbyyear.php +++ b/htdocs/accountancy/bookkeeping/listbyyear.php @@ -171,7 +171,7 @@ if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } -print_barre_liste($langs->trans("Bookkeeping") . ' ' . dol_print_date($search_date_start) . '-' . dol_print_date($search_date_end), $page, $_SERVER['PHP_SELF'], $options, $sortfield, $sortorder, '', $result, $nbtotalofrecords); +print_barre_liste($langs->trans("Bookkeeping") . ' ' . dol_print_date($search_date_start) . '-' . dol_print_date($search_date_end), $page, $_SERVER['PHP_SELF'], $options, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy'); print ''; print '
'; @@ -197,7 +197,7 @@ print "
' . $langs->trans("AccountAccounting") . '' . $langs->trans("SuppliersInvoices") . ' / ' . $langs->trans("CustomersInvoices") . '
' . $object->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, '') . ''; +print '' . $object->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, '') . ''; print $langs->trans('From') . ': '; print $form->select_date($search_date_start, 'date_start', 0, 0, 1); print '
'; @@ -263,7 +267,7 @@ $total_debit = 0; $total_credit = 0; $sous_total_debit = 0; $sous_total_credit = 0; -$displayed_account_number = ""; +$displayed_account_number = null; // Start with undefined to be able to distinguish with empty foreach ( $object->lines as $line ) { $var = ! $var; @@ -271,38 +275,47 @@ foreach ( $object->lines as $line ) { $total_debit += $line->debit; $total_credit += $line->credit; - // Permet d'afficher le compte comptable - if (length_accountg($line->numero_compte) != $displayed_account_number) { - - // Affiche un Sous-Total par compte comptable - if ($displayed_account_number != "") { - print '
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).' 
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).' 
'; + if (! empty($line->numero_compte) && $line->numero_compte != '-1') print length_accountg($line->numero_compte) . ' : ' . $object->get_compte_desc($line->numero_compte); + else print ''.$langs->trans("Unknown").''; + print '
'.length_accountg($line->numero_compte) . ' : ' . $object->get_compte_desc($line->numero_compte).'
 '.$line->piece_num.'' . dol_print_date($line->doc_date, 'day') . '' . $line->doc_ref . '' . $line->label_compte . '' . $line->label_compte . '
(' . length_accounta($line->code_tiers) . ')
' . $line->label_compte . '' . $line->label_compte . '
(' . length_accounta($line->code_tiers) . ')
' . $line->label_compte . '' . $line->label_compte . '
(' . length_accounta($line->code_tiers) . ')
' . $line->label_compte . '' . $line->label_compte . '
(' . length_accounta($line->code_tiers) . ')
"; print ''; print_liste_field_titre($langs->trans("NumPiece"), $_SERVER['PHP_SELF'], "t.piece_num", "", $options, "", $sortfield, $sortorder); print_liste_field_titre($langs->trans("Doctype"), $_SERVER['PHP_SELF'], "t.doc_type", "", $options, "", $sortfield, $sortorder); -print_liste_field_titre($langs->trans("Date"), $_SERVER['PHP_SELF'], "t.doc_date", "", $options, "", $sortfield, $sortorder); +print_liste_field_titre($langs->trans("Date"), $_SERVER['PHP_SELF'], "t.doc_date", "", $options, 'align="center"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "t.doc_ref", "", $options, "", $sortfield, $sortorder); print_liste_field_titre($langs->trans("AccountAccounting"), $_SERVER['PHP_SELF'], "t.numero_compte", "", $options, "", $sortfield, $sortorder); print_liste_field_titre($langs->trans("ThirdPartyAccount"), $_SERVER['PHP_SELF'], "t.code_tiers", "", $options, "", $sortfield, $sortorder); @@ -269,10 +269,10 @@ $var = True; foreach ( $object->lines as $line ) { $var = ! $var; - print ''; + print ''; print '' . "\n"; print '' . "\n"; - print ''; + print ''; print ''; print ''; print ''; @@ -289,4 +289,4 @@ print "
' . $line->piece_num . '' . $line->doc_type . '' . dol_print_date($line->doc_date) . '' . dol_print_date($line->doc_date) . '' . $line->doc_ref . '' . length_accountg($line->numero_compte) . '' . length_accounta($line->code_tiers) . '
"; print '
'; llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/accountancy/class/accountancycategory.class.php b/htdocs/accountancy/class/accountancycategory.class.php index ff7f764ea31..40290bd845b 100644 --- a/htdocs/accountancy/class/accountancycategory.class.php +++ b/htdocs/accountancy/class/accountancycategory.class.php @@ -230,7 +230,7 @@ class AccountancyCategory /** * Function to know all category from accounting account * - * @return array Result in table + * @return array Result in table */ public function getCatsCpts() { global $mysoc; @@ -283,7 +283,7 @@ class AccountancyCategory $this->error = "Error " . $this->db->lasterror(); dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR); - return - 1; + return -1; } } @@ -380,7 +380,7 @@ class AccountancyCategory } else { $this->error = "Error " . $this->db->lasterror(); $this->errors[] = $this->error; - dol_syslog(__METHOD__ . " " . implode(',' . $this->errors), LOG_ERR); + dol_syslog(__METHOD__ . " " . implode(',', $this->errors), LOG_ERR); return - 1; } diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index 8c7fedbfa5c..d40d8147ef0 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -1,10 +1,11 @@ - * Copyright (C) 2014 Juanjo Menent - * Copyright (C) 2015 Florian Henry - * Copyright (C) 2015 Raphaël Doursenaud - * Copyright (C) 2016 Pierre-Henry Favre + * Copyright (C) 2007-2012 Laurent Destailleur + * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2015 Florian Henry + * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) 2016 Pierre-Henry Favre + * Copyright (C) 2016 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 @@ -21,7 +22,9 @@ */ /** - * \file htdocs/accountancy/class/accountancyexport.class.php + * \file htdocs/accountancy/class/accountancyexport.class.php + * \ingroup Advanced accountancy + * \brief Class accountancy export */ /** @@ -157,7 +160,7 @@ class AccountancyExport */ public function exportNormal($objectLines) { global $conf; - + foreach ( $objectLines as $line ) { // Std export $date = dol_print_date($line->doc_date, $conf->global->ACCOUNTING_EXPORT_DATE); @@ -182,15 +185,16 @@ class AccountancyExport public function exportCegid($objectLines) { foreach ( $objectLines as $line ) { $date = dol_print_date($line->doc_date, '%d%m%Y'); + $separator = ";"; - print $date . $this->separator; - print $line->code_journal . $this->separator; - print length_accountg($line->numero_compte) . $this->separator; - print ' ' . $this->separator; - print $line->sens . $this->separator; - print price($line->montant) . $this->separator; - print dol_trunc($line->label_compte, 32) . $this->separator; - print $line->doc_ref . $this->separator; + print $date . $separator; + print $line->code_journal . $separator; + print length_accountg($line->numero_compte) . $separator; + print length_accounta($line->code_tiers) . $separator; + print $line->sens . $separator; + print price($line->montant) . $separator; + print $line->label_compte . $separator; + print $line->doc_ref; print $this->end_line; } } diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 690f3785df1..b63d7ce2fda 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -45,7 +45,8 @@ class AccountingAccount extends CommonObject var $label; var $fk_user_author; var $fk_user_modif; - var $active; + var $active; // duplicate with status + var $status; /** * Constructor @@ -103,6 +104,7 @@ class AccountingAccount extends CommonObject $this->fk_user_author = $obj->fk_user_author; $this->fk_user_modif = $obj->fk_user_modif; $this->active = $obj->active; + $this->status = $obj->active; return $this->id; } else { @@ -170,16 +172,15 @@ class AccountingAccount extends CommonObject $sql .= " '" . $this->db->idate($now) . "'"; $sql .= ", " . $conf->entity; - $sql .= ", " . (! isset($this->fk_pcg_version) ? 'NULL' : "'" . $this->db->escape($this->fk_pcg_version) . "'"); - $sql .= ", " . (! isset($this->pcg_type) ? 'NULL' : "'" . $this->db->escape($this->pcg_type) . "'"); - $sql .= ", " . (! isset($this->pcg_subtype) ? 'NULL' : "'" . $this->pcg_subtype . "'"); - $sql .= ", " . (! isset($this->account_number) ? 'NULL' : "'" . $this->account_number . "'"); - $sql .= ", " . (! isset($this->account_parent) ? 'NULL' : "'" . $this->db->escape($this->account_parent) . "'"); - $sql .= ", " . (! isset($this->label) ? 'NULL' : "'" . $this->db->escape($this->label) . "'"); - $sql .= ", " . (! isset($this->account_category) ? 'NULL' : "'" . $this->db->escape($this->account_category) . "'"); + $sql .= ", " . (empty($this->fk_pcg_version) ? 'NULL' : "'" . $this->db->escape($this->fk_pcg_version) . "'"); + $sql .= ", " . (empty($this->pcg_type) ? 'NULL' : "'" . $this->db->escape($this->pcg_type) . "'"); + $sql .= ", " . (empty($this->pcg_subtype) ? 'NULL' : "'" . $this->pcg_subtype . "'"); + $sql .= ", " . (empty($this->account_number) ? 'NULL' : "'" . $this->account_number . "'"); + $sql .= ", " . (empty($this->account_parent) ? 'NULL' : "'" . $this->db->escape($this->account_parent) . "'"); + $sql .= ", " . (empty($this->label) ? 'NULL' : "'" . $this->db->escape($this->label) . "'"); + $sql .= ", " . (empty($this->account_category) ? 'NULL' : "'" . $this->db->escape($this->account_category) . "'"); $sql .= ", " . $user->id; - $sql .= ", " . (! isset($this->active) ? 'NULL' : "'" . $this->db->escape($this->active) . "'"); - + $sql .= ", " . (! isset($this->active) ? 'NULL' : $this->db->escape($this->active)); $sql .= ")"; $this->db->begin(); @@ -465,4 +466,61 @@ class AccountingAccount extends CommonObject return - 1; } } + + + /** + * Retourne le libelle du statut 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); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut Id statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Label of status + */ + function LibStatut($statut,$mode=0) + { + global $langs; + $langs->load('users'); + + if ($mode == 0) + { + $prefix=''; + if ($statut == 1) return $langs->trans('Enabled'); + if ($statut == 0) return $langs->trans('Disabled'); + } + if ($mode == 1) + { + if ($statut == 1) return $langs->trans('Enabled'); + if ($statut == 0) return $langs->trans('Disabled'); + } + if ($mode == 2) + { + if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 3) + { + if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4'); + if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 4) + { + if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 5) + { + if ($statut == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($statut == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + } + } } diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 0d863e064d4..a6f487c1211 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -55,12 +55,17 @@ class BookKeeping extends CommonObject */ public $table_element = 'accounting_bookkeeping'; + + public $entity = 1; + + /** * * @var BookKeepingLine[] Lines */ public $lines = array (); + /** * * @var int ID @@ -100,18 +105,18 @@ class BookKeeping extends CommonObject /** * 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 + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK */ public function create(User $user, $notrigger = false) { + global $conf, $langs; + dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; // Clean parameters - if (isset($this->doc_type)) { $this->doc_type = trim($this->doc_type); } @@ -157,6 +162,17 @@ class BookKeeping extends CommonObject if (isset($this->piece_num)) { $this->piece_num = trim($this->piece_num); } + if (empty($this->debit)) $this->debit = 0; + if (empty($this->credit)) $this->credit = 0; + + // Check parameters + if (empty($this->numero_compte) || $this->numero_compte == '-1') + { + $langs->load("errors"); + $this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet); + return -1; + } + $this->db->begin(); @@ -168,8 +184,10 @@ class BookKeeping extends CommonObject $sql .= " WHERE doc_type = '" . $this->doc_type . "'"; $sql .= " AND fk_docdet = " . $this->fk_docdet; $sql .= " AND numero_compte = '" . $this->numero_compte . "'"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } - dol_syslog(get_class($this) . ":: create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -182,6 +200,9 @@ class BookKeeping extends CommonObject $sqlnum .= " WHERE doc_type = '" . $this->doc_type . "'"; $sqlnum .= " AND fk_docdet = '" . $this->fk_docdet . "'"; $sqlnum .= " AND doc_ref = '" . $this->doc_ref . "'"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG); $resqlnum = $this->db->query($sqlnum); @@ -193,7 +214,10 @@ class BookKeeping extends CommonObject if (empty($this->piece_num)) { $sqlnum = "SELECT MAX(piece_num)+1 as maxpiecenum"; $sqlnum .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")"; + } + dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG); $resqlnum = $this->db->query($sqlnum); if ($resqlnum) { @@ -212,7 +236,6 @@ class BookKeeping extends CommonObject } $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " ("; - $sql .= "doc_date"; $sql .= ", doc_type"; $sql .= ", doc_ref"; @@ -229,10 +252,9 @@ class BookKeeping extends CommonObject $sql .= ", import_key"; $sql .= ", code_journal"; $sql .= ", piece_num"; - + $sql .= ', entity'; $sql .= ") VALUES ("; - - $sql .= "'" . $this->doc_date . "'"; + $sql .= "'" . $this->db->idate($this->doc_date) . "'"; $sql .= ",'" . $this->doc_type . "'"; $sql .= ",'" . $this->doc_ref . "'"; $sql .= "," . $this->fk_doc; @@ -245,10 +267,10 @@ class BookKeeping extends CommonObject $sql .= "," . $this->montant; $sql .= ",'" . $this->sens . "'"; $sql .= ",'" . $this->fk_user_author . "'"; - $sql .= ",'" . $this->date_create . "'"; + $sql .= ",'" . $this->db->idate($this->date_create). "'"; $sql .= ",'" . $this->code_journal . "'"; $sql .= "," . $this->piece_num; - + $sql .= ", " . (! isset($this->entity) ? '1' : $this->entity); $sql .= ")"; dol_syslog(get_class($this) . ":: create sql=" . $sql, LOG_DEBUG); @@ -271,11 +293,11 @@ class BookKeeping extends CommonObject $this->errors[] = 'Error ' . $this->db->lasterror(); dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); } - } else { - $result = - 3; - $error ++; - $this->errors[] = 'Error ' . $this->db->lasterror(); - dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + } else { // Already exists + $result = -3; + $error++; + $this->errors[] = 'Error Transaction for ('.$this->doc_type.', '.$this->doc_ref.', '.$this->fk_docdet.') were already recorded'; + dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_WARNING); } } else { $result = - 5; @@ -312,10 +334,9 @@ class BookKeeping extends CommonObject /** * 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 + * @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 createStd(User $user, $notrigger = false) { dol_syslog(__METHOD__, LOG_DEBUG); @@ -369,13 +390,14 @@ class BookKeeping extends CommonObject if (isset($this->piece_num)) { $this->piece_num = trim($this->piece_num); } + if (empty($this->debit)) $this->debit = 0; + if (empty($this->credit)) $this->credit = 0; // Check parameters // Put here code to add control on parameters values // Insert request $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '('; - $sql .= 'doc_date,'; $sql .= 'doc_type,'; $sql .= 'doc_ref,'; @@ -391,27 +413,26 @@ class BookKeeping extends CommonObject $sql .= 'fk_user_author,'; $sql .= 'import_key,'; $sql .= 'code_journal,'; - $sql .= 'piece_num'; - + $sql .= 'piece_num,'; + $sql .= 'entity'; $sql .= ') VALUES ('; - $sql .= ' ' . (! isset($this->doc_date) || dol_strlen($this->doc_date) == 0 ? 'NULL' : "'" . $this->db->idate($this->doc_date) . "'") . ','; $sql .= ' ' . (! isset($this->doc_type) ? 'NULL' : "'" . $this->db->escape($this->doc_type) . "'") . ','; $sql .= ' ' . (! isset($this->doc_ref) ? 'NULL' : "'" . $this->db->escape($this->doc_ref) . "'") . ','; $sql .= ' ' . (empty($this->fk_doc) ? '0' : $this->fk_doc) . ','; $sql .= ' ' . (empty($this->fk_docdet) ? '0' : $this->fk_docdet) . ','; $sql .= ' ' . (! isset($this->code_tiers) ? 'NULL' : "'" . $this->db->escape($this->code_tiers) . "'") . ','; - $sql .= ' ' . (! isset($this->numero_compte) ? 'NULL' : "'" . $this->db->escape($this->numero_compte) . "'") . ','; + $sql .= ' ' . (! isset($this->numero_compte) ? "'NotDefined'" : "'" . $this->db->escape($this->numero_compte) . "'") . ','; $sql .= ' ' . (! isset($this->label_compte) ? 'NULL' : "'" . $this->db->escape($this->label_compte) . "'") . ','; - $sql .= ' ' . (! isset($this->debit) ? 'NULL' : "'" . $this->debit . "'") . ','; - $sql .= ' ' . (! isset($this->credit) ? 'NULL' : "'" . $this->credit . "'") . ','; - $sql .= ' ' . (! isset($this->montant) ? 'NULL' : "'" . $this->montant . "'") . ','; + $sql .= ' ' . (! isset($this->debit) ? 'NULL' : $this->debit ). ','; + $sql .= ' ' . (! isset($this->credit) ? 'NULL' : $this->credit ). ','; + $sql .= ' ' . (! isset($this->montant) ? 'NULL' : $this->montant ). ','; $sql .= ' ' . (! isset($this->sens) ? 'NULL' : "'" . $this->db->escape($this->sens) . "'") . ','; $sql .= ' ' . $user->id . ','; $sql .= ' ' . (! isset($this->import_key) ? 'NULL' : "'" . $this->db->escape($this->import_key) . "'") . ','; - $sql .= ' ' . (! isset($this->code_journal) ? 'NULL' : "'" . $this->db->escape($this->code_journal) . "'") . ','; - $sql .= ' ' . (! isset($this->piece_num) ? 'NULL' : $this->piece_num); - + $sql .= ' ' . (empty($this->code_journal) ? 'NULL' : "'" . $this->db->escape($this->code_journal) . "'") . ','; + $sql .= ' ' . (empty($this->piece_num) ? 'NULL' : $this->piece_num).','; + $sql .= ' ' . (! isset($this->entity) ? '1' : $this->entity); $sql .= ')'; $this->db->begin(); @@ -458,11 +479,12 @@ class BookKeeping extends CommonObject * @return int <0 if KO, 0 if not found, >0 if OK */ public function fetch($id, $ref = null) { - dol_syslog(__METHOD__, LOG_DEBUG); + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); $sql = 'SELECT'; $sql .= ' t.rowid,'; - $sql .= " t.doc_date,"; $sql .= " t.doc_type,"; $sql .= " t.doc_ref,"; @@ -479,12 +501,15 @@ class BookKeeping extends CommonObject $sql .= " t.import_key,"; $sql .= " t.code_journal,"; $sql .= " t.piece_num"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' WHERE 1 = 1'; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } if (null !== $ref) { - $sql .= ' WHERE t.ref = ' . '\'' . $ref . '\''; + $sql .= ' AND t.ref = ' . '\'' . $ref . '\''; } else { - $sql .= ' WHERE t.rowid = ' . $id; + $sql .= ' AND t.rowid = ' . $id; } $resql = $this->db->query($sql); @@ -540,11 +565,12 @@ class BookKeeping extends CommonObject * @return int <0 if KO, >0 if OK */ public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') { - dol_syslog(__METHOD__, LOG_DEBUG); + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); $sql = 'SELECT'; $sql .= ' t.rowid,'; - $sql .= " t.doc_date,"; $sql .= " t.doc_type,"; $sql .= " t.doc_ref,"; @@ -561,9 +587,6 @@ class BookKeeping extends CommonObject $sql .= " t.import_key,"; $sql .= " t.code_journal,"; $sql .= " t.piece_num"; - - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; - // Manage filter $sqlwhere = array (); if (count($filter) > 0) { @@ -585,14 +608,17 @@ class BookKeeping extends CommonObject } } } - - if (count($sqlwhere) > 0) { - $sql .= ' WHERE ' . implode(' ' . $filtermode . ' ', $sqlwhere); + $sql.= ' WHERE 1 = 1'; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; } - // Affichage par compte comptable - $sql .= ' ORDER BY t.numero_compte ASC'; + if (count($sqlwhere) > 0) { + $sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere); + } + // Affichage par compte comptable + $sql .= ' ORDER BY t.numero_compte ASC'; if (! empty($sortfield)) { - $sql .= ', ' . $sortfield . ' ' .$sortorder; + $sql .= ', ' . $sortfield . ' ' .$sortorder; } if (! empty($limit)) { $sql .= ' ' . $this->db->plimit($limit + 1, $offset); @@ -652,11 +678,12 @@ class BookKeeping extends CommonObject * @return int <0 if KO, >0 if OK */ public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') { - dol_syslog(__METHOD__, LOG_DEBUG); + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); $sql = 'SELECT'; $sql .= ' t.rowid,'; - $sql .= " t.doc_date,"; $sql .= " t.doc_type,"; $sql .= " t.doc_ref,"; @@ -673,9 +700,7 @@ class BookKeeping extends CommonObject $sql .= " t.import_key,"; $sql .= " t.code_journal,"; $sql .= " t.piece_num"; - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; - // Manage filter $sqlwhere = array (); if (count($filter) > 0) { @@ -695,9 +720,12 @@ class BookKeeping extends CommonObject } } } - + $sql.= ' WHERE 1 = 1'; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } if (count($sqlwhere) > 0) { - $sql .= ' WHERE ' . implode(' ' . $filtermode . ' ', $sqlwhere); + $sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere); } if (! empty($sortfield)) { @@ -760,16 +788,15 @@ class BookKeeping extends CommonObject * @return int <0 if KO, >0 if OK */ public function fetchAllBalance($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') { - dol_syslog(__METHOD__, LOG_DEBUG); + global $conf; + + dol_syslog(__METHOD__, LOG_DEBUG); $sql = 'SELECT'; $sql .= " t.numero_compte,"; $sql .= " SUM(t.debit) as debit,"; $sql .= " SUM(t.credit) as credit"; - - $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; - // Manage filter $sqlwhere = array (); if (count($filter) > 0) { @@ -789,11 +816,14 @@ class BookKeeping extends CommonObject } } } - - if (count($sqlwhere) > 0) { - $sql .= ' WHERE ' . implode(' ' . $filtermode . ' ', $sqlwhere); + $sql.= ' WHERE 1 = 1'; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; } - + if (count($sqlwhere) > 0) { + $sql .= ' AND ' . implode(' ' . $filtermode . ' ', $sqlwhere); + } + $sql .= ' GROUP BY t.numero_compte'; if (! empty($sortfield)) { @@ -893,7 +923,6 @@ class BookKeeping extends CommonObject // Update request $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET'; - $sql .= ' doc_date = ' . (! isset($this->doc_date) || dol_strlen($this->doc_date) != 0 ? "'" . $this->db->idate($this->doc_date) . "'" : 'null') . ','; $sql .= ' doc_type = ' . (isset($this->doc_type) ? "'" . $this->db->escape($this->doc_type) . "'" : "null") . ','; $sql .= ' doc_ref = ' . (isset($this->doc_ref) ? "'" . $this->db->escape($this->doc_ref) . "'" : "null") . ','; @@ -910,7 +939,6 @@ class BookKeeping extends CommonObject $sql .= ' import_key = ' . (isset($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null") . ','; $sql .= ' code_journal = ' . (isset($this->code_journal) ? "'" . $this->db->escape($this->code_journal) . "'" : "null") . ','; $sql .= ' piece_num = ' . (isset($this->piece_num) ? $this->piece_num : "null"); - $sql .= ' WHERE rowid=' . $this->id; $this->db->begin(); @@ -998,7 +1026,7 @@ class BookKeeping extends CommonObject /** * Delete bookkepping by importkey * - * @param string $importkey Import key + * @param string $importkey Import key * @return int Result */ function deleteByImportkey($importkey) { @@ -1013,10 +1041,7 @@ class BookKeeping extends CommonObject if (! $resql) { $this->errors[] = "Error " . $this->db->lasterror(); - foreach ( $this->errors as $errmsg ) { - dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); - $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); - } + dol_syslog(get_class($this)."::delete Error " . $this->db->lasterror(), LOG_ERR); $this->db->rollback(); return - 1; } @@ -1028,17 +1053,29 @@ class BookKeeping extends CommonObject /** * Delete bookkepping by year * - * @param string $delyear year to delete - * @return int Result + * @param string $delyear Year to delete + * @param string $journal Journal to delete + * @return int <0 if KO, >0 if OK */ - function deleteByYear($delyear) { + function deleteByYearAndJournal($delyear='', $journal='') { + global $conf; + + if (empty($delyear) && empty($journal)) + { + return -1; + } + $this->db->begin(); // first check if line not yet in bookkeeping $sql = "DELETE"; - $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql .= " WHERE YEAR(doc_date) = " . $delyear; - + $sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element; + $sql.= " WHERE 1 = 1"; + if (! empty($delyear)) $sql.= " AND YEAR(doc_date) = " . $delyear; // FIXME Must use between + if (! empty($journal)) $sql.= " AND code_journal = '".$journal."'"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } $resql = $this->db->query($sql); if (! $resql) { @@ -1048,7 +1085,7 @@ class BookKeeping extends CommonObject $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return - 1; + return -1; } $this->db->commit(); @@ -1062,12 +1099,17 @@ class BookKeeping extends CommonObject * @return int Result */ function deleteMvtNum($piecenum) { + global $conf; + $this->db->begin(); // first check if line not yet in bookkeeping $sql = "DELETE"; $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; $sql .= " WHERE piece_num = " . $piecenum; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } $resql = $this->db->query($sql); @@ -1165,9 +1207,14 @@ class BookKeeping extends CommonObject * @return int <0 if KO, >0 if OK */ public function fetchPerMvt($piecenum) { - $sql = "SELECT piece_num,doc_date,code_journal,doc_ref,doc_type"; + global $conf; + + $sql = "SELECT piece_num,doc_date,code_journal,doc_ref,doc_type"; $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; $sql .= " WHERE piece_num = " . $piecenum; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG); $result = $this->db->query($sql); @@ -1191,18 +1238,25 @@ class BookKeeping extends CommonObject /** * Return next number movement * - * @return string Last number + * @return string Next numero to use */ - public function getNextNumMvt() { + public function getNextNumMvt() + { + global $conf; + $sql = "SELECT MAX(piece_num)+1 as max FROM " . MAIN_DB_PREFIX . $this->table_element; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")"; + } dol_syslog(get_class($this) . "getNextNumMvt sql=" . $sql, LOG_DEBUG); $result = $this->db->query($sql); - + if ($result) { $obj = $this->db->fetch_object($result); - - return $obj->max; + if ($obj) $result = $obj->max; + if (empty($result)) $result = 1; + return $result; } else { $this->error = "Error " . $this->db->lasterror(); dol_syslog(get_class($this) . "::getNextNumMvt " . $this->error, LOG_ERR); @@ -1217,12 +1271,17 @@ class BookKeeping extends CommonObject * @return int <0 if KO, >0 if OK */ function fetch_all_per_mvt($piecenum) { + global $conf; + $sql = "SELECT rowid, doc_date, doc_type,"; $sql .= " doc_ref, fk_doc, fk_docdet, code_tiers,"; $sql .= " numero_compte, label_compte, debit, credit,"; $sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num"; $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; $sql .= " WHERE piece_num = " . $piecenum; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; + } dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG); $result = $this->db->query($sql); @@ -1267,11 +1326,16 @@ class BookKeeping extends CommonObject * @return int Result */ function export_bookkeping($model = 'ebp') { + global $conf; + $sql = "SELECT rowid, doc_date, doc_type,"; $sql .= " doc_ref, fk_doc, fk_docdet, code_tiers,"; $sql .= " numero_compte, label_compte, debit, credit,"; $sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num"; $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")"; + } dol_syslog(get_class($this) . "::export_bookkeping", LOG_DEBUG); @@ -1315,75 +1379,76 @@ class BookKeeping extends CommonObject - /** - * Return list of accounts with label by chart of accounts - * - * @param string $selectid Preselected chart of accounts - * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field - * @param array $event Event options - * @param int $select_in $selectid value is a aa.rowid (0 default) or aa.account_number (1) - * @param int $select_out set value returned by select 0=rowid (default), 1=account_number - * @param int $aabase set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number - * - * @return string String with HTML select - */ - function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') { - global $conf; - - require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; - - $pcgver = $conf->global->CHARTOFACCOUNTS; - - $sql = "SELECT DISTINCT ab.numero_compte as account_number, aa.label as label, aa.rowid as rowid, aa.fk_pcg_version"; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.account_number = ab.numero_compte"; - $sql .= " AND aa.active = 1"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; - $sql .= " AND asy.rowid = " . $pcgver; - $sql .= " ORDER BY account_number ASC"; - - dol_syslog(get_class($this) . "::select_account", LOG_DEBUG); - $resql = $this->db->query($sql); - - if (!$resql) { - $this->error = "Error " . $this->db->lasterror(); - dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR); - return -1; - } - - $out = ajax_combobox($htmlname, $event); - - $options = array(); - $selected = null; - - while ($obj = $this->db->fetch_object($resql)) { - $label = length_accountg($obj->account_number) . ' - ' . $obj->label; - $label = dol_trunc($label, $trunclength); - - $select_value_in = $obj->rowid; - $select_value_out = $obj->rowid; - - if ($select_in == 1) { - $select_value_in = $obj->account_number; - } - if ($select_out == 1) { - $select_value_out = $obj->account_number; - } - - // Remember guy's we store in database llx_facturedet the rowid of accounting_account and not the account_number - // Because same account_number can be share between different accounting_system and do have the same meaning - if (($selectid != '') && $selectid == $select_value_in) { - $selected = $select_value_out; - } - - $options[$select_value_out] = $label; - } - - $out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', 'maxwidth300'); - $this->db->free($resql); - return $out; - } + /** + * Return list of accounts with label by chart of accounts + * + * @param string $selectid Preselected chart of accounts + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) + * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number + * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number + * @return string String with HTML select + */ + function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') { + global $conf; + + require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; + + $pcgver = $conf->global->CHARTOFACCOUNTS; + + $sql = "SELECT DISTINCT ab.numero_compte as account_number, aa.label as label, aa.rowid as rowid, aa.fk_pcg_version"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.account_number = ab.numero_compte"; + $sql .= " AND aa.active = 1"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND asy.rowid = " . $pcgver; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND ab.entity IN (" . getEntity("accountancy", 1) . ")"; + } + $sql .= " ORDER BY account_number ASC"; + + dol_syslog(get_class($this) . "::select_account", LOG_DEBUG); + $resql = $this->db->query($sql); + + if (! $resql) { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR); + return - 1; + } + + $out = ajax_combobox($htmlname, $event); + + $options = array(); + $selected = null; + + while ($obj = $this->db->fetch_object($resql)) { + $label = length_accountg($obj->account_number) . ' - ' . $obj->label; + + $select_value_in = $obj->rowid; + $select_value_out = $obj->rowid; + + if ($select_in == 1) { + $select_value_in = $obj->account_number; + } + if ($select_out == 1) { + $select_value_out = $obj->account_number; + } + + // Remember guy's we store in database llx_facturedet the rowid of accounting_account and not the account_number + // Because same account_number can be share between different accounting_system and do have the same meaning + if (($selectid != '') && $selectid == $select_value_in) { + $selected = $select_value_out; + } + + $options[$select_value_out] = $label; + } + + $out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', 'maxwidth300'); + $this->db->free($resql); + return $out; + } @@ -1391,25 +1456,26 @@ class BookKeeping extends CommonObject * Description of a root accounting account * * @param string $account Accounting account - * @return string + * @return string Root account */ function get_compte_racine($account = null) { global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; - - - $sql = "SELECT root.account_number, root.label as label"; - $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa"; - $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; - $sql .= " AND asy.rowid = " . $pcgver; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as parent ON aa.account_parent = parent.rowid"; - $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as root ON parent.account_parent = root.rowid"; - $sql .= " WHERE aa.account_number = '" . $account . "'"; - $sql .= " AND parent.active = 1"; - $sql .= " AND root.active = 1"; - - + + $sql = "SELECT root.account_number, root.label as label"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND asy.rowid = " . $pcgver; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as parent ON aa.account_parent = parent.rowid"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as root ON parent.account_parent = root.rowid"; + $sql .= " WHERE aa.account_number = '" . $account . "'"; + $sql .= " AND parent.active = 1"; + $sql .= " AND root.active = 1"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND aa.entity IN (" . getEntity("accountancy", 1) . ")"; + } + dol_syslog(get_class($this) . "::select_account sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1433,11 +1499,12 @@ class BookKeeping extends CommonObject * Description of accounting account * * @param string $account Accounting account - * @return string + * @return string Account desc */ function get_compte_desc($account = null) { global $conf; + $pcgver = $conf->global->CHARTOFACCOUNTS; $sql = "SELECT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version, cat.label as category"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa "; @@ -1446,6 +1513,10 @@ class BookKeeping extends CommonObject $sql .= " AND asy.rowid = " . $pcgver; $sql .= " AND aa.active = 1"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_accounting_category as cat ON aa.fk_accounting_category = cat.rowid"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE aa.entity IN (" . getEntity("accountancy", 1) . ")"; + } + dol_syslog(get_class($this) . "::select_account sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1469,6 +1540,7 @@ class BookKeeping extends CommonObject } + /** * Class BookKeepingLine */ diff --git a/htdocs/accountancy/class/html.formventilation.class.php b/htdocs/accountancy/class/html.formventilation.class.php index 9294cf7f6a8..fab9e81031d 100644 --- a/htdocs/accountancy/class/html.formventilation.class.php +++ b/htdocs/accountancy/class/html.formventilation.class.php @@ -41,6 +41,9 @@ class FormVentilation extends Form $options = array(); $sql = 'SELECT DISTINCT import_key from ' . MAIN_DB_PREFIX . 'accounting_bookkeeping'; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")"; + } $sql .= ' ORDER BY import_key DESC'; dol_syslog(get_class($this) . "::select_bookkeeping_importkey", LOG_DEBUG); @@ -62,17 +65,16 @@ class FormVentilation extends Form /** * Return list of accounts with label by chart of accounts * - * @param string $selectid Preselected chart of accounts - * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field - * @param array $event Event options - * @param int $select_in $selectid value is a aa.rowid (0 default) or aa.account_number (1) - * @param int $select_out set value returned by select 0=rowid (default), 1=account_number - * @param int $aabase set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number - * + * @param string $selectid Preselected id or code of accounting accounts (depends on $select_in) + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * @param int $select_in selectid value is a aa.rowid (0 default) or aa.account_number (1) + * @param int $select_out set value returned by select 0=rowid (default), 1=account_number + * @param string $morecss More css non HTML object * @return string String with HTML select */ - function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') { + function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone') { global $conf; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; @@ -97,34 +99,37 @@ class FormVentilation extends Form $out = ajax_combobox($htmlname, $event); + // TODO Add $options in cache so next call will not execute the request + $selected = 0; $options = array(); - $selected = null; - - while ($obj = $this->db->fetch_object($resql)) { + while ($obj = $this->db->fetch_object($resql)) + { $label = length_accountg($obj->account_number) . ' - ' . $obj->label; $label = dol_trunc($label, $trunclength); $select_value_in = $obj->rowid; $select_value_out = $obj->rowid; + // Try to guess if we have found default value if ($select_in == 1) { $select_value_in = $obj->account_number; } if ($select_out == 1) { $select_value_out = $obj->account_number; } - // Remember guy's we store in database llx_facturedet the rowid of accounting_account and not the account_number // Because same account_number can be share between different accounting_system and do have the same meaning - if (($selectid != '') && $selectid == $select_value_in) { + if ($selectid != '' && $selectid == $select_value_in) { + //var_dump("Found ".$selectid." ".$select_value_in); $selected = $select_value_out; } $options[$select_value_out] = $label; } - $out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', 'maxwidth300'); + $out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, 1); $this->db->free($resql); + return $out; } @@ -227,6 +232,9 @@ class FormVentilation extends Form // Auxiliary customer account $sql = "SELECT DISTINCT code_compta, nom "; $sql .= " FROM ".MAIN_DB_PREFIX."societe"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("societe", 1) . ")"; + } $sql .= " ORDER BY code_compta"; dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG); $resql = $this->db->query($sql); @@ -246,6 +254,9 @@ class FormVentilation extends Form // Auxiliary supplier account $sql = "SELECT DISTINCT code_compta_fournisseur, nom "; $sql .= " FROM ".MAIN_DB_PREFIX."societe"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("societe", 1) . ")"; + } $sql .= " ORDER BY code_compta_fournisseur"; dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG); $resql = $this->db->query($sql); @@ -280,10 +291,15 @@ class FormVentilation extends Form */ function selectyear_accountancy_bookkepping($selected = '', $htmlname = 'yearid', $useempty = 0, $output_format = 'html') { + global $conf; + $out_array = array(); $sql = "SELECT DISTINCT date_format(doc_date,'%Y') as dtyear"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")"; + } $sql .= " ORDER BY date_format(doc_date,'%Y')"; dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); @@ -308,18 +324,23 @@ class FormVentilation extends Form /** * Return HTML combo list of years existing into book keepping * - * @param string $selected Preselected value - * @param string $htmlname Name of HTML select object - * @param int $useempty Affiche valeur vide dans liste - * @param string $output_format (html/opton (for option html only)/array (to return options arrays + * @param string $selected Preselected value + * @param string $htmlname Name of HTML select object + * @param int $useempty Affiche valeur vide dans liste + * @param string $output_format Html/option (for option html only)/array (to return options arrays * @return string/array */ function selectjournal_accountancy_bookkepping($selected = '', $htmlname = 'journalid', $useempty = 0, $output_format = 'html') { + global $conf,$langs; + $out_array = array(); $sql = "SELECT DISTINCT code_journal"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping"; + if (! empty($conf->multicompany->enabled)) { + $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")"; + } $sql .= " ORDER BY code_journal"; dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); @@ -330,7 +351,7 @@ class FormVentilation extends Form return -1; } while ($obj = $this->db->fetch_object($resql)) { - $out_array[$obj->code_journal] = $obj->code_journal; + $out_array[$obj->code_journal] = $obj->code_journal?$obj->code_journal:$langs->trans("NotDefined"); // TODO Not defined is accepted ? We should avoid this, shouldn't we ? } $this->db->free($resql); diff --git a/htdocs/accountancy/customer/card.php b/htdocs/accountancy/customer/card.php index c49dd7ce78a..ba6173d8ebf 100644 --- a/htdocs/accountancy/customer/card.php +++ b/htdocs/accountancy/customer/card.php @@ -40,26 +40,35 @@ $id = GETPOST('id'); if ($user->societe_id > 0) accessforbidden(); - /* + + +/* * Actions */ -if ($action == 'ventil' && $user->rights->accounting->ventilation->dispatch) { + +if ($action == 'ventil' && $user->rights->accounting->bind->write) { if (! GETPOST('cancel', 'alpha')) { + if ($codeventil < 0) $codeventil = 0; + $sql = " UPDATE " . MAIN_DB_PREFIX . "facturedet"; $sql .= " SET fk_code_ventilation = " . $codeventil; $sql .= " WHERE rowid = " . $id; - dol_syslog("/accounting/customer/card.php sql=" . $sql, LOG_DEBUG); $resql = $db->query($sql); if (! $resql) { setEventMessages($db->lasterror(), null, 'errors'); } + else + { + setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); + } } else { header("Location: ./lines.php"); exit(); } } + /* * View */ @@ -86,9 +95,7 @@ if (! empty($id)) { $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON l.fk_code_ventilation = aa.rowid"; $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = l.fk_facture"; $sql .= " WHERE f.fk_statut > 0 AND l.rowid = " . $id; - if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; - } + $sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; // We don't share object for accountancy dol_syslog("/accounting/customer/card.php sql=" . $sql, LOG_DEBUG); $result = $db->query($sql); diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index 4df2c68243a..08677974a6d 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -25,9 +25,8 @@ * \ingroup Advanced accountancy * \brief Home customer ventilation */ -require '../../main.inc.php'; -// Class +require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; @@ -39,12 +38,15 @@ $langs->load("main"); $langs->load("accountancy"); // Security check +if (empty($conf->accounting->enabled)) { + accessforbidden(); +} if ($user->societe_id > 0) accessforbidden(); -if (! $user->rights->accounting->ventilation->read) +if (! $user->rights->accounting->bind->write) accessforbidden(); - // Filter +// Filter $year = $_GET["year"]; if ($year == 0) { $year_current = strftime("%Y", time()); @@ -56,11 +58,29 @@ if ($year == 0) { // Validate History $action = GETPOST('action'); + + + +/* + * Actions + */ + if ($action == 'validatehistory') { $error = 0; $db->begin(); + // First clean corrupted data + $sqlclean = "UPDATE " . MAIN_DB_PREFIX . "facturedet as fd"; + $sqlclean .= " SET fd.fk_code_ventilation = 0"; + $sqlclean .= ' WHERE fd.fk_code_ventilation NOT IN '; + $sqlclean .= ' (SELECT accnt.rowid '; + $sqlclean .= ' FROM ' . MAIN_DB_PREFIX . 'accounting_account as accnt'; + $sqlclean .= ' INNER JOIN ' . MAIN_DB_PREFIX . 'accounting_system as syst'; + $sqlclean .= ' ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=' . $conf->global->CHARTOFACCOUNTS . ')'; + $resql = $db->query($sqlclean); + + // Now make the binding if ($db->type == 'pgsql') { $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet"; $sql1 .= " SET fk_code_ventilation = accnt.rowid"; @@ -85,7 +105,7 @@ if ($action == 'validatehistory') { setEventMessages($db->lasterror(), null, 'errors'); } else { $db->commit(); - setEventMessages($langs->trans('Dispatched'), null, 'mesgs'); + setEventMessages($langs->trans('AutomaticBindingDone'), null, 'mesgs'); } } elseif ($action == 'fixaccountancycode') { $error = 0; @@ -113,12 +133,13 @@ if ($action == 'validatehistory') { } elseif ($action == 'cleanaccountancycode') { $error = 0; $db->begin(); - + + // Now clean $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as fd"; $sql1 .= " SET fd.fk_code_ventilation = 0"; $sql1 .= " WHERE fd.fk_facture IN ( SELECT f.rowid FROM " . MAIN_DB_PREFIX . "facture as f"; $sql1 .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($year_current, 1, false)) . "'"; - $sql1 .= " AND f.datef <= '" . $db->idate(dol_get_last_day($year_current, 12, false)) . "')"; + $sql1 .= " AND f.datef <= '" . $db->idate(dol_get_last_day($year_current, 12, false)) . "')"; dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG); @@ -133,21 +154,26 @@ if ($action == 'validatehistory') { } } + /* * View */ + llxHeader('', $langs->trans("CustomersVentilation")); $textprevyear = '' . img_previous() . ''; $textnextyear = ' ' . img_next() . ''; -print load_fiche_titre($langs->trans("CustomersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear); +print load_fiche_titre($langs->trans("CustomersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); -print '' . $langs->trans("DescVentilCustomer") . ''; +print $langs->trans("DescVentilCustomer") . '
'; +print $langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")) . '
'; +print '
'; print '
'; print '' . $langs->trans("ValidateHistory") . ''; -print '' . $langs->trans("CleanFixHistory", $year_current) . ''; -print '' . $langs->trans("CleanHistory", $year_current) . ''; +print '' . $langs->trans("CleanHistory", $year_current) . ''; +// TODO Remove this. Should be done into the repair.php script +if ($conf->global->MAIN_FEATURES_LEVEL > 0) print '' . $langs->trans("CleanFixHistory", $year_current) . ''; print '
'; $sql = "SELECT count(*) FROM " . MAIN_DB_PREFIX . "facturedet as fd"; @@ -171,9 +197,9 @@ print ''; print ''; print ''; for($i = 1; $i <= 12; $i ++) { - print ''; + print ''; } -print ''; +print ''; $sql = "SELECT " . $db->ifsql('aa.account_number IS NULL', "'".$langs->trans('NotMatch')."'", 'aa.account_number') . " AS codecomptable,"; $sql .= " " . $db->ifsql('aa.label IS NULL', "'".$langs->trans('NotMatch')."'", 'aa.label') . " AS intitule,"; @@ -186,10 +212,7 @@ $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_factu $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = fd.fk_code_ventilation"; $sql .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; $sql .= " AND f.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; - -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; -} +$sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; // We don't share object for accountancy $sql .= " GROUP BY fd.fk_code_ventilation,aa.account_number,aa.label"; @@ -220,9 +243,9 @@ print "
\n"; print '
' . $langs->trans("Account") . '' . $langs->trans("Label") . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("Total") . '
' . $langs->trans("Total") . '
'; print ''; for($i = 1; $i <= 12; $i ++) { - print ''; + print ''; } -print ''; +print ''; $sql = "SELECT '" . $langs->trans("TotalVente") . "' AS total,"; for($i = 1; $i <= 12; $i ++) { @@ -233,12 +256,9 @@ $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; $sql .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; $sql .= " AND f.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; +$sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; // We don't share object for accountancy -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; -} - -dol_syslog('htdocs/accountancy/customer/index.php:: $sql=' . $sql); +dol_syslog('htdocs/accountancy/customer/index.php'); $resql = $db->query($sql); if ($resql) { $i = 0; @@ -264,9 +284,9 @@ if (! empty($conf->margin->enabled)) { print '
' . $langs->trans("TotalVente") . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("Total") . '
' . $langs->trans("Total") . '
'; print ''; for($i = 1; $i <= 12; $i ++) { - print ''; + print ''; } - print ''; + print ''; $sql = "SELECT '" . $langs->trans("Vide") . "' AS marge,"; for($i = 1; $i <= 12; $i ++) { @@ -277,10 +297,7 @@ if (! empty($conf->margin->enabled)) { $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; $sql .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; $sql .= " AND f.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; - - if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; - } + $sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; // We don't share object for accountancy dol_syslog('htdocs/accountancy/customer/index.php:: $sql=' . $sql); $resql = $db->query($sql); @@ -291,9 +308,9 @@ if (! empty($conf->margin->enabled)) { print ''; for($i = 1; $i <= 12; $i ++) { - print ''; + print ''; } - print ''; + print ''; print ''; } $db->free($resql); diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index 3549651cbd6..d33fc82f3bc 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -3,7 +3,7 @@ * Copyright (C) 2013-2016 Alexandre Spangaro * Copyright (C) 2014-2015 Ari Elbaz (elarifr) * Copyright (C) 2014-2016 Florian Henry - * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2014 Juanjo Menent * * 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 @@ -52,41 +52,36 @@ $search_vat = GETPOST('search_vat', 'alpha'); $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); -// Getpost Order and column and limit page +// Load variable for pagination +$limit = GETPOST('limit') ? GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); $page = GETPOST('page', 'int'); -if ($page < 0) - $page = 0; - +if ($page < 0) $page = 0; $pageprev = $page - 1; $pagenext = $page + 1; -if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { - $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; -} else if ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} else { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} $offset = $limit * $page; - if (! $sortfield) $sortfield = "f.datef, f.facnumber, fd.rowid"; - if (! $sortorder) { if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) { - $sortorder = " DESC "; + $sortorder = "DESC"; } } // Security check if ($user->societe_id > 0) accessforbidden(); -if (! $user->rights->accounting->ventilation->dispatch) +if (! $user->rights->accounting->bind->write) accessforbidden(); $formventilation = new FormVentilation($db); + +/* + * Actions + */ + // Purge search criteria if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { @@ -103,13 +98,13 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both if (is_array($changeaccount) && count($changeaccount) > 0) { $error = 0; - + $db->begin(); - + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as l"; $sql1 .= " SET l.fk_code_ventilation=" . $account_parent; $sql1 .= ' WHERE l.rowid IN (' . implode(',', $changeaccount) . ')'; - + dol_syslog('accountancy/customer/lines.php::changeaccount sql= ' . $sql1); $resql1 = $db->query($sql1); if (! $resql1) { @@ -123,6 +118,8 @@ if (is_array($changeaccount) && count($changeaccount) > 0) { $db->rollback(); setEventMessages($db->lasterror(), null, 'errors'); } + + $account_parent = ''; // Protection to avoid to mass apply it a second time } /* @@ -148,10 +145,6 @@ print ''; -/* - * Action - */ - /* * Customer Invoice lines */ @@ -167,9 +160,7 @@ $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_factu $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as co ON co.rowid = s.fk_pays "; $sql .= " WHERE fd.fk_code_ventilation > 0 "; -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; -} +$sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")"; @@ -203,28 +194,28 @@ if (strlen(trim($search_country))) { if (strlen(trim($search_tvaintra))) { $sql .= " AND (s.tva_intra like'" . $search_tvaintra . "%')"; } -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; -} -// Count total nb of records with no order and no limits -$nbtotalofrecords = 0; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $resql = $db->query($sql); - if ($resql) - $nbtotalofrecords = $db->num_rows($resql); - else - dol_print_error($db); -} +$sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; // We don't share object for accountancy $sql .= $db->order($sortfield, $sortorder); + +// Count total nb of records +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + $sql .= $db->plimit($limit + 1, $offset); -dol_syslog("/accountancy/customer/lines.php sql=" . $sql, LOG_DEBUG); +dol_syslog("/accountancy/customer/lines.php", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num_lines = $db->num_rows($result); $i = 0; - - $param = ""; + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($search_invoice) $param .= "&search_invoice=" . $search_invoice; if ($search_ref) @@ -243,69 +234,82 @@ if ($result) { $param .= "&search_tvaintra=" . $search_tvaintra; - print_barre_liste($langs->trans("InvoiceLinesDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords); - print ''; - - print ''; - print '
' . $langs->trans("TotalMarge") . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("Total") . '
' . $langs->trans("Total") . '
' . $row[0] . '' . price($row[$i]) . '' . price(price2num($row[$i])) . '' . price($row[13]) . '' . price(price2num($row[13])) . '
' . $langs->trans("DescVentilDoneCustomer") . '
'; + print '' . "\n"; + print ''; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print_barre_liste($langs->trans("InvoiceLinesDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit); + print $langs->trans("DescVentilDoneCustomer") . '
'; + print '
' . $langs->trans("ChangeAccount") . '
'; print $formventilation->select_account($account_parent, 'account_parent', 1); - print '
'; + print ''; + + $moreforfilter = ''; + + print '
'."\n"; print ''; print_liste_field_titre($langs->trans("Invoice"), $_SERVER["PHP_SELF"], "f.facnumber", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Ref"), $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Label"), $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "fd.description", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "fd.total_ht", "", $param, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "fd.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("VATRate"), $_SERVER["PHP_SELF"], "fd.tva_tx", "", $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Account"), $_SERVER["PHP_SELF"], "aa.account_number", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Country"), $_SERVER["PHP_SELF"], "co.label", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("IntracommunityVATNumber"), $_SERVER["PHP_SELF"], "s.tva_intra", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Ventilate") . '
/', '', '', '', '', 'align="center"'); + print_liste_field_titre($langs->trans("Country"), $_SERVER["PHP_SELF"], "co.label", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("VATIntra"), $_SERVER["PHP_SELF"], "s.tva_intra", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("LineId"), $_SERVER["PHP_SELF"], "fd.rowid", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre('', '', '', '', '', 'align="center"'); print "\n"; - + print ''; print ''; print ''; print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print '\n"; - + $facture_static = new Facture($db); $product_static = new Product($db); - + $var = True; while ( $objp = $db->fetch_object($result) ) { $var = ! $var; $codecompta = length_accountg($objp->account_number) . ' - ' . $objp->label_compte; - - print ''; - + + print ''; + // Ref Invoice $facture_static->ref = $objp->facnumber; - $facture_static->id = $objp->facid; + $facture_static->id = $objp->rowid; print ''; - + // Ref Product $product_static->ref = $objp->product_ref; $product_static->id = $objp->product_id; - $product_static->type = $objp->type; + $product_static->type = $objp->product_type; + $product_static->label = $objp->product_label; print ''; - + print ''; print ''; print ''; @@ -313,10 +317,11 @@ if ($result) { print ''; - print ''; - print ''; - print ''; - + print ''; + print ''; + print ''; + print ''; + print ""; $i ++; } @@ -324,11 +329,14 @@ if ($result) { print $db->error(); } -print "
%'; - print ''; + print ''; + $searchpitco=$form->showFilterAndCheckAddButtons(1); + print $searchpitco; print "
' . $facture_static->getNomUrl(1) . ''; if ($product_static->id) print $product_static->getNomUrl(1); else print ' '; print '' . dol_trunc($objp->product_label, 24) . '' . nl2br(dol_trunc($objp->description, 32)) . '' . price($objp->total_ht) . '' . $codecompta . ''; print img_edit(); print '' . $objp->country .'' . $objp->tva_intra . '' . $objp->country .'' . $objp->tva_intra . '' . $objp->rowid . '
"; +print ""; -if ($num_lines > $conf->liste_limit) { - print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, ''); +if ($nbtotalofrecords > $limit) { + print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, '', 0, '', '', $limit, 1); } +print ''; + + llxFooter(); $db->close(); diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index 0c1a4d1eb6b..7c718c54bfb 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -4,6 +4,7 @@ * Copyright (C) 2014-2015 Ari Elbaz (elarifr) * Copyright (C) 2013-2014 Florian Henry * Copyright (C) 2014 Juanjo Menent + * 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 @@ -43,7 +44,6 @@ $langs->load("accountancy"); $action = GETPOST('action'); // Select Box -$codeventil = GETPOST('codeventil', 'array'); $mesCasesCochees = GETPOST('mesCasesCochees', 'array'); // Search Getpost @@ -56,35 +56,27 @@ $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', 'alpha'); $btn_ventil = GETPOST('ventil', 'alpha'); -// Getpost Order and column and limit page +// Load variable for pagination +$limit = GETPOST('limit') ? GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); -if ($page < 0) - $page = 0; - -if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { - $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; -} else if ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} else { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} +$page = GETPOST('page','int'); +if ($page < 0) { $page = 0; } $offset = $limit * $page; - +$pageprev = $page - 1; +$pagenext = $page + 1; if (! $sortfield) $sortfield = "f.datef, f.facnumber, l.rowid"; - if (! $sortorder) { if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO > 0) { - $sortorder = " DESC "; + $sortorder = "DESC"; } } // Security check if ($user->societe_id > 0) accessforbidden(); -if (! $user->rights->accounting->ventilation->dispatch) +if (! $user->rights->accounting->bind->write) accessforbidden(); $formventilation = new FormVentilation($db); @@ -92,8 +84,14 @@ $accounting = new AccountingAccount($db); $aarowid_s = $accounting->fetch('', $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT, 1); $aarowid_p = $accounting->fetch('', $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT, 1); + +/* + * Action + */ + // Purge search criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) { +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +{ $search_ref = ''; $search_invoice = ''; $search_label = ''; @@ -103,79 +101,63 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) { $search_vat = ''; } +if ($action == 'ventil' && ! empty($btn_ventil)) { + $msg=''; + //print '
' . $langs->trans("Processing") . '...
'; + if (! empty($mesCasesCochees)) { + $msg = '
' . $langs->trans("SelectedLines") . ': '.count($_POST["mesCasesCochees"]).'
'; + $msg.='
'; + $cpt = 0; + $ok=0; + $ko=0; + + foreach ($mesCasesCochees as $maLigneCochee) { + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monCompte = GETPOST('codeventil'.$monId); + + if ($monCompte <= 0) + { + $msg.= '
' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NoAccountSelected") . '
'; + $ko++; + } + else + { + $sql = " UPDATE " . MAIN_DB_PREFIX . "facturedet"; + $sql .= " SET fk_code_ventilation = " . $monCompte; + $sql .= " WHERE rowid = " . $monId; + + $accountventilated = new AccountingAccount($db); + $accountventilated->fetch($monCompte, ''); + + dol_syslog("/accountancy/customer/list.php sql=" . $sql, LOG_DEBUG); + if ($db->query($sql)) { + $msg.= '
' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("VentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
'; + $ok++; + } else { + $msg.= '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NotVentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
' . $sql . '
'; + $ko++; + } + } + + $cpt++; + } + $msg.='
'; + } else { + setEventMessages($langs->trans("NoRecordSelected"), null, 'warnings'); + } + $msg.= '
' . $langs->trans("EndProcessing") . '
'; +} + + + /* * View */ + llxHeader('', $langs->trans("Ventilation")); -print ''; - -/* - * Action - */ -if ($action == 'ventil' && ! empty($btn_ventil)) { - print '
' . $langs->trans("Processing") . '...
'; - if (! empty($codeventil) && ! empty($mesCasesCochees)) { - print '
' . count($mesCasesCochees) . ' ' . $langs->trans("SelectedLines") . '
'; - $mesCodesVentilChoisis = $codeventil; - $cpt = 0; - - foreach ( $mesCasesCochees as $maLigneCochee ) { - $maLigneCourante = explode("_", $maLigneCochee); - $monId = $maLigneCourante[0]; - $monNumLigne = $maLigneCourante[1]; - $monCompte = $mesCodesVentilChoisis[$monNumLigne]; - - $sql = " UPDATE " . MAIN_DB_PREFIX . "facturedet"; - $sql .= " SET fk_code_ventilation = " . $monCompte; - $sql .= " WHERE rowid = " . $monId; - - $accountventilated = new AccountingAccount($db); - $accountventilated->fetch($monCompte, ''); - - dol_syslog("/accountancy/customer/list.php sql=" . $sql, LOG_DEBUG); - if ($db->query($sql)) { - print '
' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("VentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
'; - } else { - print '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NotVentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
' . $sql . '
'; - } - - $cpt ++; - } - } else { - print '
' . $langs->trans("AnyLineVentilate") . '
'; - } - print '
' . $langs->trans("EndProcessing") . '
'; -} - -/* - * Customer Invoice lines - */ -if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { - $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; -} else if ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} else { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} - -$offset = $limit * $page; - +// Customer Invoice lines $sql = "SELECT f.facnumber, f.rowid as facid, f.datef, f.type as ftype, l.fk_product, l.description, l.total_ht, l.rowid, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line,"; $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_sell as code_sell, p.tva_tx as tva_tx_prod,"; $sql .= " aa.rowid as aarowid"; @@ -184,11 +166,9 @@ $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facturedet as l ON f.rowid = l.fk_fac $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON p.accountancy_code_sell = aa.account_number"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_system as accsys ON accsys.pcg_version = aa.fk_pcg_version"; -$sql .= " WHERE f.fk_statut > 0"; -$sql .= " AND l.fk_code_ventilation <= 0"; +$sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; $sql .= " AND product_type <= 2"; $sql .= " AND (accsys.rowid='" . $conf->global->CHARTOFACCOUNTS . "' OR p.accountancy_code_sell IS NULL OR p.accountancy_code_sell ='')"; - // Add search filter like if (strlen(trim($search_invoice))) { $sql .= " AND (f.facnumber like '%" . $search_invoice . "%')"; @@ -211,53 +191,78 @@ if (strlen(trim($search_account))) { if (strlen(trim($search_vat))) { $sql .= " AND (l.tva_tx like '" . $search_vat . "%')"; } - -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; -} +$sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; // We don't share object for accountancy $sql .= $db->order($sortfield, $sortorder); +// Count total nb of records +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + $sql .= $db->plimit($limit + 1, $offset); -dol_syslog("/accountancy/customer/list.php sql=" . $sql, LOG_DEBUG); +dol_syslog("/accountancy/customer/list.php", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num_lines = $db->num_rows($result); $i = 0; - print_barre_liste($langs->trans("InvoiceLines"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); - print '
' . $langs->trans("DescVentilTodoCustomer") . '
'; + $arrayofselected=is_array($toselect)?$toselect:array(); + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; print '
' . "\n"; print ''; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + + $center='
'; + + print_barre_liste($langs->trans("InvoiceLines"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num_lines, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit); - print ''; + print $langs->trans("DescVentilTodoCustomer") . '

'; + + if ($msg) print $msg.'
'; + + $moreforfilter = ''; + + print '
'."\n"; print ''; print_liste_field_titre($langs->trans("Invoice"), $_SERVER["PHP_SELF"], "f.facnumber", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Ref"), $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Label"), $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "l.description", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "l.total_ht", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("VATRate"), $_SERVER["PHP_SELF"], "l.tva_tx", "", $param, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "l.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("VATRate"), $_SERVER["PHP_SELF"], "l.tva_tx", "", $param, 'align="right"', $sortfield, $sortorder); print_liste_field_titre($langs->trans("AccountAccountingSuggest"), '', '', '', '', 'align="center"'); print_liste_field_titre($langs->trans("IntoAccount"), '', '', '', '', 'align="center"'); - print_liste_field_titre(''); - print_liste_field_titre($langs->trans("Ventilate") . '
/', '', '', '', '', 'align="center"'); + print_liste_field_titre($langs->trans("LineId"), $_SERVER["PHP_SELF"], "l.rowid", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre('', '', '', '', '', 'align="center"'); print ''; // We add search filter print ''; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; @@ -302,7 +307,7 @@ if ($result) { if ($objp->code_sell_l != $objp->code_sell_p) $code_sell_p_l_differ = 'color:red'; - print ''; + print ''; // Ref Invoice $facture_static->ref = $objp->facnumber; @@ -325,35 +330,45 @@ if ($result) { print ''; $trunclength = defined('ACCOUNTING_LENGTH_DESCRIPTION') ? ACCOUNTING_LENGTH_DESCRIPTION : 32; print ''; + print ''; + + // Vat rate if ($objp->vat_tx_l != $objp->vat_tx_p) $code_vat_differ = 'font-weight:bold; text-decoration:blink; color:red'; - print ''; + + // Accounting account suggested print ''; print ''; + + // Line id print ''; - print ''; print ''; $i ++; } print '
%'; - print ''; - print ' '; - print ''; + print '%'; + $searchpitco=$form->showFilterAndCheckAddButtons(1); + print $searchpitco; print '
' . dol_trunc($objp->product_label, 24) . '' . nl2br(dol_trunc($objp->description, $trunclength)) . ''; print price($objp->total_ht); print ''; + print ''; print price($objp->tva_tx_line); print ''; - if ($objp->code_sell_l == $objp->code_sell_p) { - print $objp->code_sell_l; + if ($objp->code_sell_l == $objp->code_sell_p) { // Test if there is a difference between code by default and code on product + if ($objp->code_sell_l > 0) print $objp->code_sell_l; + else print $langs->trans("Unknown"); } else { - print $langs->trans("Buy") . ' = ' . $objp->code_sell_l . '
' . $langs->trans("Sell") . ' = ' . $objp->code_sell_p; + print $langs->trans("Default") . ' = ' . ($objp->code_sell_l > 0 ? $objp->code_sell_l : $langs->trans("Unknown")); + print '
'; + print $langs->trans("Product") . ' = ' . ($objp->code_sell_p > 0 ? $objp->code_sell_p : $langs->trans("Unknown")); } print '
'; - print $formventilation->select_account($objp->aarowid_suggest, 'codeventil[]', 1); + print $formventilation->select_account($objp->aarowid_suggest, 'codeventil'.$objp->rowid, 1); print '' . $objp->rowid . ''; - print 'aarowid ? "checked" : "") . '/>'; + + print ''; + print 'aarowid ? "checked" : "") . '/>'; print '
'; - print '
'; print '
'; } else { print $db->error(); diff --git a/htdocs/accountancy/expensereport/card.php b/htdocs/accountancy/expensereport/card.php new file mode 100644 index 00000000000..4819bd656ae --- /dev/null +++ b/htdocs/accountancy/expensereport/card.php @@ -0,0 +1,162 @@ + + * Copyright (C) 2005 Simon TOSSER + * Copyright (C) 2013-2016 Alexandre Spangaro + * Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2015 Jean-François Ferry + * + * 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/accountancy/supplier/card.php + * \ingroup Accountancy + * \brief Card expense report ventilation + */ +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/html.formventilation.class.php'; + +// Langs +$langs->load("bills"); +$langs->load("accountancy"); +$langs->load("trips"); + +$action = GETPOST('action', 'alpha'); +$codeventil = GETPOST('codeventil'); +$id = GETPOST('id'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +/* + * Actions + */ + +if ($action == 'ventil' && $user->rights->accounting->bind->write) { + if (! GETPOST('cancel', 'alpha')) { + if ($codeventil < 0) $codeventil = 0; + + $sql = " UPDATE " . MAIN_DB_PREFIX . "expensereport_det"; + $sql .= " SET fk_code_ventilation = " . $codeventil; + $sql .= " WHERE rowid = " . $id; + + $resql = $db->query($sql); + if (! $resql) { + setEventMessages($db->lasterror(), null, 'errors'); + } + else + { + setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); + } + } else { + header("Location: ./lines.php"); + exit(); + } +} + + + +/* + * View + */ +llxHeader("", "FicheVentilation"); + +if ($cancel == $langs->trans("Cancel")) { + $action = ''; +} + +// Create +$form = new Form($db); +$expensereport_static = new ExpenseReport($db); +$formventilation = new FormVentilation($db); + +if (! empty($id)) { + $sql = "SELECT er.ref, er.rowid as facid, erd.fk_c_type_fees, erd.comments, erd.rowid, erd.fk_code_ventilation,"; + $sql .= " f.id as fees_id, f.label as fees_label,"; + $sql .= " aa.account_number, aa.label"; + $sql .= " FROM " . MAIN_DB_PREFIX . "expensereport_det as erd"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_type_fees as f ON f.id = erd.fk_c_type_fees"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON erd.fk_code_ventilation = aa.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "expensereport as er ON er.rowid = erd.fk_expensereport"; + $sql .= " WHERE er.fk_statut > 0 AND erd.rowid = " . $id; + $sql .= " AND er.entity IN (" . getEntity("expensereport", 0) . ")"; // We don't share object for accountancy + + dol_syslog("/accounting/expensereport/card.php sql=" . $sql, LOG_DEBUG); + $result = $db->query($sql); + + if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + if ($num_lines) { + $objp = $db->fetch_object($result); + + print '
' . "\n"; + print ''; + print ''; + + print load_fiche_titre($langs->trans('ExpenseReportsVentilation'), '', 'title_setup'); + + dol_fiche_head(); + + print ''; + + // Ref + print ''; + $expensereport_static->ref = $objp->ref; + $expensereport_static->id = $objp->erid; + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print '
' . $langs->trans("ExpenseReport") . '' . $expensereport_static->getNomUrl(1) . '
' . $langs->trans("Line") . '' . stripslashes(nl2br($objp->rowid)) . '
' . $langs->trans("Description") . '' . stripslashes(nl2br($objp->comments)) . '
' . $langs->trans("TypeFees") . '' . dol_trunc($objp->fees_label, 24) . '
' . $langs->trans("Account") . ''; + print $formventilation->select_account($objp->fk_code_ventilation, 'codeventil', 1); + print '
'; + + dol_fiche_end(); + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + + print '
'; + } else { + print "Error"; + } + } else { + print "Error"; + } +} else { + print "Error ID incorrect"; +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/expensereport/index.html b/htdocs/accountancy/expensereport/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/expensereport/index.php b/htdocs/accountancy/expensereport/index.php new file mode 100644 index 00000000000..affb3971c08 --- /dev/null +++ b/htdocs/accountancy/expensereport/index.php @@ -0,0 +1,267 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2016 Alexandre Spangaro + * Copyright (C) 2014 Juanjo Menent + * + * 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/accountancy/expensereport/index.php + * \ingroup Advanced accountancy + * \brief Home expense report ventilation + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if (empty($conf->accounting->enabled)) { + accessforbidden(); +} +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->bind->write) + accessforbidden(); + +// Filter +$year = $_GET["year"]; +if ($year == 0) { + $year_current = strftime("%Y", time()); + $year_start = $year_current; +} else { + $year_current = $year; + $year_start = $year; +} + +// Validate History +$action = GETPOST('action'); + + +/* + * Actions + */ + +if ($action == 'validatehistory') { + + $error = 0; + $db->begin(); + + // First clean corrupted data + $sqlclean = "UPDATE " . MAIN_DB_PREFIX . "facturedet as fd"; + $sqlclean .= " SET fd.fk_code_ventilation = 0"; + $sqlclean .= ' WHERE fd.fk_code_ventilation NOT IN '; + $sqlclean .= ' (SELECT accnt.rowid '; + $sqlclean .= ' FROM ' . MAIN_DB_PREFIX . 'accounting_account as accnt'; + $sqlclean .= ' INNER JOIN ' . MAIN_DB_PREFIX . 'accounting_system as syst'; + $sqlclean .= ' ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=' . $conf->global->CHARTOFACCOUNTS . ')'; + $resql = $db->query($sqlclean); + + // Now make the binding + if ($db->type == 'pgsql') { + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det"; + $sql1 .= " SET fk_code_ventilation = accnt.rowid"; + $sql1 .= " FROM " . MAIN_DB_PREFIX . "product as p, " . MAIN_DB_PREFIX . "accounting_account as accnt , " . MAIN_DB_PREFIX . "accounting_system as syst"; + $sql1 .= " WHERE " . MAIN_DB_PREFIX . "facture_fourn_det.fk_product = p.rowid AND accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=" . $conf->global->CHARTOFACCOUNTS; + $sql1 .= " AND accnt.active = 1 AND p.accountancy_code_buy=accnt.account_number"; + $sql1 .= " AND " . MAIN_DB_PREFIX . "facture_fourn_det.fk_code_ventilation = 0"; + } else { + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as fd, " . MAIN_DB_PREFIX . "product as p, " . MAIN_DB_PREFIX . "accounting_account as accnt , " . MAIN_DB_PREFIX . "accounting_system as syst"; + $sql1 .= " SET fd.fk_code_ventilation = accnt.rowid"; + $sql1 .= " WHERE fd.fk_product = p.rowid AND accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=" . $conf->global->CHARTOFACCOUNTS; + $sql1 .= " AND accnt.active = 1 AND p.accountancy_code_buy=accnt.account_number"; + $sql1 .= " AND fd.fk_code_ventilation = 0"; + } + + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + $db->rollback(); + setEventMessages($db->lasterror(), null, 'errors'); + } else { + $db->commit(); + setEventMessages($langs->trans('AutomaticBindingDone'), null, 'mesgs'); + } +} elseif ($action == 'fixaccountancycode') { + $error = 0; + $db->begin(); + + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as fd"; + $sql1 .= " SET fd.fk_code_ventilation = 0"; + $sql1 .= ' WHERE fd.fk_code_ventilation NOT IN '; + $sql1 .= ' (SELECT accnt.rowid '; + $sql1 .= ' FROM ' . MAIN_DB_PREFIX . 'accounting_account as accnt'; + $sql1 .= ' INNER JOIN ' . MAIN_DB_PREFIX . 'accounting_system as syst'; + $sql1 .= ' ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=' . $conf->global->CHARTOFACCOUNTS . ')'; + + dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG); + + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + $db->rollback(); + setEventMessage($db->lasterror(), 'errors'); + } else { + $db->commit(); + setEventMessage($langs->trans('Done'), 'mesgs'); + } +} elseif ($action == 'cleanaccountancycode') { + $error = 0; + $db->begin(); + + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as fd"; + $sql1 .= " SET fd.fk_code_ventilation = 0"; + $sql1 .= " WHERE fd.fk_facture_fourn IN ( SELECT f.rowid FROM " . MAIN_DB_PREFIX . "facture_fourn as f"; + $sql1 .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($year_current, 1, false)) . "'"; + $sql1 .= " AND f.datef <= '" . $db->idate(dol_get_last_day($year_current, 12, false)) . "')"; + + dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG); + + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + $db->rollback(); + setEventMessage($db->lasterror(), 'errors'); + } else { + $db->commit(); + setEventMessage($langs->trans('Done'), 'mesgs'); + } +} + +/* + * View + */ + +llxHeader('', $langs->trans("ExpenseReportsVentilation")); + +$textprevyear = '' . img_previous() . ''; +$textnextyear = ' ' . img_next() . ''; + +print load_fiche_titre($langs->trans("ExpenseReportsVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); + +print $langs->trans("DescVentilExpenseReport") . '
'; +print $langs->trans("DescVentilExpenseReportMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")) . '
'; +print '
'; + +print '
'; +print '' . $langs->trans("ValidateHistory") . ''; +print '' . $langs->trans("CleanHistory", $year_current) . ''; +// TODO Remove this. Should be done always. +if ($conf->global->MAIN_FEATURES_LEVEL > 0) print '' . $langs->trans("CleanFixHistory", $year_current) . ''; +print '
'; + +$y = $year_current; + +$var = true; + +print ''; +print ''; +print ''; +for($i = 1; $i <= 12; $i ++) { + print ''; +} +print ''; + +$sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'".$langs->trans('NotMatch')."'", 'aa.account_number') ." AS codecomptable,"; +$sql .= " " . $db->ifsql('aa.label IS NULL', "'".$langs->trans('NotMatch')."'", 'aa.label') . " AS intitule,"; +for($i = 1; $i <= 12; $i ++) { + $sql .= " SUM(" . $db->ifsql('MONTH(er.date_create)=' . $i, 'erd.total_ht', '0') . ") AS month" . str_pad($i, 2, '0', STR_PAD_LEFT) . ","; +} +$sql .= " ROUND(SUM(erd.total_ht),2) as total"; +$sql .= " FROM " . MAIN_DB_PREFIX . "expensereport_det as erd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "expensereport as er ON er.rowid = erd.fk_expensereport"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = erd.fk_code_ventilation"; +$sql .= " WHERE er.date_create >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; +$sql .= " AND er.date_create <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; +$sql .= " AND er.fk_statut > 0 "; +$sql .= " AND er.entity IN (" . getEntity("expensereport", 0) . ")"; // We don't share object for accountancy + +$sql .= " GROUP BY erd.fk_code_ventilation,aa.account_number,aa.label"; + +dol_syslog('/accountancy/expensereport/index.php:: sql=' . $sql); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + + while ( $row = $db->fetch_row($resql)) { + + $var = ! $var; + print ''; + print ''; + for($i = 2; $i <= 12; $i ++) { + print ''; + } + print ''; + print ''; + print ''; + } + $db->free($resql); +} else { + print $db->lasterror(); // Show last sql error +} +print "
' . $langs->trans("Account") . '' . $langs->trans("Label") . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("Total") . '
' . length_accountg($row[0]) . '' . $row[1] . '' . price($row[$i]) . '' . price($row[13]) . '' . price($row[14]) . '
\n"; + +print "
\n"; +print ''; +print ''; +for($i = 1; $i <= 12; $i ++) { + print ''; +} +print ''; + +$sql = "SELECT '" . $langs->trans("TotalExpenseReport") . "' AS label,"; +for($i = 1; $i <= 12; $i ++) { + $sql .= " SUM(" . $db->ifsql('MONTH(er.date_create)=' . $i, 'erd.total_ht', '0') . ") AS month" . str_pad($i, 2, '0', STR_PAD_LEFT) . ","; +} +$sql .= " ROUND(SUM(erd.total_ht),2) as total"; +$sql .= " FROM " . MAIN_DB_PREFIX . "expensereport_det as erd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "expensereport as er ON er.rowid = erd.fk_expensereport"; +$sql .= " WHERE er.date_create >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; +$sql .= " AND er.date_create <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; +$sql .= " AND er.fk_statut > 0 "; +$sql .= " AND er.entity IN (" . getEntity("expensereport", 0) . ")"; // We don't share object for accountancy + +dol_syslog('/accountancy/expensereport/index.php:: sql=' . $sql); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + + while ( $row = $db->fetch_row($resql)) { + + + print ''; + for($i = 1; $i <= 12; $i ++) { + print ''; + } + print ''; + print ''; + } + + $db->free($resql); +} else { + print $db->lasterror(); // Show last sql error +} +print "
' . $langs->trans("Total") . '' . $langs->trans('MonthShort' . str_pad($i, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("Total") . '
' . $row[0] . '' . price($row[$i]) . '' . price($row[13]) . '
\n"; + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php new file mode 100644 index 00000000000..9720aba485d --- /dev/null +++ b/htdocs/accountancy/expensereport/lines.php @@ -0,0 +1,309 @@ + + * Copyright (C) 2013-2016 Alexandre Spangaro + * Copyright (C) 2014-2015 Ari Elbaz (elarifr) + * Copyright (C) 2013-2016 Florian Henry + * Copyright (C) 2014 Juanjo Menent + * + * 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/accountancy/expensereport/lines.php + * \ingroup Advanced accountancy + * \brief Page of detail of the lines of ventilation of expense reports + */ +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/html.formventilation.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'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); +$langs->load("trips"); + +$account_parent = GETPOST('account_parent'); +$changeaccount = GETPOST('changeaccount'); +// Search Getpost +$search_expensereport = GETPOST('search_expensereport', 'alpha'); +$search_label = GETPOST('search_label', 'alpha'); +$search_desc = GETPOST('search_desc', 'alpha'); +$search_amount = GETPOST('search_amount', 'alpha'); +$search_account = GETPOST('search_account', 'alpha'); +$search_vat = GETPOST('search_vat', 'alpha'); + +// Load variable for pagination +$limit = GETPOST('limit') ? GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOST('page', 'int'); +if ($page < 0) $page = 0; +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) + $sortfield = "er.date_create, er.ref, erd.rowid"; +if (! $sortorder) { + if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) { + $sortorder = "DESC"; + } +} + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->bind->write) + accessforbidden(); + +$formventilation = new FormVentilation($db); + + +/* + * Actions + */ + +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_expensereport = ''; + $search_label = ''; + $search_desc = ''; + $search_amount = ''; + $search_account = ''; + $search_vat = ''; +} + +if (is_array($changeaccount) && count($changeaccount) > 0) { + $error = 0; + + $db->begin(); + + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "expensereport_det as erd"; + $sql1 .= " SET erd.fk_code_ventilation=" . GETPOST('account_parent'); + $sql1 .= ' WHERE erd.rowid IN (' . implode(',', $changeaccount) . ')'; + + dol_syslog('accountancy/expensereport/lines.php::changeaccount sql= ' . $sql1); + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + setEventMessages($db->lasterror(), null, 'errors'); + } + if (! $error) { + $db->commit(); + setEventMessages($langs->trans('Save'), null, 'mesgs'); + } else { + $db->rollback(); + setEventMessages($db->lasterror(), null, 'errors'); + } + + $account_parent = ''; // Protection to avoid to mass apply it a second time +} + + +/* + * View + */ + +llxHeader('', $langs->trans("ExpenseReportsVentilation") . ' - ' . $langs->trans("Dispatched")); + +print ''; + +/* + * Expense reports lines + */ +$sql = "SELECT er.ref, er.rowid as erid, erd.rowid, erd.fk_c_type_fees, erd.comments, erd.total_ht, erd.fk_code_ventilation, erd.tva_tx, aa.label, aa.account_number, "; +$sql .= " f.id as fees_id, f.label as fees_label"; +$sql .= " FROM " . MAIN_DB_PREFIX . "expensereport as er"; +$sql .= " , " . MAIN_DB_PREFIX . "accounting_account as aa"; +$sql .= " , " . MAIN_DB_PREFIX . "expensereport_det as erd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_type_fees as f ON f.id = erd.fk_c_type_fees"; +$sql .= " WHERE er.rowid = erd.fk_expensereport and er.fk_statut >= 5 AND erd.fk_code_ventilation <> 0 "; +$sql .= " AND aa.rowid = erd.fk_code_ventilation"; +if (strlen(trim($search_expensereport))) { + $sql .= " AND er.ref like '%" . $search_expensereport . "%'"; +} +if (strlen(trim($search_label))) { + $sql .= " AND f.label like '%" . $search_label . "%'"; +} +if (strlen(trim($search_desc))) { + $sql .= " AND er.comments like '%" . $search_desc . "%'"; +} +if (strlen(trim($search_amount))) { + $sql .= " AND erd.total_ht like '%" . $search_amount . "%'"; +} +if (strlen(trim($search_account))) { + $sql .= " AND aa.account_number like '%" . $search_account . "%'"; +} +if (strlen(trim($search_vat))) { + $sql .= " AND (erd.tva_tx like '" . $search_vat . "%')"; +} +$sql .= " AND er.entity IN (" . getEntity("expensereport", 0) . ")"; // We don't share object for accountancy + +$sql .= $db->order($sortfield, $sortorder); + +// Count total nb of records +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog('accountancy/expensereport/lines.php::list'); +$result = $db->query($sql); + +if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($search_expensereport) + $param .= "&search_expensereport=" . $search_expensereport; + if ($search_label) + $param .= "&search_label=" . $search_label; + if ($search_desc) + $param .= "&search_desc=" . $search_desc; + if ($search_account) + $param .= "&search_account=" . $search_account; + if ($search_vat) + $param .= "&search_vat=" . $search_vat; + if ($search_country) + $param .= "&search_country=" . $search_country; + if ($search_tvaintra) + $param .= "&search_tvaintra=" . $search_tvaintra; + + print '
' . "\n"; + print ''; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + + print_barre_liste($langs->trans("ExpenseReportLinesDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit); + + print $langs->trans("DescVentilDoneExpenseReport") . '
'; + + print '
' . $langs->trans("ChangeAccount") . '
'; + print $formventilation->select_account(GETPOST('account_parent'), 'account_parent', 1); + print '
'; + + $moreforfilter = ''; + + print ''."\n"; + + print ''; + print_liste_field_titre($langs->trans("ExpenseReport"), $_SERVER["PHP_SELF"], "er.ref", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("TypeFees"), $_SERVER["PHP_SELF"], "f.label", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "erd.comments", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "erd.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("VATRate"), $_SERVER["PHP_SELF"], "erd.tva_tx", "", $param, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Account"), $_SERVER["PHP_SELF"], "aa.account_number", "", $param, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("LineId"), $_SERVER["PHP_SELF"], "erd.rowid", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre(''); + print_liste_field_titre('', '', '', '', '', 'align="center"'); + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $expensereport_static = new ExpenseReport($db); + + $var = True; + while ( $i < min($num_lines, $limit) ) { + $objp = $db->fetch_object($result); + $var = ! $var; + $codeCompta = length_accountg($objp->account_number) . ' - ' . $objp->label; + + print ''; + + // Ref Invoice + $expensereport_static->ref = $objp->ref; + $expensereport_static->id = $objp->erid; + print ''; + + print ''; + + $trunclength = defined('ACCOUNTING_LENGTH_DESCRIPTION') ? ACCOUNTING_LENGTH_DESCRIPTION : 32; + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ""; + $i ++; + } +} else { + print $db->error(); +} + +print "
'; + $searchpicto=$form->showFilterAndCheckAddButtons(1); + print $searchpicto; + print '
' . $expensereport_static->getNomUrl(1) . '' . dol_trunc($objp->fees_label, 24) . '' . nl2br(dol_trunc($objp->comments, $trunclength)) . '' . price($objp->total_ht) . '' . price($objp->tva_tx) . '' . $codeCompta . '' . $objp->rowid . ''; + print img_edit(); + print '
"; + +if ($nbtotalofrecords > $limit) { + print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, '', 0, '', '', $limit, 1); +} + +print '
'; + + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/expensereport/list.php b/htdocs/accountancy/expensereport/list.php new file mode 100644 index 00000000000..943105a00fa --- /dev/null +++ b/htdocs/accountancy/expensereport/list.php @@ -0,0 +1,328 @@ + + * Copyright (C) 2013-2016 Alexandre Spangaro + * Copyright (C) 2014-2015 Ari Elbaz (elarifr) + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent s + * 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 . + */ + +/** + * \file htdocs/accountancy/expensereport/list.php + * \ingroup Advanced accountancy + * \brief Ventilation page from expense reports + */ +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/html.formventilation.class.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("trips"); +$langs->load("main"); +$langs->load("accountancy"); + +$action = GETPOST('action'); + +// Select Box +$mesCasesCochees = GETPOST('mesCasesCochees', 'array'); + +// Search Getpost +$search_expensereport = GETPOST('search_expensereport', 'alpha'); +$search_label = GETPOST('search_label', 'alpha'); +$search_desc = GETPOST('search_desc', 'alpha'); +$search_amount = GETPOST('search_amount', 'alpha'); +$search_account = GETPOST('search_account', 'alpha'); +$search_vat = GETPOST('search_vat', 'alpha'); +$btn_ventil = GETPOST('ventil', 'alpha'); + +// Load variable for pagination +$limit = GETPOST('limit') ? GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOST('page','int'); +if ($page < 0) { $page = 0; } +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) + $sortfield = "er.date_create, er.ref, erd.rowid"; +if (! $sortorder) { + if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO > 0) { + $sortorder = "DESC"; + } +} + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->bind->write) + accessforbidden(); + +$formventilation = new FormVentilation($db); + +// Defaut AccountingAccount RowId Product / Service +// at this time ACCOUNTING_SERVICE_SOLD_ACCOUNT & ACCOUNTING_PRODUCT_SOLD_ACCOUNT are account number not accountingacount rowid +// so we need to get those default value rowid first +$accounting = new AccountingAccount($db); + +/* + * Action + */ + +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +{ + $search_expensereport = ''; + $search_label = ''; + $search_desc = ''; + $search_amount = ''; + $search_account = ''; + $search_vat = ''; +} + +if ($action == 'ventil' && ! empty($btn_ventil)) { + $msg=''; + //print '
' . $langs->trans("Processing") . '...
'; + if (! empty($mesCasesCochees)) { + $msg = '
' . $langs->trans("SelectedLines") . ': '.count($_POST["mesCasesCochees"]).'
'; + $msg.='
'; + $mesCodesVentilChoisis = $codeventil; + $cpt = 0; + $ok=0; + $ko=0; + + foreach ( $mesCasesCochees as $maLigneCochee ) { + // print '
id selectionnee : '.$monChoix."
"; + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monCompte = GETPOST('codeventil'.$monId); + + if ($monCompte <= 0) + { + $msg.= '
' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NoAccountSelected") . '
'; + $ko++; + } + else + { + $sql = " UPDATE " . MAIN_DB_PREFIX . "expensereport_det"; + $sql .= " SET fk_code_ventilation = " . $monCompte; + $sql .= " WHERE rowid = " . $monId; + + $accountventilated = new AccountingAccount($db); + $accountventilated->fetch($monCompte, ''); + + dol_syslog('accountancy/expensereport/list.php:: sql=' . $sql, LOG_DEBUG); + if ($db->query($sql)) { + $ok++; + $msg.= '
' . $langs->trans("LineOfExpenseReport") . ' ' . $monId . ' - ' . $langs->trans("VentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
'; + } else { + $ko++; + $msg.= '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NotVentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
' . $sql . '
'; + } + } + + $cpt++; + } + $msg.='
'; + } else { + setEventMessages($langs->trans("NoRecordSelected"), null, 'warnings'); + } + $msg.= '
' . $langs->trans("EndProcessing") . '
'; +} + + + +/* + * View + */ +llxHeader('', $langs->trans("ExpenseReportsVentilation")); + +// Expense report lines +$sql = "SELECT er.ref, er.rowid as erid, er.date_debut, erd.rowid, erd.fk_c_type_fees, erd.comments, erd.total_ht as price, erd.fk_code_ventilation, erd.tva_tx as tva_tx_line, "; +$sql .= " f.id as fees_id, f.label as fees_label, f.accountancy_code as code_buy,"; +$sql .= " aa.rowid as aarowid"; +$sql .= " FROM " . MAIN_DB_PREFIX . "expensereport as er"; +$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "expensereport_det as erd ON er.rowid = erd.fk_expensereport"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_type_fees as f ON f.id = erd.fk_c_type_fees"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON f.accountancy_code = aa.account_number"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_system as accsys ON accsys.pcg_version = aa.fk_pcg_version"; +$sql .= " WHERE er.fk_statut > 4 AND erd.fk_code_ventilation <= 0"; +$sql .= " AND (accsys.rowid='" . $conf->global->CHARTOFACCOUNTS . "' OR f.accountancy_code IS NULL OR f.accountancy_code ='')"; +// Add search filter like +if (strlen(trim($search_expensereport))) { + $sql .= " AND (er.ref like '%" . $search_expensereport . "%')"; +} +if (strlen(trim($search_label))) { + $sql .= " AND (f.label like '%" . $search_label . "%')"; +} +if (strlen(trim($search_desc))) { + $sql .= " AND (erd.comments like '%" . $search_desc . "%')"; +} +if (strlen(trim($search_amount))) { + $sql .= " AND erd.total_ht like '" . $search_amount . "%'"; +} +if (strlen(trim($search_account))) { + $sql .= " AND aa.account_number like '%" . $search_account . "%'"; +} +if (strlen(trim($search_vat))) { + $sql .= " AND (erd.tva_tx like '" . $search_vat . "%')"; +} +$sql .= " AND er.entity IN (" . getEntity("expensereport", 0) . ")"; // We don't share object for accountancy + +$sql .= $db->order($sortfield, $sortorder); + +// Count total nb of records +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog('accountancy/expensereport/list.php'); +$result = $db->query($sql); +if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + $arrayofselected=is_array($toselect)?$toselect:array(); + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + + print '
' . "\n"; + print ''; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + + $center='
'; + + print_barre_liste($langs->trans("ExpenseReportLines"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num_lines, 0, 'title_accountancy', 0, '', '', $limit); + + if ($msg) print $msg.'
'; + + print $langs->trans("DescVentilTodoExpenseReport") . '

'; + + $moreforfilter = ''; + + print ''."\n"; + print ''; + print_liste_field_titre($langs->trans("ExpenseReport"), $_SERVER["PHP_SELF"], "er.ref", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("TypeFees"), $_SERVER["PHP_SELF"], "f.label", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "erd.comments", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "erd.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("VATRate"), $_SERVER["PHP_SELF"], "erd.tva_tx", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("AccountAccountingSuggest"), '', '', '', '', 'align="center"'); + print_liste_field_titre($langs->trans("IntoAccount"), '', '', '', '', 'align="center"'); + print_liste_field_titre($langs->trans("LineId"), $_SERVER["PHP_SELF"], "erd.rowid", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre('', '', '', '', '', 'align="center"'); + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $expensereport_static = new ExpenseReport($db); + $form = new Form($db); + + $var = True; + while ( $i < min($num_lines, $limit) ) { + $objp = $db->fetch_object($result); + $var = ! $var; + + $objp->aarowid_suggest = ''; + $objp->aarowid_suggest = $objp->aarowid; + + print ''; + + // Ref Expense report + $expensereport_static->ref = $objp->ref; + $expensereport_static->id = $objp->erid; + print ''; + + // Fees label + print ''; + + // Fees description -- Can be null + // TODO: we should set a user defined value to adjust user square / wide screen size + $trunclength = defined('ACCOUNTING_LENGTH_DESCRIPTION') ? ACCOUNTING_LENGTH_DESCRIPTION : 32; + print ''; + + print ''; + + // Vat rate + print ''; + + // Accounting account suggested + print ''; + + // Colonne choix du compte + print ''; + + // Line id + print ''; + + // Colonne choix ligne a ventiler + print ''; + + print ""; + $i ++; + } + + print '
'; + $searchpicto=$form->showFilterAndCheckAddButtons(1); + print $searchpicto; + print '
' . $expensereport_static->getNomUrl(1) . ''; + print dol_trunc($objp->fees_label, 24); + print '' . nl2br(dol_trunc($objp->comments, $trunclength)) . ''; + print price($objp->price); + print ''; + print price($objp->tva_tx_line); + print ''; + print length_accountg(html_entity_decode($objp->code_buy)); + print ''; + print $formventilation->select_account($objp->aarowid_suggest, 'codeventil'.$objp->rowid, 1); + print '' . $objp->rowid . ''; + print 'aarowid ? "checked" : "") . '/>'; + print '
'; + print '
'; +} else { + print $db->error(); +} + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/index.php b/htdocs/accountancy/index.php new file mode 100644 index 00000000000..26edab6f859 --- /dev/null +++ b/htdocs/accountancy/index.php @@ -0,0 +1,164 @@ + + * + * 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/accountancy/index.php + * \ingroup Advanced accountancy + * \brief Home accounting module + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +// Validate History +$action = GETPOST('action'); + +$langs->load("admin"); +$langs->load("dict"); +$langs->load("bills"); +$langs->load("accountancy"); +$langs->load("compta"); +$langs->load("banks"); +$langs->load("loans"); + +/* + * Actions + */ + + +/* + * View + */ + +llxHeader('', $langs->trans("AccountancyArea")); + +print load_fiche_titre($langs->trans("AccountancyArea"), '', 'title_accountancy'); + +$step = 0; + +print "
\n"; + +print $langs->trans("AccountancyAreaDescIntro")."
\n"; +print "
\n";print "
\n"; + +print_fiche_titre($langs->trans("AccountancyAreaDescActionOnce"), '', 'object_calendar')."
\n"; +print '
'; +print "
\n"; + +// STEPS +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescChartModel", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("Pcg_version").''); +print "
\n"; +print "
\n"; +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescChart", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("Chartofaccounts").''); +print "
\n"; +print "
\n"; + +print $langs->trans("AccountancyAreaDescActionOnceBis"); +print "
\n"; +print "
\n"; + +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescMisc", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'')."
\n"; +print "
\n"; +$step++; +$textlink = ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup").'-'.$langs->transnoentitiesnoconv("MenuVatAccounts").''; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescVat", $step, $textlink); +print "
\n"; +print "
\n"; +if (! empty($conf->tax->enabled)) +{ + $textlink = ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup").'-'.$langs->transnoentitiesnoconv("MenuTaxAccounts").''; + $step++; + print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescContrib", $step, $textlink); + print "
\n"; + print "
\n"; +} +/*if (! empty($conf->salaries->enabled)) +{ + $step++; + print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescSal", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").''); + // htdocs/admin/salaries.php + print "
\n"; + print "
\n"; +}*/ +if (! empty($conf->expensereport->enabled)) // TODO Move this in the default account page because this is only one accounting account per purpose, not several. +{ + $step++; + print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescExpenseReport", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuExpenseReportAccounts").''); + print "
\n"; + print "
\n"; +} +if (! empty($conf->loan->enabled)) // TODO Move this in the default account page because this is only one accounting account per purpose, not several. +{ + $step++; + print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescLoan", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuLoanAccounts").''); + print "
\n"; + print "
\n"; +} +/* +if (! empty($conf->don->enabled)) +{ + $step++; + print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescDonation", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDonationAccounts").''); + print "
\n"; + print "
\n"; +}*/ +$step++; +$textlink=''.$langs->transnoentitiesnoconv("Home").'-'.$langs->transnoentitiesnoconv("MenuBankCash").''; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBank", $step, $textlink); +print "
\n"; +print "
\n"; + +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescProd", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("ProductsBinding").'')."
\n"; +print "
\n"; + +print "
\n"; +print_fiche_titre($langs->trans("AccountancyAreaDescActionFreq"), '', 'object_calendarweek'); +print '
'; +print "
\n"; +$step = 0; + +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescCustomer", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy")."-".$langs->transnoentitiesnoconv("CustomersVentilation").'')."
\n"; +print "
\n"; +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescSupplier", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy")."-".$langs->transnoentitiesnoconv("SuppliersVentilation").'')."
\n"; +print "
\n"; +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescWriteRecords", $step, ''.$langs->transnoentitiesnoconv("Financial").'-'.$langs->transnoentitiesnoconv("Accountancy")."-".$langs->transnoentitiesnoconv("SuppliersVentilation").'')."
\n"; +print "
\n"; +$step++; +print img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescAnalyze", $step)."
\n"; +print "
\n"; + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index c990465bacf..bd18388aacb 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -4,9 +4,9 @@ * Copyright (C) 2011 Juanjo Menent * Copyright (C) 2012 Regis Houssin * Copyright (C) 2013 Christophe Battarel - * Copyright (C) 2013-2016 Alexandre Spangaro - * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2016 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Olivier Geffroy * * 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 @@ -42,6 +42,7 @@ require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT . '/don/class/paymentdonation.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/fourn/class/paiementfourn.class.php'; require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.class.php'; @@ -73,9 +74,13 @@ $now = dol_now(); if ($user->societe_id > 0 && empty($id_bank_account)) accessforbidden(); + /* - * View + * Actions */ + +$error = 0; + $year_current = strftime("%Y", dol_now()); $pastmonth = strftime("%m", dol_now()) - 1; $pastmonthyear = $year_current; @@ -96,16 +101,15 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end $p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); $idpays = $p[0]; -$sql = "SELECT b.rowid , b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, soc.code_compta, ba.courant,"; -$sql .= " soc.code_compta_fournisseur, soc.rowid as socid, soc.nom as name, ba.account_number, bu1.type as typeop"; +$sql = "SELECT b.rowid , b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,"; +$sql .= " ba.courant, ba.ref as baref, ba.account_number,"; +$sql .= " soc.code_compta, soc.code_compta_fournisseur, soc.rowid as socid, soc.nom as name, bu1.type as typeop"; $sql .= " FROM " . MAIN_DB_PREFIX . "bank as b"; $sql .= " JOIN " . MAIN_DB_PREFIX . "bank_account as ba on b.fk_account=ba.rowid"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url as bu1 ON bu1.fk_bank = b.rowid AND bu1.type='company'"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as soc on bu1.url_id=soc.rowid"; $sql .= " WHERE ba.rowid=" . $id_bank_account; -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND ba.entity = " . $conf->entity; -} +$sql .= ' AND ba.entity IN ('.getEntity('banque', 0).')'; // We don't share object for accountancy if ($date_start && $date_end) $sql .= " AND b.dateo >= '" . $db->idate($date_start) . "' AND b.dateo <= '" . $db->idate($date_end) . "'"; $sql .= " ORDER BY b.datev"; @@ -138,28 +142,33 @@ if ($result) { $account_pay_donation = (! empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : $langs->trans("CodeNotDef")); $account_transfer = (! empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : $langs->trans("CodeNotDef")); + $tabcompany = array(); $tabpay = array (); $tabbq = array (); $tabtp = array (); $tabtype = array (); + // Loop on each line into bank account. For each line, we should get: + // on line tabpay = line into bank + // one line for bank jounral = tabbq + // one line for thirdparty journal = tabtp $i = 0; while ( $i < $num ) { $obj = $db->fetch_object($result); - $tabcompany[$obj->rowid] = array ( - 'id' => $obj->socid, - 'name' => $obj->name, - 'code_client' => $obj->code_compta - ); - - // Controls + // Set accountancy code (for bank and thirdparty) $compta_bank = $obj->account_number; if ($obj->label == '(SupplierInvoicePayment)') $compta_soc = (! empty($obj->code_compta_fournisseur) ? $obj->code_compta_fournisseur : $account_supplier); if ($obj->label == '(CustomerInvoicePayment)') $compta_soc = (! empty($obj->code_compta) ? $obj->code_compta : $account_customer); + $tabcompany[$obj->rowid] = array ( + 'id' => $obj->socid, + 'name' => $obj->name, + 'code_compta' => $compta_soc, + ); + // Variable bookkeeping $tabpay[$obj->rowid]["date"] = $obj->do; $tabpay[$obj->rowid]["type_payment"] = $obj->fk_type; @@ -174,16 +183,24 @@ if ($result) { // get_url may return -1 which is not traversable if (is_array($links)) { + // Now loop on each link of record in bank. foreach ( $links as $key => $val ) { - $tabtype[$obj->rowid] = $links[$key]['type']; + + if (in_array($links[$key]['type'], array('sc', 'payment_sc', 'payment', 'payment_supplier', 'payment_vat'))) // So we excluded 'company' here + { + // We save tabtype for a future use, to remember what kind of payment it is + $tabtype[$obj->rowid] = $links[$key]['type']; + } if ($links[$key]['type'] == 'payment') { $paymentstatic->id = $links[$key]['url_id']; $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentstatic->getNomUrl(2); + $tabpay[$obj->rowid]["paymentid"] = $paymentstatic->id; } else if ($links[$key]['type'] == 'payment_supplier') { $paymentsupplierstatic->id = $links[$key]['url_id']; $paymentsupplierstatic->ref = $links[$key]['url_id']; $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentsupplierstatic->getNomUrl(2); + $tabpay[$obj->rowid]["paymentsupplierid"] = $paymentsupplierstatic->id; } else if ($links[$key]['type'] == 'company') { $societestatic->id = $links[$key]['url_id']; $societestatic->name = $links[$key]['label']; @@ -248,6 +265,26 @@ if ($result) { $tabbq[$obj->rowid][$compta_bank] += $obj->amount; + + // Check account number is ok + /*if ($action == 'writebookkeeping') // Make test now in such a case + { + reset($tabbq[$obj->rowid]); + $first_key_tabbq = key($tabbq[$obj->rowid]); + if (empty($first_key_tabbq)) + { + $error++; + setEventMessages($langs->trans('ErrorAccountancyCodeOnBankAccountNotDefined', $obj->baref), null, 'errors'); + } + reset($tabtp[$obj->rowid]); + $first_key_tabtp = key($tabtp[$obj->rowid]); + if (empty($first_key_tabtp)) + { + $error++; + setEventMessages($langs->trans('ErrorAccountancyCodeOnThirdPartyNotDefined'), null, 'errors'); + } + }*/ + // if($obj->socid)$tabtp[$obj->rowid][$compta_soc] += $obj->amount; $i ++; @@ -257,151 +294,185 @@ if ($result) { } /* - * Actions - */ +var_dump($tabpay); +var_dump($tabbq); +var_dump($tabtp); +*/ // Write bookkeeping -if ($action == 'writebookkeeping') { +if (! $error && $action == 'writebookkeeping') { $now = dol_now(); $error = 0; - foreach ( $tabpay as $key => $val ) { + foreach ( $tabpay as $key => $val ) { // $key is rowid into llx_bank + + $errorforline = 0; + + $db->begin(); + // Bank - foreach ( $tabbq[$key] as $k => $mt ) { - $bookkeeping = new BookKeeping($db); - $bookkeeping->doc_date = $val["date"]; - $bookkeeping->doc_ref = $val["ref"]; - $bookkeeping->doc_type = 'bank'; - $bookkeeping->fk_doc = $key; - $bookkeeping->fk_docdet = $val["fk_bank"]; - $bookkeeping->code_tiers = $tabcompany[$key]['code_client']; - $bookkeeping->numero_compte = $k; - $bookkeeping->label_compte = $compte->label; - $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); - $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; - $bookkeeping->debit = ($mt >= 0 ? $mt : 0); - $bookkeeping->credit = ($mt < 0 ? - $mt : 0); - $bookkeeping->code_journal = $journal; - $bookkeeping->fk_user_author = $user->id; - $bookkeeping->date_create = $now; - - if ($tabtype[$key] == 'payment') { - - $sqlmid = 'SELECT fac.facnumber'; - $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; - $sqlmid .= " WHERE pay.fk_bank=" . $key; - dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); - $resultmid = $db->query($sqlmid); - if ($resultmid) { - $objmid = $db->fetch_object($resultmid); - $bookkeeping->doc_ref = $objmid->facnumber; - } - } else if ($tabtype[$key] == 'payment_supplier') { - - $sqlmid = 'SELECT facf.ref_supplier,facf.ref'; - $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; - $sqlmid .= " WHERE payf.fk_bank=" . $key; - dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); - $resultmid = $db->query($sqlmid); - if ($resultmid) { - $objmid = $db->fetch_object($resultmid); - $bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')'; - } - } - - $result = $bookkeeping->create($user); - if ($result < 0) { - $error ++; - setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); - } + if (! $errorforline) + { + // Line into bank account + foreach ( $tabbq[$key] as $k => $mt ) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_type = 'bank'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_bank"]; + $bookkeeping->numero_compte = $k; + $bookkeeping->label_compte = $compte->label; + $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); + $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt >= 0 ? $mt : 0); + $bookkeeping->credit = ($mt < 0 ? - $mt : 0); + $bookkeeping->code_journal = $journal; + $bookkeeping->fk_user_author = $user->id; + $bookkeeping->date_create = $now; + + if ($tabtype[$key] == 'payment') { + $bookkeeping->code_tiers = $tabcompany[$key]['code_compta']; + + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; // Ref of invoice + } + } else if ($tabtype[$key] == 'payment_supplier') { + $bookkeeping->code_tiers = $tabcompany[$key]['code_compta']; + + $sqlmid = 'SELECT facf.ref_supplier, facf.ref'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sqlmid .= " WHERE payf.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')'; // Ref on invoice + } + } + + $result = $bookkeeping->create($user); + if ($result < 0) { + $error++; + $errorforline++; + setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); + } + } } + // Third party - foreach ( $tabtp[$key] as $k => $mt ) { - $bookkeeping = new BookKeeping($db); - $bookkeeping->doc_date = $val["date"]; - $bookkeeping->doc_ref = $val["ref"]; - $bookkeeping->doc_type = 'bank'; - $bookkeeping->fk_doc = $key; - $bookkeeping->fk_docdet = $val["fk_bank"]; - $bookkeeping->label_compte = $tabcompany[$key]['name']; - $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); - $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; - $bookkeeping->debit = ($mt < 0 ? - $mt : 0); - $bookkeeping->credit = ($mt >= 0) ? $mt : 0; - $bookkeeping->code_journal = $journal; - $bookkeeping->fk_user_author = $user->id; - $bookkeeping->date_create = $now; - - if ($tabtype[$key] == 'sc') { - $bookkeeping->code_tiers = ''; - $bookkeeping->numero_compte = $k; - } else if ($tabtype[$key] == 'payment') { - - $sqlmid = 'SELECT fac.facnumber'; - $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; - $sqlmid .= " WHERE pay.fk_bank=" . $key; - dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); - $resultmid = $db->query($sqlmid); - if ($resultmid) { - $objmid = $db->fetch_object($resultmid); - $bookkeeping->doc_ref = $objmid->facnumber; - } - $bookkeeping->code_tiers = $k; - $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; - } else if ($tabtype[$key] == 'payment_supplier') { - - $sqlmid = 'SELECT facf.ref_supplier,facf.ref'; - $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; - $sqlmid .= " WHERE payf.fk_bank=" . $key; - dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); - $resultmid = $db->query($sqlmid); - if ($resultmid) { - $objmid = $db->fetch_object($resultmid); - $bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')'; - } - $bookkeeping->code_tiers = $k; - $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER; - } else if ($tabtype[$key] == 'company') { - - $sqlmid = 'SELECT fac.facnumber'; - $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; - $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; - $sqlmid .= " WHERE pay.fk_bank=" . $key; - dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); - $resultmid = $db->query($sqlmid); - if ($resultmid) { - $objmid = $db->fetch_object($resultmid); - $bookkeeping->doc_ref = $objmid->facnumber; - } - $bookkeeping->code_tiers = $k; - $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; - } else { - - $bookkeeping->doc_ref = $k; - $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; - } - - $result = $bookkeeping->create($user); - if ($result < 0) { - $error ++; - setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); - } + if (! $errorforline) + { + // Line into thirdparty account + foreach ( $tabtp[$key] as $k => $mt ) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_type = 'bank'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_bank"]; + $bookkeeping->label_compte = $tabcompany[$key]['name']; + $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); + $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt < 0 ? - $mt : 0); + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $journal; + $bookkeeping->fk_user_author = $user->id; + $bookkeeping->date_create = $now; + + if (in_array($tabtype[$key], array('sc', 'payment_sc'))) { // If payment is payment of social contribution + $bookkeeping->code_tiers = ''; + $bookkeeping->numero_compte = $k; + } else if ($tabtype[$key] == 'payment') { // If payment is payment of customer invoice, we get ref of invoice + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + $bookkeeping->code_tiers = $tabcompany[$key]['code_compta']; + $bookkeeping->numero_compte = $k; + } else if ($tabtype[$key] == 'payment_supplier') { // If payment is payment of supplier invoice, we get ref of invoice + + $sqlmid = 'SELECT facf.ref_supplier,facf.ref'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sqlmid .= " WHERE payf.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->ref_supplier . ' (' . $objmid->ref . ')'; + } + $bookkeeping->code_tiers = $tabcompany[$key]['code_compta']; + $bookkeeping->numero_compte = $k; + } else { + // FIXME Should be a temporary account ??? + $bookkeeping->doc_ref = $k; + //$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + $bookkeeping->numero_compte = 'CodeNotDef'; + } + + $result = $bookkeeping->create($user); + if ($result < 0) { + $error++; + $errorforline++; + setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); + } + } + } + + if (! $errorforline) + { + $db->commit(); + } + else + { + $db->rollback(); } } if (empty($error)) { - setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs'); + setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs'); } + elseif (count($tabpay) == $error) + { + setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings'); + } + else + { + setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings'); + } + + $action = ''; } + + + + +/* + * View + */ + +$form = new Form($db); + + // Export if ($action == 'export_csv') { $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; @@ -424,7 +495,7 @@ if ($action == 'export_csv') { } if ($reflabel == '(CustomerInvoicePayment)') { $reflabel = $langs->trans('Customer'); - } + } if ($reflabel == '(SocialContributionPayment)') { $reflabel = $langs->trans('SocialContribution'); } @@ -437,7 +508,6 @@ if ($action == 'export_csv') { $companystatic->id = $tabcompany[$key]['id']; $companystatic->name = $tabcompany[$key]['name']; - $companystatic->client = $tabcompany[$key]['code_client']; // Bank foreach ( $tabbq[$key] as $k => $mt ) { @@ -562,14 +632,17 @@ if ($action == 'export_csv') { } } } -else { - $form = new Form($db); +if (empty($action) || $action == 'view') { + $invoicestatic = new Facture($db); + $invoicesupplierstatic = new FactureFournisseur($db); + llxHeader('', $langs->trans("FinanceJournal")); $nom = $langs->trans("FinanceJournal") . ' - ' . $bank_code_journal->getNomUrl(1); $builddate = time(); - $description = $langs->trans("DescFinanceJournal") . '
'; + //$description = $langs->trans("DescFinanceJournal") . '
'; + $description.= $langs->trans("DescJournalOnlyBindedVisible").'
'; $period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1); $varlink = 'id_account=' . $id_bank_account; @@ -577,18 +650,25 @@ else { 'action' => '' ), '', $varlink); - print ''; + if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) { + print ''; + } else { + print ''; + } - print ''; + print ''; + // TODO Avoid using js. We can use a direct link with $param print ' '; + + /* + * Show result array + */ + print '

'; + + $i = 0; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print "\n"; + + $var = true; + $r = ''; + + $expensereportstatic = new ExpenseReport($db); + $expensereportlinestatic = new ExpenseReportLine($db); + + foreach ( $taber as $key => $val ) { + $expensereportstatic->id = $key; + $expensereportstatic->ref = $val["ref"]; + $expensereportlinestatic->comments = html_entity_decode(dol_trunc($val["comments"], 32)); + + $date = dol_print_date($val["date"], 'day'); + + // Fees + foreach ( $tabht[$key] as $k => $mt ) { + $accountingaccount = new AccountingAccount($db); + $accountingaccount->fetch(null, $k); + + if ($mt) { + print ""; + print ""; + print ""; + print ""; + $userstatic->id = $tabuser[$key]['id']; + $userstatic->name = $tabuser[$key]['name']; + print ""; + $userstatic->id = $tabuser[$key]['id']; + $userstatic->name = $tabuser[$key]['name']; + print ""; + print '"; + print '"; + print ""; + } + } + + // VAT + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print '"; + print '"; + print ""; + } + } + print ""; + + // Third party + foreach ( $tabttc[$key] as $k => $mt ) { + print ""; + print ""; + print ""; + $userstatic->id = $tabuser[$key]['id']; + $userstatic->name = $tabuser[$key]['name']; + print ""; + print ""; + print '"; + print '"; + } + print ""; + + $var = ! $var; + } + + print "
" . $langs->trans("Date") . "" . $langs->trans("Piece") . ' (' . $langs->trans("ExpenseReportRef") . ")" . $langs->trans("Account") . "" . $langs->trans("Label") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $date . "" . $expensereportstatic->getNomUrl(1) . ""; + $accountoshow = length_accountg($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("FeeAccountNotDefined").''; + } + else print $accountoshow; + print "" . $userstatic->getNomUrl(0, 'user', 16) . ' - ' . $accountingaccount->label . "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $expensereportstatic->getNomUrl(1) . ""; + $accountoshow = length_accountg($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("VatAccountNotDefined").''; + } + else print $accountoshow; + print "" . $userstatic->getNomUrl(0, 'user', 16) . ' - ' . $langs->trans("VAT"). ' '.$def_tva[$key]. "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $expensereportstatic->getNomUrl(1) . ""; + $accountoshow = length_accounta($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("ThirdpartyAccountNotDefined").''; + } + else print $accountoshow; + print "" . $userstatic->getNomUrl(0, 'user', 16) . ' - ' . $langs->trans("Code_tiers") . "' . ($mt < 0 ? - price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
"; + + // End of page + llxFooter(); +} +$db->close(); diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php index 937b6a8fa36..91436669ba8 100644 --- a/htdocs/accountancy/journal/purchasesjournal.php +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -59,6 +59,7 @@ if ($user->societe_id > 0) $action = GETPOST('action'); + /* * Actions */ @@ -85,8 +86,8 @@ $idpays = $p[0]; $sql = "SELECT f.rowid, f.ref, f.type, f.datef as df, f.libelle,f.ref_supplier,"; $sql .= " fd.rowid as fdid, fd.description, fd.total_ttc, fd.tva_tx, fd.total_ht, fd.tva as total_tva, fd.product_type,"; -$sql .= " s.rowid as socid, s.nom as name, s.code_compta_fournisseur, s.fournisseur,"; -$sql .= " s.code_compta_fournisseur, p.accountancy_code_buy , ct.accountancy_code_buy as account_tva, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte"; +$sql .= " s.rowid as socid, s.nom as name, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,"; +$sql .= " p.accountancy_code_buy , ct.accountancy_code_buy as account_tva, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte"; $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as fd"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_tva as ct ON fd.tva_tx = ct.taux AND ct.fk_pays = '" . $idpays . "'"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = fd.fk_product"; @@ -95,9 +96,7 @@ $sql .= " JOIN " . MAIN_DB_PREFIX . "facture_fourn as f ON f.rowid = fd.fk_factu $sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc"; $sql .= " WHERE f.fk_statut > 0 "; $sql .= " AND fd.fk_code_ventilation > 0 "; -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture_fourn", 1) . ")"; -} +$sql .= " AND f.entity IN (" . getEntity("facture_fourn", 0) . ")"; // We don't share object for accountancy if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2)"; else @@ -168,6 +167,10 @@ if ($action == 'writebookkeeping') { foreach ($tabfac as $key => $val) { + $errorforline = 0; + + $db->begin(); + $companystatic = new Societe($db); $invoicestatic = new FactureFournisseur($db); @@ -179,6 +182,10 @@ if ($action == 'writebookkeeping') { $companystatic->id = $tabcompany[$key]['id']; $companystatic->name = $tabcompany[$key]['name']; + $companystatic->code_compta = $tabcompany[$key]['code_compta']; + $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur']; + $companystatic->code_client = $tabcompany[$key]['code_client']; + $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur']; $companystatic->client = $tabcompany[$key]['code_client']; foreach ( $tabttc[$key] as $k => $mt ) { @@ -203,8 +210,9 @@ if ($action == 'writebookkeeping') { $result = $bookkeeping->create($user); if ($result < 0) { - $error ++; - setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); + $error++; + $errorforline++; + setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); } } @@ -235,7 +243,8 @@ if ($action == 'writebookkeeping') { $result = $bookkeeping->create($user); if ($result < 0) { - $error ++; + $error++; + $errorforline++; setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); } } @@ -266,154 +275,180 @@ if ($action == 'writebookkeeping') { $result = $bookkeeping->create($user); if ($result < 0) { - $error ++; + $error++; + $errorforline++; setEventMessages($object->error, $object->errors, 'errors'); } } } + + + + if (! $errorforline) + { + $db->commit(); + } + else + { + $db->rollback(); + } + } - if (empty($error)) { - setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs'); + if (empty($error) && count($tabpay)) { + setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs'); } + elseif (count($tabpay) == $error) + { + setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings'); + } + else + { + setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings'); + } + + $action=''; } /* * View */ +$form = new Form($db); + $companystatic = new Fournisseur($db); // Export if ($action == 'export_csv') { - $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - $journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL; + $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; + $journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL; - include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; + include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; - // Model Cegid Expert Export - if ($conf->global->ACCOUNTING_EXPORT_MODELCSV == 2) { - $sep = ";"; + // Model Cegid Expert Export + if ($conf->global->ACCOUNTING_EXPORT_MODELCSV == 2) { + $sep = ";"; - foreach ( $tabfac as $key => $val ) { - $date = dol_print_date($val["date"], '%d%m%Y'); - - // Product / Service - foreach ( $tabht[$key] as $k => $mt ) { - $companystatic->id = $tabcompany[$key]['id']; - $companystatic->name = $tabcompany[$key]['name']; - $companystatic->client = $tabcompany[$key]['code_client']; - - if ($mt) { - print $date . $sep; - print $purchase_journal . $sep; - print length_accountg(html_entity_decode($k)) . $sep; - print $sep; - print ($mt < 0 ? 'C' : 'D') . $sep; - print ($mt <= 0 ? price(- $mt) : $mt) . $sep; - print dol_trunc($val["description"], 32) . $sep; - print $val["ref"]; - print "\n"; - } - } - - // VAT - foreach ( $tabtva[$key] as $k => $mt ) { - if ($mt) { - print $date . $sep; - print $purchase_journal . $sep; - print length_accountg(html_entity_decode($k)) . $sep; - print $sep; - print ($mt < 0 ? 'C' : 'D') . $sep; - print ($mt <= 0 ? price(- $mt) : $mt) . $sep; - print $langs->trans("VAT") . $sep; - print $val["ref"]; - print "\n"; - } - } - - foreach ( $tabttc[$key] as $k => $mt ) { - print $date . $sep; - print $purchase_journal . $sep; - print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) . $sep; - print length_accounta(html_entity_decode($k)) . $sep; - print ($mt < 0 ? 'D' : 'C') . $sep; - print ($mt <= 0 ? price(- $mt) : $mt) . $sep; - print $companystatic->name . $sep; - print $val["ref"]; - print "\n"; - } - } - } elseif ($conf->global->ACCOUNTING_EXPORT_MODELCSV == 1) { - // Model Classic Export - foreach ( $tabfac as $key => $val ) { - - $invoicestatic->id = $key; - $invoicestatic->ref = $val["ref"]; - $invoicestatic->ref = $val["refsologest"]; - $invoicestatic->refsupplier = $val["refsuppliersologest"]; - $invoicestatic->type = $val["type"]; - $invoicestatic->description = html_entity_decode(dol_trunc($val["description"], 32)); - - $date = dol_print_date($val["date"], 'day'); + foreach ( $tabfac as $key => $val ) { + $date = dol_print_date($val["date"], '%d%m%Y'); + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { $companystatic->id = $tabcompany[$key]['id']; $companystatic->name = $tabcompany[$key]['name']; $companystatic->client = $tabcompany[$key]['code_client']; - // Product / Service - foreach ( $tabht[$key] as $k => $mt ) { - $accountingaccount = new AccountingAccount($db); - $accountingaccount->fetch(null, $k); - if ($mt) { - print '"' . $date . '"' . $sep; - print '"' . $val["ref"] . '"' . $sep; - print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - print '"' . dol_trunc($companystatic->name, 16) . ' - ' . $val["refsuppliersologest"] . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; - // print '"' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; - print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; - print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; - print "\n"; - } - } - // VAT - foreach ( $tabtva[$key] as $k => $mt ) { - if ($mt) { - print '"' . $date . '"' . $sep; - print '"' . $val["ref"] . '"' . $sep; - print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; - // print '"' . $langs->trans("VAT") . '"' . $sep; - print '"' . dol_trunc($companystatic->name, 16) . ' - ' . $val["refsuppliersologest"] . ' - ' . $langs->trans("VAT") . '"' . $sep; - print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; - print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; - print "\n"; - } + if ($mt) { + print $date . $sep; + print $purchase_journal . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print dol_trunc($val["description"], 32) . $sep; + print $val["ref"]; + print "\n"; } + } - // Third party - foreach ( $tabttc[$key] as $k => $mt ) { - print '"' . $date . '"' . $sep; - print '"' . $val["ref"] . '"' . $sep; - print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep; - print '"' . dol_trunc($companystatic->name, 16) . ' - ' . $val["refsuppliersologest"] . ' - ' . $langs->trans("Code_tiers") . '"' . $sep; - print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; - print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + // VAT + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print $date . $sep; + print $purchase_journal . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print $langs->trans("VAT") . $sep; + print $val["ref"]; + print "\n"; } + } + + foreach ( $tabttc[$key] as $k => $mt ) { + print $date . $sep; + print $purchase_journal . $sep; + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) . $sep; + print length_accounta(html_entity_decode($k)) . $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print $companystatic->name . $sep; + print $val["ref"]; print "\n"; } } -} else { + } elseif ($conf->global->ACCOUNTING_EXPORT_MODELCSV == 1) { + // Model Classic Export + foreach ( $tabfac as $key => $val ) { + + $invoicestatic->id = $key; + $invoicestatic->ref = $val["ref"]; + $invoicestatic->ref = $val["refsologest"]; + $invoicestatic->refsupplier = $val["refsuppliersologest"]; + $invoicestatic->type = $val["type"]; + $invoicestatic->description = html_entity_decode(dol_trunc($val["description"], 32)); + + $date = dol_print_date($val["date"], 'day'); + + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + $accountingaccount = new AccountingAccount($db); + $accountingaccount->fetch(null, $k); + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . dol_trunc($companystatic->name, 16) . ' - ' . $val["refsuppliersologest"] . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; + // print '"' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + print "\n"; + } + } + // VAT + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + // print '"' . $langs->trans("VAT") . '"' . $sep; + print '"' . dol_trunc($companystatic->name, 16) . ' - ' . $val["refsuppliersologest"] . ' - ' . $langs->trans("VAT") . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + print "\n"; + } + } + + // Third party + foreach ( $tabttc[$key] as $k => $mt ) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep; + print '"' . dol_trunc($companystatic->name, 16) . ' - ' . $val["refsuppliersologest"] . ' - ' . $langs->trans("Code_tiers") . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + } + print "\n"; + } + } +} + +if (empty($action) || $action == 'view') { llxHeader('', $langs->trans("PurchasesJournal")); - $form = new Form($db); - $nom = $langs->trans("PurchasesJournal"); $nomlink = ''; $periodlink = ''; $exportlink = ''; $builddate = time(); - $description = $langs->trans("DescPurchasesJournal") . '
'; + //$description = $langs->trans("DescPurchasesJournal") . '
'; + $description.= $langs->trans("DescJournalOnlyBindedVisible").'
'; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description .= $langs->trans("DepositsAreNotIncluded"); } else { @@ -426,12 +461,12 @@ if ($action == 'export_csv') { )); if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) { - print ''; + print ''; } else { - print ''; + print ''; } - print ''; + print ''; print ' '; - -/* - * Action - */ -if ($action == 'ventil' && ! empty($btn_ventil)) { - print '
' . $langs->trans("Processing") . '...
'; - if ($_POST['codeventil'] && $_POST["mesCasesCochees"]) { - print '
' . count($_POST["mesCasesCochees"]) . ' ' . $langs->trans("SelectedLines") . '
'; - $mesCodesVentilChoisis = $codeventil; - $cpt = 0; - - foreach ( $mesCasesCochees as $maLigneCochee ) { - // print '
id selectionnee : '.$monChoix."
"; - $maLigneCourante = explode("_", $maLigneCochee); - $monId = $maLigneCourante[0]; - $monNumLigne = $maLigneCourante[1]; - $monCompte = $mesCodesVentilChoisis[$monNumLigne]; - - $sql = " UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det"; - $sql .= " SET fk_code_ventilation = " . $monCompte; - $sql .= " WHERE rowid = " . $monId; - - $accountventilated = new AccountingAccount($db); - $accountventilated->fetch($monCompte, ''); - - dol_syslog('accountancy/supplier/list.php:: sql=' . $sql, LOG_DEBUG); - if ($db->query($sql)) { - print '
' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("VentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
'; - } else { - print '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NotVentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '
' . $sql . '
'; - } - - $cpt ++; - } - } else { - print '
' . $langs->trans("AnyLineVentilate") . '
'; - } - print '
' . $langs->trans("EndProcessing") . '
'; -} - -/* - * Supplier Invoice Lines - */ -if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { - $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; -} else if ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} else { - $limit = GETPOST('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; -} - -$offset = $limit * $page; - +// Supplier Invoice Lines $sql = "SELECT f.ref, f.rowid as facid, f.ref_supplier, f.datef, l.fk_product, l.description, l.total_ht as price, l.rowid, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, "; $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_buy as code_buy, p.tva_tx as tva_tx_prod"; $sql .= " , aa.rowid as aarowid"; @@ -191,9 +172,9 @@ $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture_fourn_det as l ON f.rowid = l $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON p.accountancy_code_buy = aa.account_number"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_system as accsys ON accsys.pcg_version = aa.fk_pcg_version"; -$sql .= " WHERE f.fk_statut > 0 AND fk_code_ventilation <= 0"; +$sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; $sql .= " AND product_type <= 2"; -$sql .= " AND (accsys.rowid='" . $conf->global->CHARTOFACCOUNTS . "' OR p.accountancy_code_sell IS NULL OR p.accountancy_code_buy ='')"; +$sql .= " AND (accsys.rowid='" . $conf->global->CHARTOFACCOUNTS . "' OR p.accountancy_code_buy IS NULL OR p.accountancy_code_buy ='')"; // Add search filter like if (strlen(trim($search_invoice))) { $sql .= " AND (f.ref like '%" . $search_invoice . "%')"; @@ -216,55 +197,77 @@ if (strlen(trim($search_account))) { if (strlen(trim($search_vat))) { $sql .= " AND (l.tva_tx like '" . $search_vat . "%')"; } -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture_fourn", 1) . ")"; -} +$sql .= " AND f.entity IN (" . getEntity("facture_fourn", 0) . ")"; // We don't share object for accountancy $sql .= $db->order($sortfield, $sortorder); +// Count total nb of records +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + $sql .= $db->plimit($limit + 1, $offset); -dol_syslog('accountancy/supplier/list.php:: $sql=' . $sql); +dol_syslog('accountancy/supplier/list.php'); $result = $db->query($sql); if ($result) { $num_lines = $db->num_rows($result); $i = 0; - // TODO : print_barre_liste always use $conf->liste_limit and do not care about custom limit in list... - print_barre_liste($langs->trans("InvoiceLines"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); - - print '
' . $langs->trans("DescVentilTodoCustomer") . '
'; - + $arrayofselected=is_array($toselect)?$toselect:array(); + + $param=''; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + print '
' . "\n"; print ''; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + + $center='
'; + + print_barre_liste($langs->trans("InvoiceLines"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num_lines, 0, 'title_accountancy', 0, '', '', $limit); - print ''; + if ($msg) print $msg.'
'; + + print $langs->trans("DescVentilTodoCustomer") . '

'; + + $moreforfilter = ''; + + print '
'."\n"; print ''; print_liste_field_titre($langs->trans("Invoice"), $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Ref"), $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Label"), $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder); print_liste_field_titre($langs->trans("Description"), $_SERVER["PHP_SELF"], "l.description", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "l.total_ht", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("VATRate"), $_SERVER["PHP_SELF"], "l.tva_tx", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre($langs->trans("AccountAccounting"), '', '', '', '', 'align="center"'); + print_liste_field_titre($langs->trans("Amount"), $_SERVER["PHP_SELF"], "l.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("VATRate"), $_SERVER["PHP_SELF"], "l.tva_tx", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("AccountAccountingSuggest"), '', '', '', '', 'align="center"'); print_liste_field_titre($langs->trans("IntoAccount"), '', '', '', '', 'align="center"'); - print_liste_field_titre(''); - print_liste_field_titre($langs->trans("Ventilate") . '
/', '', '', '', '', 'align="center"'); + print_liste_field_titre($langs->trans("LineId"), $_SERVER["PHP_SELF"], "l.rowid", "", $param, 'align="right"', $sortfield, $sortorder); + print_liste_field_titre('', '', '', '', '', 'align="center"'); print "\n"; print ''; print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; @@ -314,7 +317,7 @@ if ($result) { if ($objp->code_buy_l != $objp->code_buy_p) $code_buy_p_l_differ = 'color:red'; - print ''; + print ''; // Ref Invoice $facturefourn_static->ref = $objp->ref; @@ -342,29 +345,36 @@ if ($result) { print price($objp->price); print ''; + // Vat rate if ($objp->vat_tx_l != $objp->vat_tx_p) $code_vat_differ = 'font-weight:bold; text-decoration:blink; color:red'; - print ''; + // Accounting account suggested print ''; // Colonne choix du compte print ''; + + // Line id print ''; + // Colonne choix ligne a ventiler - print ''; print ""; @@ -372,7 +382,6 @@ if ($result) { } print '
%%  '; - print ''; - print ' '; - print ''; + print ''; + $searchpitco=$form->showFilterAndCheckAddButtons(1); + print $searchpitco; print '
'; + print ''; print price($objp->tva_tx_line); print ''; - // if not same kind of product_type stored in product & facturedt we display both account and let user choose - if ($objp->code_buy_l == $objp->code_buy_p) { - print $objp->code_buy_l; + if ($objp->code_buy_l == $objp->code_buy_p) { // Test if there is a difference between code by default and code on product + if ($objp->code_buy_l > 0) print $objp->code_buy_l; + else print $langs->trans("Unknown"); } else { - print 'lines=' . $objp->code_buy_l . '
product=' . $objp->code_buy_p; + print $langs->trans("Default") . ' = ' . ($objp->code_buy_l > 0 ? $objp->code_buy_l : $langs->trans("Unknown")); + print '
'; + print $langs->trans("Product") . ' = ' . ($objp->code_buy_p > 0 ? $objp->code_buy_p : $langs->trans("Unknown")); } print '
'; - print $formventilation->select_account($objp->aarowid_suggest, 'codeventil[]', 1); + print $formventilation->select_account($objp->aarowid_suggest, 'codeventil'.$objp->rowid, 1); print '' . $objp->rowid . ''; - print 'aarowid ? "checked" : "") . '/>'; + print ''; + print 'aarowid ? "checked" : "") . '/>'; print '
'; - print '
'; print '
'; } else { print $db->error(); diff --git a/htdocs/adherents/admin/index.html b/htdocs/adherents/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/adherents/agenda.php b/htdocs/adherents/agenda.php index 057d7ada946..1aa1dc6bee7 100644 --- a/htdocs/adherents/agenda.php +++ b/htdocs/adherents/agenda.php @@ -120,6 +120,13 @@ if ($object->id > 0) print ''; + + print '
'; + + $object->info($id); + print dol_print_object_info($object, 1); + + print '
'; dol_fiche_end(); diff --git a/htdocs/adherents/canvas/default/index.html b/htdocs/adherents/canvas/default/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index ba1a06c9f17..ddbc7123d70 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -34,11 +34,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $langs->load("companies"); $langs->load("bills"); @@ -47,10 +48,11 @@ $langs->load("users"); $langs->load('other'); $action=GETPOST('action','alpha'); -$cancel=GETPOST('cancel'); +$cancel=GETPOST('cancel','alpha'); $backtopage=GETPOST('backtopage','alpha'); $confirm=GETPOST('confirm','alpha'); $rowid=GETPOST('rowid','int'); +$id=GETPOST('id')?GETPOST('id','int'):$rowid; $typeid=GETPOST('typeid','int'); $userid=GETPOST('userid','int'); $socid=GETPOST('socid','int'); @@ -71,7 +73,7 @@ $extrafields = new ExtraFields($db); $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Get object canvas (By default, this is not defined, so standard usage of dolibarr) -$object->getCanvas($rowid); +$object->getCanvas($id); $canvas = $object->canvas?$object->canvas:GETPOST("canvas"); $objcanvas=null; if (! empty($canvas)) @@ -82,12 +84,12 @@ if (! empty($canvas)) } // Security check -$result=restrictedArea($user, 'adherent', $rowid, '', '', 'fk_soc', 'rowid', $objcanvas); +$result=restrictedArea($user, 'adherent', $id, '', '', 'fk_soc', 'rowid', $objcanvas); -if ($rowid > 0) +if ($id > 0) { // Load member - $result = $object->fetch($rowid); + $result = $object->fetch($id); // Define variables to know what current user can do on users $canadduser=($user->admin || $user->rights->user->user->creer); @@ -105,7 +107,7 @@ if ($rowid > 0) // Define variables to determine what the current user can do on the members $canaddmember=$user->rights->adherent->creer; // Define variables to determine what the current user can do on the properties of a member -if ($rowid) +if ($id) { $caneditfieldmember=$user->rights->adherent->creer; } @@ -114,12 +116,14 @@ if ($rowid) $hookmanager->initHooks(array('membercard','globalcard')); + /* * Actions */ + if ($cancel) $action=''; -$parameters=array('rowid'=>$rowid, 'objcanvas'=>$objcanvas); +$parameters=array('id'=>$id, 'rowid'=>$id, 'objcanvas'=>$objcanvas); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); @@ -253,6 +257,7 @@ if (empty($reshook)) } $lastname=$_POST["lastname"]; $firstname=$_POST["firstname"]; + $societe=$_POST["societe"]; $morphy=$_POST["morphy"]; $login=$_POST["login"]; if ($morphy != 'mor' && empty($lastname)) { @@ -343,15 +348,15 @@ if (empty($reshook)) $object->setCategories($categories); // Logo/Photo save - $dir= $conf->adherent->dir_output . '/' . get_exdir($object->id,2,0,1,$object,'member').'/photos'; + $dir= $conf->adherent->dir_output . '/' . get_exdir(0,0,0,1,$object,'member').'/photos'; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); if ($file_OK) { if (GETPOST('deletephoto')) { require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - $fileimg=$conf->adherent->dir_output.'/'.get_exdir($object->id,2,0,1,$object,'member').'/photos/'.$object->photo; - $dirthumbs=$conf->adherent->dir_output.'/'.get_exdir($object->id,2,0,1,$object,'member').'/photos/thumbs'; + $fileimg=$conf->adherent->dir_output.'/'.get_exdir(0,0,0,1,$object,'member').'/photos/'.$object->photo; + $dirthumbs=$conf->adherent->dir_output.'/'.get_exdir(0,0,0,1,$object,'member').'/photos/thumbs'; dol_delete_file($fileimg); dol_delete_dir_recursive($dirthumbs); } @@ -394,6 +399,7 @@ if (empty($reshook)) } $rowid=$object->id; + $id=$object->id; $action=''; if (! empty($backtopage)) @@ -424,10 +430,10 @@ if (empty($reshook)) { $birthdate=dol_mktime(12, 0, 0, $_POST["birthmonth"], $_POST["birthday"], $_POST["birthyear"]); } - $datecotisation=''; + $datesubscription=''; if (isset($_POST["reday"]) && isset($_POST["remonth"]) && isset($_POST["reyear"])) { - $datecotisation=dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); + $datesubscription=dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); } $typeid=$_POST["typeid"]; @@ -451,7 +457,7 @@ if (empty($reshook)) $photo=$_POST["photo"]; //$comment=$_POST["comment"]; $morphy=$_POST["morphy"]; - $cotisation=$_POST["cotisation"]; + $subscription=$_POST["subscription"]; $public=$_POST["public"]; $userid=$_POST["userid"]; @@ -556,6 +562,7 @@ if (empty($reshook)) $db->commit(); $rowid=$object->id; + $id=$object->id; $action=''; } else @@ -578,7 +585,7 @@ if (empty($reshook)) if ($user->rights->adherent->supprimer && $action == 'confirm_delete' && $confirm == 'yes') { - $result=$object->delete($rowid); + $result=$object->delete($id); if ($result > 0) { if (! empty($backtopage)) @@ -707,6 +714,11 @@ if (empty($reshook)) } } } + + // Actions to build doc + $upload_dir = $conf->adherent->dir_output; + $permissioncreate=$user->rights->adherent->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } @@ -715,6 +727,7 @@ if (empty($reshook)) */ $form = new Form($db); +$formfile = new FormFile($db); $formcompany = new FormCompany($db); $title=$langs->trans("Member") . " - " . $langs->trans("Card"); @@ -728,10 +741,10 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // ----------------------------------------- // When used with CANVAS // ----------------------------------------- - if (empty($object->error) && $rowid) + if (empty($object->error) && $id) { $object = new Adherent($db); - $result=$object->fetch($rowid); + $result=$object->fetch($id); if ($result <= 0) dol_print_error('',$object->error); } $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates @@ -971,7 +984,7 @@ else * ********************************************/ - $res=$object->fetch($rowid); + $res=$object->fetch($id); if ($res < 0) { dol_print_error($db,$object->error); exit; } @@ -1036,14 +1049,10 @@ else print ''."\n"; } - $rowspan=15; - if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++; - if (! empty($conf->societe->enabled)) $rowspan++; - print '
'; print ''; print ''; - print ''; + print ''; print ''; if ($backtopage) print ''; @@ -1052,7 +1061,7 @@ else print ''; // Ref - print ''; + print ''; // Login if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) @@ -1065,21 +1074,7 @@ else $morphys["mor"] = $langs->trans("Morale"); print '"; - - // Photo - print ''; + print ""; // Type print ''; print ''; + // Photo + print ''; + print ''; + // EMail print ''; @@ -1235,7 +1245,7 @@ else } - if ($rowid && $action != 'edit') + if ($id > 0 && $action != 'edit') { /* ************************************************************************** */ /* */ @@ -1243,7 +1253,7 @@ else /* */ /* ************************************************************************** */ - $res=$object->fetch($rowid); + $res=$object->fetch($id); if ($res < 0) { dol_print_error($db,$object->error); exit; } @@ -1343,13 +1353,13 @@ else if (! empty($conf->mailman->enabled) && ! empty($conf->global->ADHERENT_USE_SPIP)) { $formquestion[]=array('type'=>'other','label'=>$langs->transnoentitiesnoconv("SynchroSpipEnabled"),'value'=>''); } - print $form->formconfirm("card.php?rowid=".$rowid,$langs->trans("ValidateMember"),$langs->trans("ConfirmValidateMember"),"confirm_valid",$formquestion,1,1); + print $form->formconfirm("card.php?rowid=".$id,$langs->trans("ValidateMember"),$langs->trans("ConfirmValidateMember"),"confirm_valid",$formquestion,1,1); } // Confirm send card by mail if ($action == 'sendinfo') { - print $form->formconfirm("card.php?rowid=".$rowid,$langs->trans("SendCardByMail"),$langs->trans("ConfirmSendCardByMail",$object->email),"confirm_sendinfo",'',0,1); + print $form->formconfirm("card.php?rowid=".$id,$langs->trans("SendCardByMail"),$langs->trans("ConfirmSendCardByMail",$object->email),"confirm_sendinfo",'',0,1); } // Confirm terminate @@ -1380,7 +1390,7 @@ else $formquestion=array(); if ($object->email) $formquestion[]=array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => (! empty($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL)?'true':'false')); if ($backtopage) $formquestion[]=array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); - print $form->formconfirm("card.php?rowid=".$rowid,$langs->trans("ResiliateMember"),$langs->trans("ConfirmResiliateMember"),"confirm_resign",$formquestion,'no',1); + print $form->formconfirm("card.php?rowid=".$id,$langs->trans("ResiliateMember"),$langs->trans("ConfirmResiliateMember"),"confirm_resign",$formquestion,'no',1); } // Confirm remove member @@ -1388,18 +1398,18 @@ else { $formquestion=array(); if ($backtopage) $formquestion[]=array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); - print $form->formconfirm("card.php?rowid=".$rowid,$langs->trans("DeleteMember"),$langs->trans("ConfirmDeleteMember"),"confirm_delete",$formquestion,0,1); + print $form->formconfirm("card.php?rowid=".$id,$langs->trans("DeleteMember"),$langs->trans("ConfirmDeleteMember"),"confirm_delete",$formquestion,0,1); } // Confirm add in spip if ($action == 'add_spip') { - print $form->formconfirm("card.php?rowid=".$rowid, $langs->trans('AddIntoSpip'), $langs->trans('AddIntoSpipConfirmation'), 'confirm_add_spip'); + print $form->formconfirm("card.php?rowid=".$id, $langs->trans('AddIntoSpip'), $langs->trans('AddIntoSpipConfirmation'), 'confirm_add_spip'); } // Confirm removed from spip if ($action == 'del_spip') { - print $form->formconfirm("card.php?rowid=$rowid", $langs->trans('DeleteIntoSpip'), $langs->trans('DeleteIntoSpipConfirmation'), 'confirm_del_spip'); + print $form->formconfirm("card.php?rowid=$id", $langs->trans('DeleteIntoSpip'), $langs->trans('DeleteIntoSpipConfirmation'), 'confirm_del_spip'); } $rowspan=17; @@ -1497,7 +1507,7 @@ else } else { - if (! $adht->cotisation) + if (! $adht->subscription) { print $langs->trans("SubscriptionNotRecorded"); if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated @@ -1601,7 +1611,7 @@ else // Modify if ($user->rights->adherent->creer) { - print '"; + print '"; } else { @@ -1613,7 +1623,7 @@ else { if ($user->rights->adherent->creer) { - print '\n"; + print '\n"; } else { @@ -1626,7 +1636,7 @@ else { if ($user->rights->adherent->creer) { - print '\n"; + print '\n"; } else { @@ -1657,7 +1667,7 @@ else { if ($user->rights->adherent->supprimer) { - print '\n"; + print '\n"; } else { @@ -1726,8 +1736,49 @@ else { print '

'.$langs->trans('SPIPConnectionFailed').': '.$mailmanspip->error.''; } - print "
\n"; + + + print '
'; + print ''; // ancre + + // Documents generes + $filename = dol_sanitizeFileName($object->ref); + //$filename = 'tmp_cards.php'; + //$filedir = $conf->adherent->dir_output . '/' . get_exdir($object->id, 2, 0, 0, $object, 'member') . dol_sanitizeFileName($object->ref); + $filedir = $conf->adherent->dir_output . '/' . get_exdir(0, 0, 0, 0, $object, 'member'); + $urlsource = $_SERVER['PHP_SELF'] . '?id=' . $object->id; + $genallowed = $user->rights->adherent->creer; + $delallowed = $user->rights->adherent->supprimer; + + print $formfile->showdocuments('member', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $object->default_lang, '', $object); + $somethingshown = $formfile->numoffiles; + + // Show links to link elements + //$linktoelem = $form->showLinkToObjectBlock($object, null, array('subscription')); + //$somethingshown = $form->showLinkedObjectBlock($object, ''); + + // Show links to link elements + /*$linktoelem = $form->showLinkToObjectBlock($object,array('order')); + if ($linktoelem) print ($somethingshown?'':'
').$linktoelem; + + // Link for paypal payment + /* + if (! empty($conf->paypal->enabled) && $object->statut != 0) { + include_once DOL_DOCUMENT_ROOT . '/paypal/lib/paypal.lib.php'; + print showPaypalPaymentUrl('invoice', $object->ref); + } + */ + print '
'; + + // List of actions on element + /* Already in tab Agenda/Events + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'member', $socid); + */ + print '
'; + } } diff --git a/htdocs/adherents/cartes/carte.php b/htdocs/adherents/cartes/carte.php index b5e4efaec16..db4c631c0c9 100644 --- a/htdocs/adherents/cartes/carte.php +++ b/htdocs/adherents/cartes/carte.php @@ -60,7 +60,7 @@ if ((! empty($foruserid) || ! empty($foruserlogin) || ! empty($mode)) && ! $mesg { $arrayofmembers=array(); - // requete en prenant que les adherents a jour de cotisation + // request taking into account member with up to date subscriptions $sql = "SELECT d.rowid, d.firstname, d.lastname, d.login, d.societe as company, d.datefin,"; $sql.= " d.address, d.zip, d.town, d.country, d.birth, d.email, d.photo,"; $sql.= " t.libelle as type,"; @@ -89,25 +89,25 @@ if ((! empty($foruserid) || ! empty($foruserlogin) || ! empty($mode)) && ! $mesg // List of values to scan for a replacement $substitutionarray = array ( - '%ID%'=>$objp->rowid, - '%LOGIN%'=>$objp->login, - '%FIRSTNAME%'=>$objp->firstname, - '%LASTNAME%'=>$objp->lastname, - '%FULLNAME%'=>$adherentstatic->getFullName($langs), - '%COMPANY%'=>$objp->company, - '%ADDRESS%'=>$objp->address, - '%ZIP%'=>$objp->zip, - '%TOWN%'=>$objp->town, - '%COUNTRY%'=>$objp->country, - '%COUNTRY_CODE%'=>$objp->country_code, - '%EMAIL%'=>$objp->email, - '%BIRTH%'=>dol_print_date($objp->birth,'day'), - '%TYPE%'=>$objp->type, - '%YEAR%'=>$year, - '%MONTH%'=>$month, - '%DAY%'=>$day, - '%DOL_MAIN_URL_ROOT%'=>DOL_MAIN_URL_ROOT, - '%SERVER%'=>"http://".$_SERVER["SERVER_NAME"]."/" + '%ID%'=>$objp->rowid, + '%LOGIN%'=>$objp->login, + '%FIRSTNAME%'=>$objp->firstname, + '%LASTNAME%'=>$objp->lastname, + '%FULLNAME%'=>$adherentstatic->getFullName($langs), + '%COMPANY%'=>$objp->company, + '%ADDRESS%'=>$objp->address, + '%ZIP%'=>$objp->zip, + '%TOWN%'=>$objp->town, + '%COUNTRY%'=>$objp->country, + '%COUNTRY_CODE%'=>$objp->country_code, + '%EMAIL%'=>$objp->email, + '%BIRTH%'=>dol_print_date($objp->birth,'day'), + '%TYPE%'=>$objp->type, + '%YEAR%'=>$year, + '%MONTH%'=>$month, + '%DAY%'=>$day, + '%DOL_MAIN_URL_ROOT%'=>DOL_MAIN_URL_ROOT, + '%SERVER%'=>"http://".$_SERVER["SERVER_NAME"]."/" ); complete_substitutions_array($substitutionarray, $langs); @@ -121,7 +121,10 @@ if ((! empty($foruserid) || ! empty($foruserlogin) || ! empty($mode)) && ! $mesg if (is_numeric($foruserid) || $foruserlogin) { - for($j=0;$j<100;$j++) + $nb = $_Avery_Labels[$model]['NX'] * $_Avery_Labels[$model]['NY']; + if ($nb <= 0) $nb=1; // Protection to avoid empty page + + for($j=0;$j<$nb;$j++) { $arrayofmembers[]=array( 'textleft'=>$textleft, diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 5c950b06e13..79c12e68561 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -5,11 +5,11 @@ * Copyright (C) 2004 Sebastien Di Cintio * Copyright (C) 2004 Benoit Mortier * Copyright (C) 2009-2012 Regis Houssin - * Copyright (C) 2014-2015 Alexandre Spangaro - * Copyright (C) 2015 Marcos García - * Copyright (C) 2015 Frederic France - * Copyright (C) 2015 Raphaël Doursenaud - * Copyright (C) 2016 Juanjo Menent + * Copyright (C) 2014-2016 Alexandre Spangaro + * Copyright (C) 2015 Marcos García + * Copyright (C) 2015 Frederic France + * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) 2016 Juanjo Menent * * 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 @@ -447,8 +447,8 @@ class Adherent extends CommonObject $sql.= ", fk_adherent_type=".$this->typeid; $sql.= ", morphy='".$this->morphy."'"; $sql.= ", birth=" .($this->birth?"'".$this->db->idate($this->birth)."'":"null"); - if ($this->datefin) $sql.= ", datefin='".$this->db->idate($this->datefin)."'"; // Ne doit etre modifie que par effacement cotisation - if ($this->datevalid) $sql.= ", datevalid='".$this->db->idate($this->datevalid)."'"; // Ne doit etre modifie que par validation adherent + if ($this->datefin) $sql.= ", datefin='".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription + if ($this->datevalid) $sql.= ", datevalid='".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member $sql.= ", fk_user_mod=".($user->id>0?$user->id:'null'); // Can be null because member can be create by a guest $sql.= " WHERE rowid = ".$this->id; @@ -643,7 +643,7 @@ class Adherent extends CommonObject // Search for last subscription id and end date $sql = "SELECT rowid, datec as dateop, dateadh as datedeb, datef as datefin"; - $sql.= " FROM ".MAIN_DB_PREFIX."cotisation"; + $sql.= " FROM ".MAIN_DB_PREFIX."subscription"; $sql.= " WHERE fk_adherent='".$this->id."'"; $sql.= " ORDER by dateadh DESC"; // Sort by start subscription date @@ -717,10 +717,10 @@ class Adherent extends CommonObject } - // Remove cotisation + // Remove subscription if (! $error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."cotisation WHERE fk_adherent = ".$rowid; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."subscription WHERE fk_adherent = ".$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) @@ -1070,9 +1070,10 @@ class Adherent extends CommonObject $sql.= " d.datevalid as datev,"; $sql.= " d.country,"; $sql.= " d.state_id,"; + $sql.= " d.model_pdf,"; $sql.= " c.rowid as country_id, c.code as country_code, c.label as country,"; $sql.= " dep.nom as state, dep.code_departement as state_code,"; - $sql.= " t.libelle as type, t.cotisation as cotisation,"; + $sql.= " t.libelle as type, t.subscription as subscription,"; $sql.= " u.rowid as user_id, u.login as user_login"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent_type as t, ".MAIN_DB_PREFIX."adherent as d"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.country = c.rowid"; @@ -1150,10 +1151,12 @@ class Adherent extends CommonObject $this->typeid = $obj->fk_adherent_type; $this->type = $obj->type; - $this->need_subscription = ($obj->cotisation=='yes'?1:0); + $this->need_subscription = ($obj->subscription=='yes'?1:0); $this->user_id = $obj->user_id; $this->user_login = $obj->user_login; + + $this->model_pdf = $obj->model_pdf; // Retreive all extrafield for thirdparty // fetch optionals attributes and labels @@ -1193,14 +1196,14 @@ class Adherent extends CommonObject { global $langs; - require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; - $sql = "SELECT c.rowid, c.fk_adherent, c.cotisation, c.note, c.fk_bank,"; + $sql = "SELECT c.rowid, c.fk_adherent, c.subscription, c.note, c.fk_bank,"; $sql.= " c.tms as datem,"; $sql.= " c.datec as datec,"; $sql.= " c.dateadh as dateh,"; $sql.= " c.datef as datef"; - $sql.= " FROM ".MAIN_DB_PREFIX."cotisation as c"; + $sql.= " FROM ".MAIN_DB_PREFIX."subscription as c"; $sql.= " WHERE c.fk_adherent = ".$this->id; $sql.= " ORDER BY c.dateadh"; dol_syslog(get_class($this)."::fetch_subscriptions", LOG_DEBUG); @@ -1216,15 +1219,15 @@ class Adherent extends CommonObject if ($i==0) { $this->first_subscription_date=$obj->dateh; - $this->first_subscription_amount=$obj->cotisation; + $this->first_subscription_amount=$obj->subscription; } $this->last_subscription_date=$obj->dateh; - $this->last_subscription_amount=$obj->cotisation; + $this->last_subscription_amount=$obj->subscription; - $subscription=new Cotisation($this->db); + $subscription=new Subscription($this->db); $subscription->id=$obj->rowid; $subscription->fk_adherent=$obj->fk_adherent; - $subscription->amount=$obj->cotisation; + $subscription->amount=$obj->subscription; $subscription->note=$obj->note; $subscription->fk_bank=$obj->fk_bank; $subscription->datem=$this->db->jdate($obj->datem); @@ -1260,11 +1263,11 @@ class Adherent extends CommonObject * @param int $datesubend Date end subscription * @return int rowid of record added, <0 if KO */ - function cotisation($date, $montant, $accountid=0, $operation='', $label='', $num_chq='', $emetteur_nom='', $emetteur_banque='', $datesubend=0) + function subscription($date, $montant, $accountid=0, $operation='', $label='', $num_chq='', $emetteur_nom='', $emetteur_banque='', $datesubend=0) { global $conf,$langs,$user; - require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $error=0; @@ -1285,14 +1288,14 @@ class Adherent extends CommonObject } // Create subscription - $cotisation=new Cotisation($this->db); - $cotisation->fk_adherent=$this->id; - $cotisation->dateh=$date; // Date of new subscription - $cotisation->datef=$datefin; // End data of new subscription - $cotisation->amount=$montant; - $cotisation->note=$label; + $subscription=new Subscription($this->db); + $subscription->fk_adherent=$this->id; + $subscription->dateh=$date; // Date of new subscription + $subscription->datef=$datefin; // End data of new subscription + $subscription->amount=$montant; + $subscription->note=$label; - $rowid=$cotisation->create($user); + $rowid=$subscription->create($user); if ($rowid > 0) { // Update denormalized subscription end date (read database subscription to find values) @@ -1325,7 +1328,7 @@ class Adherent extends CommonObject } else { - $this->error=$cotisation->error; + $this->error=$subscription->error; $this->db->rollback(); return -1; } @@ -1587,7 +1590,7 @@ class Adherent extends CommonObject } if ($option == 'subscription') { - $link = ''; } @@ -1614,7 +1617,7 @@ class Adherent extends CommonObject * Renvoi le libelle d'un statut donne * * @param int $statut Id statut - * @param int $need_subscription 1 si type adherent avec cotisation, 0 sinon + * @param int $need_subscription 1 if member type need subscription, 0 otherwise * @param int $date_end_subscription Date fin adhesion * @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 @@ -1679,6 +1682,17 @@ class Adherent extends CommonObject if ($statut == 0) return img_picto($langs->trans('MemberStatusResiliated'),'statut5').' '.$langs->trans("MemberStatusResiliated"); } if ($mode == 5) + { + if ($statut == -1) return $langs->trans("MemberStatusDraft").' '.img_picto($langs->trans('MemberStatusDraft'),'statut0'); + if ($statut >= 1) + { + if (! $date_end_subscription) return ''.$langs->trans("MemberStatusActiveShort").' '.img_picto($langs->trans('MemberStatusActive'),'statut1'); + elseif ($date_end_subscription < time()) return ''.$langs->trans("MemberStatusActiveLateShort").' '.img_picto($langs->trans('MemberStatusActiveLate'),'statut3'); + else return ''.$langs->trans("MemberStatusPaidShort").' '.img_picto($langs->trans('MemberStatusPaid'),'statut4'); + } + if ($statut == 0) return ''.$langs->trans("MemberStatusResiliated").' '.img_picto($langs->trans('MemberStatusResiliated'),'statut5'); + } + if ($mode == 6) { if ($statut == -1) return $langs->trans("MemberStatusDraft").' '.img_picto($langs->trans('MemberStatusDraft'),'statut0'); if ($statut >= 1) @@ -1753,7 +1767,7 @@ class Adherent extends CommonObject $langs->load("members"); $response = new WorkboardResponse(); - $response->warning_delay=$conf->adherent->cotisation->warning_delay/60/60/24; + $response->warning_delay=$conf->adherent->subscription->warning_delay/60/60/24; $response->label=$langs->trans("MembersWithSubscriptionToReceive"); $response->url=DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&statut=1&filter=outofdate'; $response->img=img_object($langs->trans("Members"),"user"); @@ -1783,6 +1797,41 @@ class Adherent extends CommonObject } + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf,$langs; + + $langs->load("orders"); + + // Positionne le modele sur le nom du modele a utiliser + if (! dol_strlen($modele)) + { + if (! empty($conf->global->ADHERENT_ADDON_PDF)) + { + $modele = $conf->global->ADHERENT_ADDON_PDF; + } + else + { + $modele = 'standard'; + } + } + + $modelpath = "core/modules/member/doc/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + + /** * Initialise an instance with random values. * Used to build previews or test instances. @@ -2039,7 +2088,7 @@ class Adherent extends CommonObject $now = dol_now(); - return $this->datefin < ($now - $conf->adherent->cotisation->warning_delay); + return $this->datefin < ($now - $conf->adherent->subscription->warning_delay); } } diff --git a/htdocs/adherents/class/adherent_type.class.php b/htdocs/adherents/class/adherent_type.class.php index 71f41d84e00..7520bdbf6a5 100644 --- a/htdocs/adherents/class/adherent_type.class.php +++ b/htdocs/adherents/class/adherent_type.class.php @@ -2,7 +2,7 @@ /* Copyright (C) 2002 Rodolphe Quiedeville * Copyright (C) 2004-2008 Laurent Destailleur * Copyright (C) 2009 Regis Houssin - * Copyright (C) 2016 Charlie Benke + * Copyright (C) 2016 Charlie Benke * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -33,17 +33,28 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; */ class AdherentType extends CommonObject { - public $table_element = 'adherent_type'; - public $element = 'adherent_type'; + public $table_element = 'adherent_type'; + public $element = 'adherent_type'; - var $id; - var $ref; - var $libelle; - var $cotisation; // Soumis a la cotisation - var $note; - var $vote; // droit de vote - var $mail_valid; //mail envoye lors de la validation - var $statut; + /** @var string Label */ + public $libelle; + /** + * @var bool + * @deprecated Use subscription + * @see subscription + */ + public $cotisation; + /** + * @var bool Subsription required + * @since 5.0 + */ + public $subscription; + /** @var string Public note */ + public $note; + /** @var bool Can vote*/ + public $vote; + /** @var bool Email sent during validation */ + public $mail_valid; /** @@ -111,7 +122,7 @@ class AdherentType extends CommonObject $sql.= "SET "; $sql.= "statut = ".$this->statut.","; $sql.= "libelle = '".$this->db->escape($this->libelle) ."',"; - $sql.= "cotisation = '".$this->cotisation."',"; + $sql.= "subscription = '".$this->subscription."',"; $sql.= "note = '".$this->db->escape($this->note)."',"; $sql.= "vote = '".$this->vote."',"; $sql.= "mail_valid = '".$this->db->escape($this->mail_valid)."'"; @@ -188,7 +199,7 @@ class AdherentType extends CommonObject */ function fetch($rowid) { - $sql = "SELECT d.rowid, d.libelle, d.statut, d.cotisation, d.mail_valid, d.note, d.vote"; + $sql = "SELECT d.rowid, d.libelle, d.statut, d.subscription, d.mail_valid, d.note, d.vote"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as d"; $sql .= " WHERE d.rowid = ".$rowid; @@ -205,7 +216,7 @@ class AdherentType extends CommonObject $this->ref = $obj->rowid; $this->libelle = $obj->libelle; $this->statut = $obj->statut; - $this->cotisation = $obj->cotisation; + $this->subscription = $obj->subscription; $this->mail_valid = $obj->mail_valid; $this->note = $obj->note; $this->vote = $obj->vote; diff --git a/htdocs/adherents/class/adherentstats.class.php b/htdocs/adherents/class/adherentstats.class.php index d3f72d2ea5d..97a4c8201a7 100644 --- a/htdocs/adherents/class/adherentstats.class.php +++ b/htdocs/adherents/class/adherentstats.class.php @@ -24,7 +24,7 @@ */ include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; -include_once DOL_DOCUMENT_ROOT . '/adherents/class/cotisation.class.php'; +include_once DOL_DOCUMENT_ROOT . '/adherents/class/subscription.class.php'; /** @@ -57,12 +57,12 @@ class AdherentStats extends Stats $this->socid = $socid; $this->userid = $userid; - $object=new Cotisation($this->db); + $object=new Subscription($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as p"; $this->from.= ", ".MAIN_DB_PREFIX."adherent as m"; - $this->field='cotisation'; + $this->field='subscription'; $this->where.= " m.statut != 0"; $this->where.= " AND p.fk_adherent = m.rowid AND m.entity IN (".getEntity('adherent', 1).")"; @@ -76,7 +76,7 @@ class AdherentStats extends Stats /** - * Renvoie le nombre de proposition par mois pour une annee donnee + * Return the number of proposition by month for a given year * * @param int $year Year * @return array Array of nb each month @@ -97,7 +97,7 @@ class AdherentStats extends Stats } /** - * Renvoie le nombre de cotisation par annee + * Return the number of subscriptions by year * * @return array Array of nb each year */ @@ -116,7 +116,7 @@ class AdherentStats extends Stats } /** - * Renvoie le nombre de cotisation par mois pour une annee donnee + * Return the number of subscriptions by month for a given year * * @param int $year Year * @return array Array of amount each month diff --git a/htdocs/adherents/class/api_members.class.php b/htdocs/adherents/class/api_members.class.php new file mode 100644 index 00000000000..548b5728b1a --- /dev/null +++ b/htdocs/adherents/class/api_members.class.php @@ -0,0 +1,365 @@ + + * + * 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.'/adherents/class/adherent.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; + +/** + * API class for members + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Members extends DolibarrApi +{ + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'morphy', + 'typeid' + ); + + /** + * Constructor + */ + function __construct() + { + global $db, $conf; + $this->db = $db; + } + + /** + * Get properties of a member object + * + * Return an array with member informations + * + * @param int $id ID of member + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { + if(! DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } + + $member = new Adherent($this->db); + $result = $member->fetch($id); + if( ! $result ) { + throw new RestException(404, 'member not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('adherent',$member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($member); + } + + /** + * List members + * + * Get a list of members + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $typeid ID of the type of member + * @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 member objects + * + * @throws RestException + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $typeid = '', $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + + if(! DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } + + $sql = "SELECT t.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."adherent as t"; + $sql.= ' WHERE t.entity IN ('.getEntity('adherent', 1).')'; + if (!empty($typeid)) + { + $sql.= ' AND t.fk_adherent_type='.$typeid; + } + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $db->plimit($limit + 1, $offset); + } + + $result = $db->query($sql); + if ($result) + { + $i=0; + $num = $db->num_rows($result); + while ($i < min($limit, $num)) + { + $obj = $db->fetch_object($result); + $member = new Adherent($this->db); + if($member->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($member); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve member list : '.$member->error); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No member found'); + } + + return $obj_ret; + } + + /** + * Create member object + * + * @param array $request_data Request data + * @return int ID of member + */ + function post($request_data = null) + { + if(! DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + $member = new Adherent($this->db); + foreach($request_data as $field => $value) { + $member->$field = $value; + } + if($member->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(503, 'Error when create member : '.$member->error); + } + return $member->id; + } + + /** + * Update member + * + * @param int $id ID of member to update + * @param array $request_data Datas + * @return int + */ + function put($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + + $member = new Adherent($this->db); + $result = $member->fetch($id); + if( ! $result ) { + throw new RestException(404, 'member not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('member',$member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + foreach($request_data as $field => $value) { + // Process the status separately because it must be updated using + // the validate() and resiliate() methods of the class Adherent. + if ($field == 'statut') { + if ($value == '0') { + $result = $member->resiliate(DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(500, 'Error when resiliating member: '.$member->error); + } + } else if ($value == '1') { + $result = $member->validate(DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(500, 'Error when validating member: '.$member->error); + } + } + } else { + $member->$field = $value; + } + } + + // If there is no error, update() returns the number of affected rows + // so if the update is a no op, the return value is zero. + if($member->update(DolibarrApiAccess::$user) >= 0) + return $this->get($id); + + return false; + } + + /** + * Delete member + * + * @param int $id member ID + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->adherent->supprimer) { + throw new RestException(401); + } + $member = new Adherent($this->db); + $result = $member->fetch($id); + if( ! $result ) { + throw new RestException(404, 'member not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('member',$member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + // The Adherent::delete() method uses the global variable $user. + global $user; + $user = DolibarrApiAccess::$user; + + if (! $member->delete($member->id)) { + throw new RestException(401,'error when deleting member'); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'member deleted' + ) + ); + } + + /** + * Validate fields before creating an object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + function _validate($data) + { + $member = array(); + foreach (Members::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $member[$field] = $data[$field]; + } + return $member; + } + + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + * + * @todo use an array for properties to clean + * + */ + function _cleanObjectDatas($object) { + + $object = parent::_cleanObjectDatas($object); + + // Remove the subscriptions because they are handled as a subresource. + unset($object->subscriptions); + + return $object; + } + + /** + * List subscriptions of a member + * + * Get a list of subscriptions + * + * @param int $id ID of member + * @return array Array of subscription objects + * + * @throws RestException + * + * @url GET {id}/subscriptions + */ + function getSubscriptions($id) + { + $obj_ret = array(); + + if(! DolibarrApiAccess::$user->rights->adherent->cotisation->lire) { + throw new RestException(401); + } + + $member = new Adherent($this->db); + $result = $member->fetch($id); + if( ! $result ) { + throw new RestException(404, 'member not found'); + } + + $obj_ret = array(); + foreach ($member->subscriptions as $subscription) { + $obj_ret[] = $this->_cleanObjectDatas($subscription); + } + return $obj_ret; + } + + /** + * Add a subscription for a member + * + * @param int $id ID of member + * @param int $start_date Start date {@from body} {@type timestamp} + * @param int $end_date End date {@from body} {@type timestamp} + * @param float $amount Amount (may be 0) {@from body} + * @param string $label Label {@from body} + * @return int ID of subscription + * + * @url POST {id}/subscriptions + */ + function createSubscription($id, $start_date, $end_date, $amount, $label='') + { + if(! DolibarrApiAccess::$user->rights->adherent->cotisation->creer) { + throw new RestException(401); + } + + $member = new Adherent($this->db); + $result = $member->fetch($id); + if( ! $result ) { + throw new RestException(404, 'member not found'); + } + + return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date); + } + +} diff --git a/htdocs/adherents/class/api_subscriptions.class.php b/htdocs/adherents/class/api_subscriptions.class.php new file mode 100644 index 00000000000..2dd2a609e63 --- /dev/null +++ b/htdocs/adherents/class/api_subscriptions.class.php @@ -0,0 +1,248 @@ + + * + * 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.'/adherents/class/subscription.class.php'; + +/** + * API class for subscriptions + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Subscriptions extends DolibarrApi +{ + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'fk_adherent', + 'dateh', + 'datef', + 'amount' + ); + + /** + * Constructor + */ + function __construct() + { + global $db, $conf; + $this->db = $db; + } + + /** + * Get properties of a subscription object + * + * Return an array with subscription informations + * + * @param int $id ID of subscription + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { + if(! DolibarrApiAccess::$user->rights->adherent->cotisation->lire) { + throw new RestException(401); + } + + $subscription = new Subscription($this->db); + $result = $subscription->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Subscription not found'); + } + + return $this->_cleanObjectDatas($subscription); + } + + /** + * List subscriptions + * + * Get a list of subscriptions + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.import_key:<:'20160101')" + * @return array Array of subscription objects + * + * @throws RestException + */ + function index($sortfield = "dateadh", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + + if(! DolibarrApiAccess::$user->rights->adherent->cotisation->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."subscription as t"; + $sql.= ' WHERE 1 = 1'; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $db->plimit($limit + 1, $offset); + } + + $result = $db->query($sql); + if ($result) + { + $i=0; + $num = $db->num_rows($result); + while ($i < min($limit, $num)) + { + $obj = $db->fetch_object($result); + $subscription = new Subscription($this->db); + if($subscription->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($subscription); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve subscription list : '.$subscription->error); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No Subscription found'); + } + + return $obj_ret; + } + + /** + * Create subscription object + * + * @param array $request_data Request data + * @return int ID of subscription + */ + function post($request_data = null) + { + if(! DolibarrApiAccess::$user->rights->adherent->cotisation->creer) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + $subscription = new Subscription($this->db); + foreach($request_data as $field => $value) { + $subscription->$field = $value; + } + if($subscription->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(503, 'Error when create subscription : '.$subscription->error); + } + return $subscription->id; + } + + /** + * Update subscription + * + * @param int $id ID of subscription to update + * @param array $request_data Datas + * @return int + */ + function put($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + + $subscription = new Subscription($this->db); + $result = $subscription->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Subscription not found'); + } + + foreach($request_data as $field => $value) { + $subscription->$field = $value; + } + + if ($subscription->update(DolibarrApiAccess::$user) > 0) + return $this->get($id); + + return false; + } + + /** + * Delete subscription + * + * @param int $id ID of subscription to delete + * @return array + */ + function delete($id) + { + // The right to delete a subscription comes with the right to create one. + if(! DolibarrApiAccess::$user->rights->adherent->cotisation->creer) { + throw new RestException(401); + } + $subscription = new Subscription($this->db); + $result = $subscription->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Subscription not found'); + } + + if (! $subscription->delete(DolibarrApiAccess::$user)) { + throw new RestException(401,'error when deleting subscription'); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'subscription deleted' + ) + ); + } + + /** + * Validate fields before creating an object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + function _validate($data) + { + $subscription = array(); + foreach (Subscriptions::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $subscription[$field] = $data[$field]; + } + return $subscription; + } +} diff --git a/htdocs/adherents/class/cotisation.class.php b/htdocs/adherents/class/subscription.class.php similarity index 83% rename from htdocs/adherents/class/cotisation.class.php rename to htdocs/adherents/class/subscription.class.php index 9fe26727c25..bc2234e9d5c 100644 --- a/htdocs/adherents/class/cotisation.class.php +++ b/htdocs/adherents/class/subscription.class.php @@ -17,9 +17,9 @@ */ /** - * \file htdocs/adherents/class/cotisation.class.php - * \ingroup member - * \brief File of class to manage subscriptions of foundation members + * \file htdocs/adherents/class/subscription.class.php + * \ingroup member + * \brief File of class to manage subscriptions of foundation members */ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; @@ -28,10 +28,10 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; /** * Class to manage subscriptions of foundation members */ -class Cotisation extends CommonObject +class Subscription extends CommonObject { public $element='subscription'; - public $table_element='cotisation'; + public $table_element='subscription'; var $datec; // Date creation var $datem; // Date modification @@ -54,7 +54,7 @@ class Cotisation extends CommonObject /** - * Fonction qui permet de creer la cotisation + * Function who permitted cretaion of the subscription * * @param int $userid userid de celui qui insere * @return int <0 if KO, Id subscription created if OK @@ -72,17 +72,19 @@ class Cotisation extends CommonObject return -1; } - $sql = "INSERT INTO ".MAIN_DB_PREFIX."cotisation (fk_adherent, datec, dateadh, datef, cotisation, note)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."subscription (fk_adherent, datec, dateadh, datef, subscription, note)"; $sql.= " VALUES (".$this->fk_adherent.", '".$this->db->idate($now)."',"; $sql.= " '".$this->db->idate($this->dateh)."',"; $sql.= " '".$this->db->idate($this->datef)."',"; - $sql.= " ".$this->amount.",'".$this->db->escape($this->note)."')"; + $sql.= " ".$this->amount.","; + $sql.= " '".$this->db->escape($this->note)."')"; dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - return $this->db->last_insert_id(MAIN_DB_PREFIX."cotisation"); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."subscription"); + return $this->id; } else { @@ -104,8 +106,8 @@ class Cotisation extends CommonObject $sql.=" tms,"; $sql.=" dateadh as dateh,"; $sql.=" datef,"; - $sql.=" cotisation, note, fk_bank"; - $sql.=" FROM ".MAIN_DB_PREFIX."cotisation"; + $sql.=" subscription, note, fk_bank"; + $sql.=" FROM ".MAIN_DB_PREFIX."subscription"; $sql.=" WHERE rowid=".$rowid; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -124,7 +126,7 @@ class Cotisation extends CommonObject $this->datem = $this->db->jdate($obj->tms); $this->dateh = $this->db->jdate($obj->dateh); $this->datef = $this->db->jdate($obj->datef); - $this->amount = $obj->cotisation; + $this->amount = $obj->subscription; $this->note = $obj->note; $this->fk_bank = $obj->fk_bank; return 1; @@ -143,20 +145,20 @@ class Cotisation extends CommonObject /** - * Met a jour en base la cotisation + * Update subscription * - * @param User $user Objet user qui met a jour - * @param int $notrigger 0=Desactive les triggers + * @param User $user User who updated + * @param int $notrigger 0=Disable triggers * @return int <0 if KO, >0 if OK */ function update($user,$notrigger=0) { $this->db->begin(); - $sql = "UPDATE ".MAIN_DB_PREFIX."cotisation SET "; + $sql = "UPDATE ".MAIN_DB_PREFIX."subscription SET "; $sql .= " fk_adherent = ".$this->fk_adherent.","; $sql .= " note=".($this->note ? "'".$this->db->escape($this->note)."'" : 'null').","; - $sql .= " cotisation = '".price2num($this->amount)."',"; + $sql .= " subscription = '".price2num($this->amount)."',"; $sql .= " dateadh='".$this->db->idate($this->dateh)."',"; $sql .= " datef='".$this->db->idate($this->datef)."',"; $sql .= " datec='".$this->db->idate($this->datec)."',"; @@ -201,7 +203,7 @@ class Cotisation extends CommonObject $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."cotisation WHERE rowid = ".$this->id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."subscription WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -263,7 +265,7 @@ class Cotisation extends CommonObject $result=''; $label=$langs->trans("ShowSubscription").': '.$this->ref; - $link = ''; + $link = ''; $linkend=''; $picto='payment'; @@ -276,7 +278,7 @@ class Cotisation extends CommonObject /** - * Charge les informations d'ordre info dans l'objet cotisation + * Load information of the subscription object * * @param int $id Id subscription * @return void @@ -285,7 +287,7 @@ class Cotisation extends CommonObject { $sql = 'SELECT c.rowid, c.datec,'; $sql.= ' c.tms as datem'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'cotisation as c'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'subscription as c'; $sql.= ' WHERE c.rowid = '.$id; $result=$this->db->query($sql); diff --git a/htdocs/adherents/document.php b/htdocs/adherents/document.php index eebb4fda37f..47fbebbf976 100644 --- a/htdocs/adherents/document.php +++ b/htdocs/adherents/document.php @@ -69,7 +69,7 @@ if ($result < 0) dol_print_error($db); exit; } -$upload_dir = $conf->adherent->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'member') . '/' . dol_sanitizeFileName($object->ref); +$upload_dir = $conf->adherent->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'member'); /* @@ -158,6 +158,7 @@ if ($id > 0) $modulepart = 'member'; $permission = $user->rights->adherent->creer; + $permtoedit = $user->rights->adherent->creer; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; print "

"; diff --git a/htdocs/adherents/htpasswd.php b/htdocs/adherents/htpasswd.php index ffa1a92124b..5814ed3bf70 100644 --- a/htdocs/adherents/htpasswd.php +++ b/htdocs/adherents/htpasswd.php @@ -48,7 +48,7 @@ if (! isset($statut)) if (! isset($cotis)) { - // par defaut les adherents doivent etre a jour de cotisation + // by default, members must be up to date of subscription $cotis=1; } diff --git a/htdocs/adherents/index.php b/htdocs/adherents/index.php index 8515dc1d2c8..af259296c37 100644 --- a/htdocs/adherents/index.php +++ b/htdocs/adherents/index.php @@ -27,7 +27,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $langs->load("companies"); $langs->load("members"); @@ -44,7 +44,7 @@ llxHeader('',$langs->trans("Members"),'EN:Module_Foundations|FR:Module_Adh&eacut $staticmember=new Adherent($db); $statictype=new AdherentType($db); -$subscriptionstatic=new Cotisation($db); +$subscriptionstatic=new Subscription($db); print load_fiche_titre($langs->trans("MembersArea")); @@ -59,14 +59,14 @@ $AdherentsResilies=array(); $AdherentType=array(); // Liste les adherents -$sql = "SELECT t.rowid, t.libelle, t.cotisation,"; +$sql = "SELECT t.rowid, t.libelle, t.subscription,"; $sql.= " d.statut, count(d.rowid) as somme"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent_type as t"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."adherent as d"; $sql.= " ON t.rowid = d.fk_adherent_type"; $sql.= " AND d.entity IN (".getEntity().")"; $sql.= " WHERE t.entity IN (".getEntity().")"; -$sql.= " GROUP BY t.rowid, t.libelle, t.cotisation, d.statut"; +$sql.= " GROUP BY t.rowid, t.libelle, t.subscription, d.statut"; dol_syslog("index.php::select nb of members by type", LOG_DEBUG); $result = $db->query($sql); @@ -80,7 +80,7 @@ if ($result) $adhtype=new AdherentType($db); $adhtype->id=$objp->rowid; - $adhtype->cotisation=$objp->cotisation; + $adhtype->subscription=$objp->subscription; $adhtype->libelle=$objp->libelle; $AdherentType[$objp->rowid]=$adhtype; @@ -101,7 +101,7 @@ $now=dol_now(); $sql = "SELECT count(*) as somme , d.fk_adherent_type"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."adherent_type as t"; $sql.= " WHERE d.entity IN (".getEntity().")"; -//$sql.= " AND d.statut = 1 AND ((t.cotisation = 0 AND d.datefin IS NULL) OR d.datefin >= '".$db->idate($now)."')"; +//$sql.= " AND d.statut = 1 AND ((t.subscription = 0 AND d.datefin IS NULL) OR d.datefin >= '".$db->idate($now)."')"; $sql.= " AND d.statut = 1 AND d.datefin >= '".$db->idate($now)."'"; $sql.= " AND t.rowid = d.fk_adherent_type"; $sql.= " GROUP BY d.fk_adherent_type"; @@ -212,7 +212,7 @@ $max=5; $sql = "SELECT a.rowid, a.statut, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; $sql.= " a.tms as datem, datefin as date_end_subscription,"; -$sql.= " ta.rowid as typeid, ta.libelle, ta.cotisation"; +$sql.= " ta.rowid as typeid, ta.libelle, ta.subscription"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a, ".MAIN_DB_PREFIX."adherent_type as ta"; $sql.= " WHERE a.entity IN (".getEntity().")"; $sql.= " AND a.fk_adherent_type = ta.rowid"; @@ -255,7 +255,7 @@ if ($resql) print '
'; print ''; print ''; - print ''; + print ''; print ''; $i++; } @@ -275,8 +275,8 @@ $max=5; $sql = "SELECT a.rowid, a.statut, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; $sql.= " datefin as date_end_subscription,"; -$sql.= " c.rowid as cid, c.tms as datem, c.datec as datec, c.dateadh as date_start, c.datef as date_end, c.cotisation"; -$sql.= " FROM ".MAIN_DB_PREFIX."adherent as a, ".MAIN_DB_PREFIX."cotisation as c"; +$sql.= " c.rowid as cid, c.tms as datem, c.datec as datec, c.dateadh as date_start, c.datef as date_end, c.subscription"; +$sql.= " FROM ".MAIN_DB_PREFIX."adherent as a, ".MAIN_DB_PREFIX."subscription as c"; $sql.= " WHERE a.entity IN (".getEntity().")"; $sql.= " AND c.fk_adherent = a.rowid"; $sql.= $db->order("c.tms","DESC"); @@ -315,8 +315,8 @@ if ($resql) print ''; print ''; print ''; - print ''; - //print ''; + print ''; + //print ''; print ''; print ''; $i++; @@ -345,18 +345,18 @@ foreach ($AdherentType as $key => $adhtype) $var=!$var; print ""; print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print "\n"; } print ''; print ''; -print ''; -print ''; -print ''; -print ''; +print ''; +print ''; +print ''; +print ''; print ''; print "
'.$langs->trans("Ref").''.$object->id.'
'.$langs->trans("Ref").''.$object->id.'
'.$langs->trans("Nature").''; print $form->selectarray("morphy", $morphys, isset($_POST["morphy"])?$_POST["morphy"]:$object->morphy); - print "'; - print $form->showphoto('memberphoto',$object)."\n"; - if ($caneditfieldmember) - { - if ($object->photo) print "
\n"; - print ''; - if ($object->photo) print ''; - print ''; - print ''; - print '
'.$langs->trans("Delete").'

'.$langs->trans("PhotoFile").'
'; - } - print '
'.$langs->trans("Type").''; @@ -1111,6 +1106,21 @@ else print '
'.$langs->trans("Firstname").'firstname).'">
'.$langs->trans("Photo").''; + print $form->showphoto('memberphoto',$object)."\n"; + if ($caneditfieldmember) + { + if ($object->photo) print "
\n"; + print ''; + if ($object->photo) print ''; + print ''; + print ''; + print '
'.$langs->trans("Delete").'

'.$langs->trans("PhotoFile").'
'; + } + print '
'.($conf->global->ADHERENT_MAIL_REQUIRED?'':'').$langs->trans("EMail").($conf->global->ADHERENT_MAIL_REQUIRED?'':'').'email).'">
'.$staticmember->getNomUrl(1,32).''.$statictype->getNomUrl(1,32).''.dol_print_date($db->jdate($obj->datem),'dayhour').''.$staticmember->LibStatut($obj->statut,($obj->cotisation=='yes'?1:0),$db->jdate($obj->date_end_subscription),5).''.$staticmember->LibStatut($obj->statut,($obj->subscription=='yes'?1:0),$db->jdate($obj->date_end_subscription),5).'
'.$subscriptionstatic->getNomUrl(1).''.$staticmember->getNomUrl(1,32,'subscription').''.get_date_range($db->jdate($obj->date_start),$db->jdate($obj->date_end)).''.price($obj->cotisation).''.$staticmember->LibStatut($obj->statut,($obj->cotisation=='yes'?1:0),$db->jdate($obj->date_end_subscription),5).''.price($obj->subscription).''.$staticmember->LibStatut($obj->statut,($obj->subscription=='yes'?1:0),$db->jdate($obj->date_end_subscription),5).''.dol_print_date($db->jdate($obj->datem?$obj->datem:$obj->datec),'dayhour').'
'.$adhtype->getNomUrl(1, dol_size(32)).''.(isset($MemberToValidate[$key]) && $MemberToValidate[$key] > 0?$MemberToValidate[$key]:'').' '.$staticmember->LibStatut(-1,$adhtype->cotisation,0,3).''.(isset($MembersValidated[$key]) && ($MembersValidated[$key]-(isset($MemberUpToDate[$key])?$MemberUpToDate[$key]:0) > 0) ? $MembersValidated[$key]-(isset($MemberUpToDate[$key])?$MemberUpToDate[$key]:0):'').' '.$staticmember->LibStatut(1,$adhtype->cotisation,0,3).''.(isset($MemberUpToDate[$key]) && $MemberUpToDate[$key] > 0 ? $MemberUpToDate[$key]:'').' '.$staticmember->LibStatut(1,$adhtype->cotisation,$now,3).''.(isset($MembersResiliated[$key]) && $MembersResiliated[$key]> 0 ?$MembersResiliated[$key]:'').' '.$staticmember->LibStatut(0,$adhtype->cotisation,0,3).''.(isset($MemberToValidate[$key]) && $MemberToValidate[$key] > 0?$MemberToValidate[$key]:'').' '.$staticmember->LibStatut(-1,$adhtype->subscription,0,3).''.(isset($MembersValidated[$key]) && ($MembersValidated[$key]-(isset($MemberUpToDate[$key])?$MemberUpToDate[$key]:0) > 0) ? $MembersValidated[$key]-(isset($MemberUpToDate[$key])?$MemberUpToDate[$key]:0):'').' '.$staticmember->LibStatut(1,$adhtype->subscription,0,3).''.(isset($MemberUpToDate[$key]) && $MemberUpToDate[$key] > 0 ? $MemberUpToDate[$key]:'').' '.$staticmember->LibStatut(1,$adhtype->subscription,$now,3).''.(isset($MembersResiliated[$key]) && $MembersResiliated[$key]> 0 ?$MembersResiliated[$key]:'').' '.$staticmember->LibStatut(0,$adhtype->subscription,0,3).'
'.$langs->trans("Total").''.$SommeA.' '.$staticmember->LibStatut(-1,$adhtype->cotisation,0,3).''.$SommeB.' '.$staticmember->LibStatut(1,$adhtype->cotisation,0,3).''.$SommeC.' '.$staticmember->LibStatut(1,$adhtype->cotisation,$now,3).''.$SommeD.' '.$staticmember->LibStatut(0,$adhtype->cotisation,0,3).''.$SommeA.' '.$staticmember->LibStatut(-1,$adhtype->subscription,0,3).''.$SommeB.' '.$staticmember->LibStatut(1,$adhtype->subscription,0,3).''.$SommeC.' '.$staticmember->LibStatut(1,$adhtype->subscription,$now,3).''.$SommeD.' '.$staticmember->LibStatut(0,$adhtype->subscription,0,3).'
\n"; @@ -369,8 +369,8 @@ $Number=array(); $tot=0; $numb=0; -$sql = "SELECT c.cotisation, c.dateadh as dateh"; -$sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."cotisation as c"; +$sql = "SELECT c.subscription, c.dateadh as dateh"; +$sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."subscription as c"; $sql.= " WHERE d.entity IN (".getEntity().")"; $sql.= " AND d.rowid = c.fk_adherent"; if(isset($date_select) && $date_select != '') @@ -386,9 +386,9 @@ if ($result) { $objp = $db->fetch_object($result); $year=dol_print_date($db->jdate($objp->dateh),"%Y"); - $Total[$year]=(isset($Total[$year])?$Total[$year]:0)+$objp->cotisation; + $Total[$year]=(isset($Total[$year])?$Total[$year]:0)+$objp->subscription; $Number[$year]=(isset($Number[$year])?$Number[$year]:0)+1; - $tot+=$objp->cotisation; + $tot+=$objp->subscription; $numb+=1; $i++; } @@ -408,7 +408,7 @@ foreach ($Total as $key=>$value) { $var=!$var; print ""; - print "$key"; + print "$key"; print "".$Number[$key].""; print "".price($value).""; print "".price(price2num($value/$Number[$key],'MT')).""; diff --git a/htdocs/adherents/info.php b/htdocs/adherents/info.php deleted file mode 100644 index 53e9b7ee092..00000000000 --- a/htdocs/adherents/info.php +++ /dev/null @@ -1,77 +0,0 @@ - - * Copyright (C) 2005-2012 Regis Houssin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * 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/adherents/info.php - * \ingroup member - * \brief Page des informations d'un adherent - */ - -require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php'; - -$langs->load("companies"); -$langs->load("bills"); -$langs->load("members"); -$langs->load("users"); - -$id=(GETPOST('id','int') ? GETPOST('id','int') : GETPOST('rowid','int')); - -// Security check -$result=restrictedArea($user,'adherent',$id); - - -/* - * View - */ - -$form = new Form($db); - -$title=$langs->trans("Member") . " - " . $langs->trans("Info"); -$helpurl="EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros"; -llxHeader("",$title,$helpurl); - -$object = new Adherent($db); -$object->fetch($id); -$object->info($id); - -$head = member_prepare_head($object); - -dol_fiche_head($head, 'info', $langs->trans("Member"), 0, 'user'); - - -$linkback = ''.$langs->trans("BackToList").''; - -dol_banner_tab($object, 'rowid', $linkback); - -print '
'; - -print '
'; - -print '
'; -dol_print_object_info($object); - -print '
'; - -dol_fiche_end(); - - -llxFooter(); -$db->close(); diff --git a/htdocs/adherents/list.php b/htdocs/adherents/list.php index 2297b155634..0727002aa59 100644 --- a/htdocs/adherents/list.php +++ b/htdocs/adherents/list.php @@ -129,44 +129,49 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab } } + /* * Actions */ if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction')) { $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - -// Purge search criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +if (empty($reshook)) { - $search=""; - $search_ref=""; - $search_lastname=""; - $search_firstname=""; - $search_login=""; - $search_company=""; - $type=""; - $search_email=""; - $search_address=""; - $search_zip=""; - $search_town=""; - $search_state=""; - $search_country=''; - $search_phone=''; - $search_phone_perso=''; - $search_phone_mobile=''; - $search_morphy=""; - $search_categ=""; - $catid=""; - $sall=""; - $statut=''; - $search_array_options=array(); + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers + { + $search=""; + $search_ref=""; + $search_lastname=""; + $search_firstname=""; + $search_login=""; + $search_company=""; + $type=""; + $search_email=""; + $search_address=""; + $search_zip=""; + $search_town=""; + $search_state=""; + $search_country=''; + $search_phone=''; + $search_phone_perso=''; + $search_phone_mobile=''; + $search_morphy=""; + $search_categ=""; + $catid=""; + $sall=""; + $statut=''; + $search_array_options=array(); + } } @@ -179,15 +184,13 @@ $formother=new FormOther($db); $membertypestatic=new AdherentType($db); $memberstatic=new Adherent($db); -llxHeader('',$langs->trans("Member"),'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'); - $now=dol_now(); $sql = "SELECT d.rowid, d.login, d.lastname, d.firstname, d.societe as company, d.fk_soc,"; $sql.= " d.datefin, d.address, d.zip, d.town, d.state_id, d.country,"; $sql.= " d.email, d.phone, d.phone_perso, d.phone_mobile, d.skype, d.birth, d.public, d.photo,"; $sql.= " d.fk_adherent_type as type_id, d.morphy, d.statut, d.datec as date_creation, d.tms as date_update,"; -$sql.= " t.libelle as type, t.cotisation,"; +$sql.= " t.libelle as type, t.subscription,"; $sql.= " state.code_departement as state_code, state.nom as state_name"; // Add fields for extrafields foreach ($extrafields->attribute_list as $key => $val) $sql.=",ef.".$key.' as options_'.$key; @@ -259,263 +262,510 @@ $sql.= $db->plimit($limit+1, $offset); dol_syslog("get list", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) +if (! $resql) { - $num = $db->num_rows($resql); - $i = 0; + dol_print_error($db); + exit; +} - $titre=$langs->trans("MembersList"); - if (isset($_GET["statut"])) - { - if ($statut == '-1,1') { $titre=$langs->trans("MembersListQualified"); } - if ($statut == '-1') { $titre=$langs->trans("MembersListToValid"); } - if ($statut == '1' && ! $filter) { $titre=$langs->trans("MembersListValid"); } - if ($statut == '1' && $filter=='uptodate') { $titre=$langs->trans("MembersListUpToDate"); } - if ($statut == '1' && $filter=='outofdate') { $titre=$langs->trans("MembersListNotUpToDate"); } - if ($statut == '0') { $titre=$langs->trans("MembersListResiliated"); } - } - elseif ($action == 'search') - { - $titre=$langs->trans("MembersListQualified"); - } +$num = $db->num_rows($resql); - if ($type > 0) - { - $membertype=new AdherentType($db); - $result=$membertype->fetch(GETPOST("type")); - $titre.=" (".$membertype->libelle.")"; - } +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) +{ + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/adherents/card.php?id='.$id); + exit; +} - $param=''; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($statut != "") $param.="&statut=".urlencode($statut); - if ($search_ref) $param.="&search_ref=".urlencode($search_ref); - if ($search_nom) $param.="&search_nom=".urlencode($search_nom); - if ($search_firstname) $param.="&search_firstname=".urlencode($search_firstname); - if ($search_lastname) $param.="&search_lastname=".urlencode($search_lastname); - if ($search_login) $param.="&search_login=".urlencode($search_login); - if ($search_email) $param.="&search_email=".urlencode($search_email); - if ($search_company) $param.="&search_company=".urlencode($search_company); - if ($search_address != '') $param.= "&search_address=".urlencode($search_address); - if ($search_town != '') $param.= "&search_town=".urlencode($search_town); - if ($search_zip != '') $param.= "&search_zip=".urlencode($search_zip); - if ($search_state != '') $param.= "&search_state=".urlencode($search_state); - if ($search_country != '') $param.= "&search_country=".urlencode($search_country); - if ($search_phone != '') $param.= "&search_phone=".urlencode($search_phone); - if ($search_phone_perso != '') $param.= "&search_phone_perso=".urlencode($search_phone_perso); - if ($search_phone_mobile != '') $param.= "&search_phone_mobile=".urlencode($search_phone_mobile); - if ($filter) $param.="&filter=".urlencode($filter); - if ($type > 0) $param.="&type=".urlencode($type); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } +llxHeader('',$langs->trans("Member"),'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'); + +$titre=$langs->trans("MembersList"); +if (isset($_GET["statut"])) +{ + if ($statut == '-1,1') { $titre=$langs->trans("MembersListQualified"); } + if ($statut == '-1') { $titre=$langs->trans("MembersListToValid"); } + if ($statut == '1' && ! $filter) { $titre=$langs->trans("MembersListValid"); } + if ($statut == '1' && $filter=='uptodate') { $titre=$langs->trans("MembersListUpToDate"); } + if ($statut == '1' && $filter=='outofdate') { $titre=$langs->trans("MembersListNotUpToDate"); } + if ($statut == '0') { $titre=$langs->trans("MembersListResiliated"); } +} +elseif ($action == 'search') +{ + $titre=$langs->trans("MembersListQualified"); +} + +if ($type > 0) +{ + $membertype=new AdherentType($db); + $result=$membertype->fetch(GETPOST("type")); + $titre.=" (".$membertype->libelle.")"; +} + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($sall != "") $param.="&sall=".urlencode($sall); +if ($statut != "") $param.="&statut=".urlencode($statut); +if ($search_ref) $param.="&search_ref=".urlencode($search_ref); +if ($search_nom) $param.="&search_nom=".urlencode($search_nom); +if ($search_firstname) $param.="&search_firstname=".urlencode($search_firstname); +if ($search_lastname) $param.="&search_lastname=".urlencode($search_lastname); +if ($search_login) $param.="&search_login=".urlencode($search_login); +if ($search_email) $param.="&search_email=".urlencode($search_email); +if ($search_company) $param.="&search_company=".urlencode($search_company); +if ($search_address != '') $param.= "&search_address=".urlencode($search_address); +if ($search_town != '') $param.= "&search_town=".urlencode($search_town); +if ($search_zip != '') $param.= "&search_zip=".urlencode($search_zip); +if ($search_state != '') $param.= "&search_state=".urlencode($search_state); +if ($search_country != '') $param.= "&search_country=".urlencode($search_country); +if ($search_phone != '') $param.= "&search_phone=".urlencode($search_phone); +if ($search_phone_perso != '') $param.= "&search_phone_perso=".urlencode($search_phone_perso); +if ($search_phone_mobile != '') $param.= "&search_phone_mobile=".urlencode($search_phone_mobile); +if ($filter) $param.="&filter=".urlencode($filter); +if ($type > 0) $param.="&type=".urlencode($type); +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +//$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); + +print ''; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic.png', 0, '', '', $limit); + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . implode(', ',$fieldstosearchall); +} + +// Filter on categories +$moreforfilter=''; +if (! empty($conf->categorie->enabled)) +{ + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('Categories'). ': '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_MEMBER,$search_categ,'search_categ',1); + $moreforfilter.='
'; +} +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook +if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; +else $moreforfilter = $hookmanager->resPrint; +if (! empty($moreforfilter)) +{ + print '
'; + print $moreforfilter; + print '
'; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print ''."\n"; +print ''; +if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) +{ + print ''; +} +if (! empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'],$_SERVER["PHP_SELF"],'d.rowid','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'],$_SERVER["PHP_SELF"],'d.firstname','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.lastname']['checked'])) print_liste_field_titre($arrayfields['d.lastname']['label'],$_SERVER["PHP_SELF"],'d.lastname','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.company']['checked'])) print_liste_field_titre($arrayfields['d.company']['label'],$_SERVER["PHP_SELF"],'d.societe','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.login']['checked'])) print_liste_field_titre($arrayfields['d.login']['label'],$_SERVER["PHP_SELF"],'d.login','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.morphy']['checked'])) print_liste_field_titre($arrayfields['d.morphy']['label'],$_SERVER["PHP_SELF"],'d.morphy','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['t.libelle']['checked'])) print_liste_field_titre($arrayfields['t.libelle']['label'],$_SERVER["PHP_SELF"],'t.libelle','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.address']['checked'])) print_liste_field_titre($arrayfields['d.address']['label'],$_SERVER["PHP_SELF"],'d.address','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.zip']['checked'])) print_liste_field_titre($arrayfields['d.zip']['label'],$_SERVER["PHP_SELF"],'d.zip','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.town']['checked'])) print_liste_field_titre($arrayfields['d.town']['label'],$_SERVER["PHP_SELF"],'d.town','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($langs->trans("StateShort"),$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($langs->trans("Country"),$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['d.phone']['checked'])) print_liste_field_titre($arrayfields['d.phone']['label'],$_SERVER["PHP_SELF"],'d.phone','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.phone_perso']['checked'])) print_liste_field_titre($arrayfields['d.phone_perso']['label'],$_SERVER["PHP_SELF"],'d.phone_perso','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['d.phone_mobile']['label'],$_SERVER["PHP_SELF"],'d.phone_mobile','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.email']['checked'])) print_liste_field_titre($arrayfields['d.email']['label'],$_SERVER["PHP_SELF"],'d.email','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['d.datefin']['checked'])) print_liste_field_titre($arrayfields['d.datefin']['label'],$_SERVER["PHP_SELF"],'d.datefin','',$param,'align="center"',$sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['d.datec']['checked'])) print_liste_field_titre($arrayfields['d.datec']['label'],$_SERVER["PHP_SELF"],"d.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['d.tms']['checked'])) print_liste_field_titre($arrayfields['d.tms']['label'],$_SERVER["PHP_SELF"],"d.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['d.statut']['checked'])) print_liste_field_titre($arrayfields['d.statut']['label'],$_SERVER["PHP_SELF"],"d.statut","",$param,'align="right"',$sortfield,$sortorder); +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); +print "\n"; + +// Line for filters fields +print ''; + +// Line numbering +if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) +{ + print ''; +} + +// Ref +if (! empty($arrayfields['d.ref']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.firstname']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.lastname']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.company']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.login']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.morphy']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['t.libelle']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.address']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.zip']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['d.town']['checked'])) +{ + print ''; +} +// State +if (! empty($arrayfields['state.nom']['checked'])) +{ + print ''; +} +// Country +if (! empty($arrayfields['country.code_iso']['checked'])) +{ + print ''; +} +// Phone pro +if (! empty($arrayfields['d.phone']['checked'])) +{ + print ''; +} +// Phone perso +if (! empty($arrayfields['d.phone_perso']['checked'])) +{ + print ''; +} +// Phone mobile +if (! empty($arrayfields['d.phone_mobile']['checked'])) +{ + print ''; +} +// Email +if (! empty($arrayfields['d.email']['checked'])) +{ + print ''; +} + +if (! empty($arrayfields['d.datefin']['checked'])) +{ + print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Date creation +if (! empty($arrayfields['d.datec']['checked'])) +{ + print ''; +} +// Date modification +if (! empty($arrayfields['d.tms']['checked'])) +{ + print ''; +} +// Status +if (! empty($arrayfields['d.statut']['checked'])) +{ + print ''; +} +// Action column +print ''; + +print "\n"; + +$var=True; +$i = 0; +while ($i < $num && $i < $conf->liste_limit) +{ + $obj = $db->fetch_object($resql); + + $datefin=$db->jdate($obj->datefin); + $memberstatic->id=$obj->rowid; + $memberstatic->ref=$obj->rowid; + $memberstatic->lastname=$obj->lastname; + $memberstatic->firstname=$obj->firstname; + $memberstatic->societe=$obj->company; + $memberstatic->statut=$obj->statut; + $memberstatic->datefin= $datefin; + $memberstatic->socid = $obj->fk_soc; - //$massactionbutton=$form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); - - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic.png', 0, '', '', $limit); - - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . implode(', ',$fieldstosearchall); + if (! empty($obj->fk_soc)) { + $memberstatic->fetch_thirdparty(); + $companyname=$memberstatic->thirdparty->name; + } else { + $companyname=$obj->company; } - // Filter on categories - $moreforfilter=''; - if (! empty($conf->categorie->enabled)) - { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_MEMBER,$search_categ,'search_categ',1); - $moreforfilter.='
'; - } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; - else $moreforfilter = $hookmanager->resPrint; - if (! empty($moreforfilter)) - { - print '
'; - print $moreforfilter; - print '
'; - } - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $var=!$var; + print ""; - print '
'.$langs->trans("NumberingShort").'
 '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $listetype=$membertypestatic->liste_array(); + print $form->selectarray("type", $listetype, $type, 1, 0, 0, '', 0, 32); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + print ''; + print ''; + $liststatus=array( + '-1'=>$langs->trans("Draft"), + '1'=>$langs->trans("Validated"), + '0'=>$langs->trans("Resiliated") + ); + print $form->selectarray('statut', $liststatus, $statut, -2); + print ''; +$searchpitco=$form->showFilterAndCheckAddButtons(0); +print $searchpitco; +print '
'."\n"; - print ''; if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { - print ''; + print ''; } - if (! empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'],$_SERVER["PHP_SELF"],'d.rowid','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'],$_SERVER["PHP_SELF"],'d.firstname','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.lastname']['checked'])) print_liste_field_titre($arrayfields['d.lastname']['label'],$_SERVER["PHP_SELF"],'d.lastname','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.company']['checked'])) print_liste_field_titre($arrayfields['d.company']['label'],$_SERVER["PHP_SELF"],'d.societe','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.login']['checked'])) print_liste_field_titre($arrayfields['d.login']['label'],$_SERVER["PHP_SELF"],'d.login','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.morphy']['checked'])) print_liste_field_titre($arrayfields['d.morphy']['label'],$_SERVER["PHP_SELF"],'d.morphy','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.libelle']['checked'])) print_liste_field_titre($arrayfields['t.libelle']['label'],$_SERVER["PHP_SELF"],'t.libelle','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.address']['checked'])) print_liste_field_titre($arrayfields['d.address']['label'],$_SERVER["PHP_SELF"],'d.address','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.zip']['checked'])) print_liste_field_titre($arrayfields['d.zip']['label'],$_SERVER["PHP_SELF"],'d.zip','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.town']['checked'])) print_liste_field_titre($arrayfields['d.town']['label'],$_SERVER["PHP_SELF"],'d.town','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($langs->trans("StateShort"),$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($langs->trans("Country"),$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['d.phone']['checked'])) print_liste_field_titre($arrayfields['d.phone']['label'],$_SERVER["PHP_SELF"],'d.phone','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.phone_perso']['checked'])) print_liste_field_titre($arrayfields['d.phone_perso']['label'],$_SERVER["PHP_SELF"],'d.phone_perso','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['d.phone_mobile']['label'],$_SERVER["PHP_SELF"],'d.phone_mobile','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.email']['checked'])) print_liste_field_titre($arrayfields['d.email']['label'],$_SERVER["PHP_SELF"],'d.email','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['d.datefin']['checked'])) print_liste_field_titre($arrayfields['d.datefin']['label'],$_SERVER["PHP_SELF"],'d.datefin','',$param,'align="center"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['d.datec']['checked'])) print_liste_field_titre($arrayfields['d.datec']['label'],$_SERVER["PHP_SELF"],"d.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['d.tms']['checked'])) print_liste_field_titre($arrayfields['d.tms']['label'],$_SERVER["PHP_SELF"],"d.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['d.statut']['checked'])) print_liste_field_titre($arrayfields['d.statut']['label'],$_SERVER["PHP_SELF"],"d.statut","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; - // Line for filters fields - print ''; - - // Line numbering - if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) - { - print ''; - } - // Ref if (! empty($arrayfields['d.ref']['checked'])) { - print ''; - } - + print "\n"; + } + // Firstname if (! empty($arrayfields['d.firstname']['checked'])) { - print ''; + print "\n"; } - + // Lastname if (! empty($arrayfields['d.lastname']['checked'])) { - print ''; + print "\n"; } - + // Company if (! empty($arrayfields['d.company']['checked'])) { - print ''; + print "\n"; } - + // Login if (! empty($arrayfields['d.login']['checked'])) { - print ''; + print "\n"; } - - if (! empty($arrayfields['d.morphy']['checked'])) + // Moral/Physique + if (! empty($arrayfields['d.morphy']['checked'])) { - print ''; + print "\n"; } - + // Type label if (! empty($arrayfields['t.libelle']['checked'])) { - print ''; } - - if (! empty($arrayfields['d.address']['checked'])) + // Address + if (! empty($arrayfields['d.address']['checked'])) { - print ''; + print ''; } - - if (! empty($arrayfields['d.zip']['checked'])) + // Zip + if (! empty($arrayfields['d.zip']['checked'])) { - print ''; + print ''; + if (! $i) $totalarray['nbfield']++; } - if (! empty($arrayfields['d.town']['checked'])) + // Town + if (! empty($arrayfields['d.town']['checked'])) { - print ''; + print ''; + if (! $i) $totalarray['nbfield']++; } // State if (! empty($arrayfields['state.nom']['checked'])) { - print ''; + print "\n"; + if (! $i) $totalarray['nbfield']++; } // Country if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; + if (! $i) $totalarray['nbfield']++; } // Phone pro if (! empty($arrayfields['d.phone']['checked'])) { - print ''; + print ''; + if (! $i) $totalarray['nbfield']++; } // Phone perso if (! empty($arrayfields['d.phone_perso']['checked'])) { - print ''; + print ''; + if (! $i) $totalarray['nbfield']++; } // Phone mobile if (! empty($arrayfields['d.phone_mobile']['checked'])) { - print ''; + print ''; + if (! $i) $totalarray['nbfield']++; } - // Email - if (! empty($arrayfields['d.email']['checked'])) + // EMail + if (! empty($arrayfields['d.email']['checked'])) { - print ''; + print "\n"; } - - if (! empty($arrayfields['d.datefin']['checked'])) + // End of subscription date + $datefin=$db->jdate($obj->datefin); + if (! empty($arrayfields['d.datefin']['checked'])) { - print ''; + if ($datefin) + { + print ''; + } + else + { + print ''; + } } // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) @@ -524,315 +774,78 @@ if ($resql) { if (! empty($arrayfields["ef.".$key]['checked'])) { + print 'getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; + if (! $i) $totalarray['nbfield']++; } } } // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation if (! empty($arrayfields['d.datec']['checked'])) { - print ''; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['d.tms']['checked'])) { - print ''; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['d.statut']['checked'])) { - print ''; + if (! $i) $totalarray['nbfield']++; } // Action column - print ''; - - print "\n"; - - $var=True; - while ($i < $num && $i < $conf->liste_limit) + print '"; - - if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) - { - print ''; - } - - // Ref - if (! empty($arrayfields['d.ref']['checked'])) - { - print "\n"; - } - // Firstname - if (! empty($arrayfields['d.firstname']['checked'])) - { - print "\n"; - } - // Lastname - if (! empty($arrayfields['d.lastname']['checked'])) - { - print "\n"; - } - // Company - if (! empty($arrayfields['d.company']['checked'])) - { - print "\n"; - } - // Login - if (! empty($arrayfields['d.login']['checked'])) - { - print "\n"; - } - // Moral/Physique - if (! empty($arrayfields['d.morphy']['checked'])) - { - print "\n"; - } - // Type label - if (! empty($arrayfields['t.libelle']['checked'])) - { - $membertypestatic->id=$obj->type_id; - $membertypestatic->libelle=$obj->type; - print ''; - } - // Address - if (! empty($arrayfields['d.address']['checked'])) - { - print ''; - } - // Zip - if (! empty($arrayfields['d.zip']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Town - if (! empty($arrayfields['d.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // State - if (! empty($arrayfields['state.nom']['checked'])) - { - print "\n"; - if (! $i) $totalarray['nbfield']++; - } - // Country - if (! empty($arrayfields['country.code_iso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone pro - if (! empty($arrayfields['d.phone']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone perso - if (! empty($arrayfields['d.phone_perso']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Phone mobile - if (! empty($arrayfields['d.phone_mobile']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // EMail - if (! empty($arrayfields['d.email']['checked'])) - { - print "\n"; - } - // End of subscription date - $datefin=$db->jdate($obj->datefin); - if (! empty($arrayfields['d.datefin']['checked'])) - { - if ($datefin) - { - print ''; - } - else - { - print ''; - } - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - if (! $i) $totalarray['nbfield']++; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['d.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['d.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['d.statut']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Action column - print '"; - if (! $i) $totalarray['nbfield']++; - - print "\n"; - $i++; + print "rowid."&action=edit&backtopage=1\">".img_edit().""; } - - $db->free($resql); - - $parameters=array('sql' => $sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - print "
'.$langs->trans("NumberingShort").''.($i+1).'
 '; - print ''; - print '"; + print $memberstatic->getNomUrl(1); + print "'; - print '"; + print $obj->firstname; + print "'; - print '"; + print $obj->lastname; + print "'; - print '"; + print $companyname; + print "'; - print '".$obj->login."'; - print '".$memberstatic->getmorphylib($obj->morphy)."'; - $listetype=$membertypestatic->liste_array(); - print $form->selectarray("type", $listetype, $type, 1, 0, 0, '', 0, 32); + $membertypestatic->id=$obj->type_id; + $membertypestatic->libelle=$obj->type; + print ''; + print $membertypestatic->getNomUrl(1,32); print ''; - print ''; + print $obj->address; + print ''; - print ''; + print $obj->zip; + print ''; - print ''; + print $obj->town; + print ''; - print ''; - print '".$obj->state_name."'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; + $tmparray=getCountry($obj->country,'all'); + print $tmparray['label']; print ''; - print ''; + print $obj->phone; + print ''; - print ''; + print $obj->phone_perso; + print ''; - print ''; + print $obj->phone_mobile; + print ''; - print '".dol_print_email($obj->email,0,0,1)."'; - print ''; + print dol_print_date($datefin,'day'); + if ($memberstatic->hasDelay()) { + print " ".img_warning($langs->trans("SubscriptionLate")); + } + print ''; + if ($obj->subscription == 'yes') + { + print $langs->trans("SubscriptionNotReceived"); + if ($obj->statut > 0) print " ".img_warning(); + } + else + { + print ' '; + } + print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); print ''; + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour'); print ''; - $liststatus=array( - '-1'=>$langs->trans("Draft"), - '1'=>$langs->trans("Validated"), - '0'=>$langs->trans("Resiliated") - ); - print $form->selectarray('statut', $liststatus, $statut, -2); + print ''; + print $memberstatic->LibStatut($obj->statut,$obj->subscription,$datefin,5); print ''; - $searchpitco=$form->showFilterAndCheckAddButtons(0); - print $searchpitco; - print '
'; + if ($user->rights->adherent->creer) { - $obj = $db->fetch_object($resql); - - $datefin=$db->jdate($obj->datefin); - $memberstatic->id=$obj->rowid; - $memberstatic->ref=$obj->rowid; - $memberstatic->lastname=$obj->lastname; - $memberstatic->firstname=$obj->firstname; - $memberstatic->societe=$obj->company; - $memberstatic->statut=$obj->statut; - $memberstatic->datefin= $datefin; - $memberstatic->socid = $obj->fk_soc; - - if (! empty($obj->fk_soc)) { - $memberstatic->fetch_thirdparty(); - $companyname=$memberstatic->thirdparty->name; - } else { - $companyname=$obj->company; - } - - $var=!$var; - print "
'.($i+1).'"; - print $memberstatic->getNomUrl(1); - print ""; - print $obj->firstname; - print ""; - print $obj->lastname; - print ""; - print $companyname; - print "".$obj->login."".$memberstatic->getmorphylib($obj->morphy)."'; - print $membertypestatic->getNomUrl(1,32); - print ''; - print $obj->address; - print ''; - print $obj->zip; - print ''; - print $obj->town; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->country,'all'); - print $tmparray['label']; - print ''; - print $obj->phone; - print ''; - print $obj->phone_perso; - print ''; - print $obj->phone_mobile; - print '".dol_print_email($obj->email,0,0,1)."'; - print dol_print_date($datefin,'day'); - if ($memberstatic->hasDelay()) { - print " ".img_warning($langs->trans("SubscriptionLate")); - } - print ''; - if ($obj->cotisation == 'yes') - { - print $langs->trans("SubscriptionNotReceived"); - if ($obj->statut > 0) print " ".img_warning(); - } - else - { - print ' '; - } - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''; - print $memberstatic->LibStatut($obj->statut,$obj->cotisation,$datefin,2); - print ''; - if ($user->rights->adherent->creer) - { - print "rowid."&action=edit&backtopage=1\">".img_edit().""; - } - print ' '; - if ($user->rights->adherent->supprimer && $obj->statut == -1) - { - print "rowid."&action=delete&backtopage=1\">".img_picto($langs->trans("Delete"),'disable.png').""; - } - if ($user->rights->adherent->supprimer && $obj->statut == 1) - { - print "rowid."&action=resign&backtopage=1\">".img_picto($langs->trans("Resiliate"),'disable.png').""; - } - print "
\n"; - print ''; - - if ($num > $limit || $page) print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic.png', 0, '', '', $limit, 1); -} -else -{ - dol_print_error($db); + print ' '; + if ($user->rights->adherent->supprimer && $obj->statut == -1) + { + print "rowid."&action=delete&backtopage=1\">".img_picto($langs->trans("Delete"),'disable.png').""; + } + if ($user->rights->adherent->supprimer && $obj->statut == 1) + { + print "rowid."&action=resign&backtopage=1\">".img_picto($langs->trans("Resiliate"),'disable.png').""; + } + print ""; + if (! $i) $totalarray['nbfield']++; + + print "\n"; + $i++; } +$db->free($resql); + +$parameters=array('sql' => $sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print "\n"; +print ''; + +if ($num > $limit || $page) print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic.png', 0, '', '', $limit, 1); + llxFooter(); - $db->close(); diff --git a/htdocs/adherents/stats/index.html b/htdocs/adherents/stats/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/adherents/card_subscriptions.php b/htdocs/adherents/subscription.php similarity index 94% rename from htdocs/adherents/card_subscriptions.php rename to htdocs/adherents/subscription.php index 838ba49c6a9..e70f737d126 100644 --- a/htdocs/adherents/card_subscriptions.php +++ b/htdocs/adherents/subscription.php @@ -3,7 +3,7 @@ * Copyright (C) 2002-2003 Jean-Louis Bergamo * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2012 Regis Houssin - * Copyright (C) 2015-2016 Alexandre Spangaro + * Copyright (C) 2015-2016 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 @@ -20,7 +20,7 @@ */ /** - * \file htdocs/adherents/card_subscriptions.php + * \file htdocs/adherents/subscription.php * \ingroup member * \brief Onglet d'ajout, edition, suppression des adhesions d'un adherent */ @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; @@ -186,7 +186,7 @@ if ($action == 'setsocid') } } -if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $_POST["cancel"]) +if ($user->rights->adherent->cotisation->creer && $action == 'subscription' && ! $_POST["cancel"]) { $error=0; @@ -196,12 +196,12 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ $result=$adht->fetch($object->typeid); // Subscription informations - $datecotisation=0; + $datesubscription=0; $datesubend=0; $paymentdate=0; if ($_POST["reyear"] && $_POST["remonth"] && $_POST["reday"]) { - $datecotisation=dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); + $datesubscription=dol_mktime(0, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); } if ($_POST["endyear"] && $_POST["endmonth"] && $_POST["endday"]) { @@ -211,7 +211,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ { $paymentdate=dol_mktime(0, 0, 0, $_POST["paymentmonth"], $_POST["paymentday"], $_POST["paymentyear"]); } - $cotisation=$_POST["cotisation"]; // Amount of subscription + $subscription=$_POST["subscription"]; // Amount of subscription $label=$_POST["label"]; // Payment informations @@ -224,7 +224,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ if (empty($option)) $option='none'; // Check parameters - if (! $datecotisation) + if (! $datesubscription) { $error++; $langs->load("errors"); @@ -240,7 +240,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ } if (! $datesubend) { - $datesubend=dol_time_plus_duree(dol_time_plus_duree($datecotisation,$defaultdelay,$defaultdelayunit),-1,'d'); + $datesubend=dol_time_plus_duree(dol_time_plus_duree($datesubscription,$defaultdelay,$defaultdelayunit),-1,'d'); } if (($option == 'bankviainvoice' || $option == 'bankdirect') && ! $paymentdate) { @@ -250,9 +250,9 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ } // Check if a payment is mandatory or not - if (! $error && $adht->cotisation) // Type adherent soumis a cotisation + if (! $error && $adht->subscription) // Member type need subscriptions { - if (! is_numeric($_POST["cotisation"])) + if (! is_numeric($_POST["subscription"])) { // If field is '' or not a numeric value $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Amount")); @@ -263,7 +263,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ { if (! empty($conf->banque->enabled) && $_POST["paymentsave"] != 'none') { - if ($_POST["cotisation"]) + if ($_POST["subscription"]) { if (! $_POST["label"]) $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("Label")); if ($_POST["paymentsave"] != 'invoiceonly' && ! $_POST["operation"]) $errmsg=$langs->trans("ErrorFieldRequired",$langs->transnoentities("PaymentMode")); @@ -278,12 +278,12 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ } } - if (! $error && $action=='cotisation') + if (! $error && $action=='subscription') { $db->begin(); // Create subscription - $crowid=$object->cotisation($datecotisation, $cotisation, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend); + $crowid=$object->subscription($datesubscription, $subscription, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend); if ($crowid <= 0) { $error++; @@ -293,7 +293,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ if (! $error) { - // Insert into bank account directlty (if option choosed for) + link to llx_cotisation if option is 'bankdirect' + // Insert into bank account directlty (if option choosed for) + link to llx_subscription if option is 'bankdirect' if ($option == 'bankdirect' && $accountid) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -303,17 +303,17 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ $dateop=$paymentdate; - $insertid=$acct->addline($dateop, $operation, $label, $cotisation, $num_chq, '', $user, $emetteur_nom, $emetteur_banque); + $insertid=$acct->addline($dateop, $operation, $label, $subscription, $num_chq, '', $user, $emetteur_nom, $emetteur_banque); if ($insertid > 0) { $inserturlid=$acct->add_url_line($insertid, $object->id, DOL_URL_ROOT.'/adherents/card.php?rowid=', $object->getFullname($langs), 'member'); if ($inserturlid > 0) { - // Met a jour la table cotisation - $sql ="UPDATE ".MAIN_DB_PREFIX."cotisation SET fk_bank=".$insertid; + // Update table subscription + $sql ="UPDATE ".MAIN_DB_PREFIX."subscription SET fk_bank=".$insertid; $sql.=" WHERE rowid=".$crowid; - dol_syslog("card_subscriptions::cotisation", LOG_DEBUG); + dol_syslog("subscription::subscription", LOG_DEBUG); $resql = $db->query($sql); if (! $resql) { @@ -381,7 +381,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ } } $invoice->socid=$object->fk_soc; - $invoice->date=$datecotisation; + $invoice->date=$datesubscription; // Possibility to add external linked objects with hooks $invoice->linked_objects['subscription'] = $crowid; @@ -411,7 +411,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ $vattouse=get_default_tva($mysoc, $mysoc, $idprodsubscription); } //print xx".$vattouse." - ".$mysoc." - ".$customer;exit; - $result=$invoice->addline($label,0,1,$vattouse,0,0,$idprodsubscription,0,$datecotisation,$datesubend,0,0,'','TTC',$cotisation,1); + $result=$invoice->addline($label,0,1,$vattouse,0,0,$idprodsubscription,0,$datesubscription,$datesubend,0,0,'','TTC',$subscription,1); if ($result <= 0) { $errmsg=$invoice->error; @@ -438,7 +438,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; - $amounts[$invoice->id] = price2num($cotisation); + $amounts[$invoice->id] = price2num($subscription); $paiement = new Paiement($db); $paiement->datepaye = $paymentdate; $paiement->amounts = $amounts; @@ -474,7 +474,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ if (! $error) { // Update fk_bank into subscription table - $sql = 'UPDATE '.MAIN_DB_PREFIX.'cotisation SET fk_bank='.$bank_line_id; + $sql = 'UPDATE '.MAIN_DB_PREFIX.'subscription SET fk_bank='.$bank_line_id; $sql.= ' WHERE rowid='.$crowid; $result = $db->query($sql); @@ -538,7 +538,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'cotisation' && ! $ } } - $_POST["cotisation"]=''; + $_POST["subscription"]=''; $_POST["accountid"]=''; $_POST["operation"]=''; $_POST["label"]=''; @@ -665,7 +665,7 @@ if ($rowid > 0) } else { - if (! $adht->cotisation) + if (! $adht->subscription) { print $langs->trans("SubscriptionNotRecorded"); if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Affiche picto retard uniquement si non brouillon et non resilie @@ -762,7 +762,7 @@ if ($rowid > 0) * Hotbar */ - // Lien nouvelle cotisation si non brouillon et non resilie + // Button to create a new subscription if member no draft neither resiliated if ($user->rights->adherent->cotisation->creer) { if ($action != 'addsubscription' && $action != 'create_thirdparty') @@ -786,14 +786,14 @@ if ($rowid > 0) if ($action != 'addsubscription' && $action != 'create_thirdparty') { $sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe,"; - $sql.= " c.rowid as crowid, c.cotisation,"; + $sql.= " c.rowid as crowid, c.subscription,"; $sql.= " c.datec,"; $sql.= " c.dateadh as dateh,"; $sql.= " c.datef,"; $sql.= " c.fk_bank,"; $sql.= " b.rowid as bid,"; $sql.= " ba.rowid as baid, ba.label, ba.bank"; - $sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."cotisation as c"; + $sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."subscription as c"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON c.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE d.rowid = c.fk_adherent AND d.rowid=".$rowid; @@ -801,7 +801,7 @@ if ($rowid > 0) $result = $db->query($sql); if ($result) { - $cotisationstatic=new Cotisation($db); + $subscriptionstatic=new Subscription($db); $accountstatic=new Account($db); $num = $db->num_rows($result); @@ -827,13 +827,13 @@ if ($rowid > 0) $objp = $db->fetch_object($result); $var=!$var; print ""; - $cotisationstatic->ref=$objp->crowid; - $cotisationstatic->id=$objp->crowid; - print ''.$cotisationstatic->getNomUrl(1).''; + $subscriptionstatic->ref=$objp->crowid; + $subscriptionstatic->id=$objp->crowid; + print ''.$subscriptionstatic->getNomUrl(1).''; print ''.dol_print_date($db->jdate($objp->datec),'dayhour')."\n"; print ''.dol_print_date($db->jdate($objp->dateh),'day')."\n"; print ''.dol_print_date($db->jdate($objp->datef),'day')."\n"; - print ''.price($objp->cotisation).''; + print ''.price($objp->subscription).''; if (! empty($conf->banque->enabled)) { print ''; @@ -954,9 +954,9 @@ if ($rowid > 0) } - print '
'; + print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -995,7 +995,7 @@ if ($rowid > 0) $datefrom=$object->datevalid; } } - print $form->select_date($datefrom,'','','','',"cotisation",1,1,1); + print $form->select_date($datefrom,'','','','',"subscription",1,1,1); print ""; // Date end subscription @@ -1008,13 +1008,13 @@ if ($rowid > 0) $dateto=-1; // By default, no date is suggested } print ''.$langs->trans("DateEndSubscription").''; - print $form->select_date($dateto,'end','','','',"cotisation",1,0,1); + print $form->select_date($dateto,'end','','','',"subscription",1,0,1); print ""; - if ($adht->cotisation) + if ($adht->subscription) { // Amount - print ''.$langs->trans("Amount").' '.$langs->trans("Currency".$conf->currency).''; + print ''.$langs->trans("Amount").' '.$langs->trans("Currency".$conf->currency).''; // Label print ''.$langs->trans("Label").''; @@ -1109,7 +1109,7 @@ if ($rowid > 0) // Date of payment print ''.$langs->trans("DatePayment").''; - print $form->select_date(isset($paymentdate)?$paymentdate:-1,'payment',0,0,1,'cotisation',1,1,1); + print $form->select_date(isset($paymentdate)?$paymentdate:-1,'payment',0,0,1,'subscription',1,1,1); print "\n"; print ''.$langs->trans('Numero'); diff --git a/htdocs/adherents/fiche_subscription.php b/htdocs/adherents/subscription/card.php similarity index 87% rename from htdocs/adherents/fiche_subscription.php rename to htdocs/adherents/subscription/card.php index a0f9f09ff0b..ce3baee712b 100644 --- a/htdocs/adherents/fiche_subscription.php +++ b/htdocs/adherents/subscription/card.php @@ -16,15 +16,15 @@ */ /** - * \file htdocs/adherents/fiche_subscription.php + * \file htdocs/adherents/subscription/card.php * \ingroup member * \brief Page to add/edit/remove a member subscription */ -require '../main.inc.php'; +require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("companies"); @@ -33,7 +33,7 @@ $langs->load("members"); $langs->load("users"); $adh = new Adherent($db); -$object = new Cotisation($db); +$object = new Subscription($db); $errmsg=''; $action=GETPOST("action",'alpha'); @@ -109,7 +109,7 @@ if ($user->rights->adherent->cotisation->creer && $_REQUEST["action"] == 'update { $db->commit(); - header("Location: fiche_subscription.php?rowid=".$object->id); + header("Location: card.php?rowid=".$object->id); exit; } else @@ -172,28 +172,14 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') { /******************************************** * - * Fiche en mode edition + * Subscription card in edit mode * ********************************************/ $object->fetch($rowid); $result=$adh->fetch($object->fk_adherent); - /* - * Affichage onglets - */ - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/adherents/fiche_subscription.php?rowid='.$object->id; - $head[$h][1] = $langs->trans("SubscriptionCard"); - $head[$h][2] = 'general'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/adherents/info_subscription.php?rowid='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; + $head = subscription_prepare_head($object); print ''; print ''; @@ -206,10 +192,10 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') print "\n"; print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref - print ''; + print ''; print ''; @@ -276,30 +262,16 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') if ($rowid && $action != 'edit') { - /* ************************************************************************** */ - /* */ - /* Mode affichage */ - /* */ - /* ************************************************************************** */ + /******************************************** + * + * Subscription card in view mode + * + ********************************************/ $result=$object->fetch($rowid); $result=$adh->fetch($object->fk_adherent); - /* - * Affichage onglets - */ - $h = 0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/adherents/fiche_subscription.php?rowid='.$object->id; - $head[$h][1] = $langs->trans("SubscriptionCard"); - $head[$h][2] = 'general'; - $h++; - - $head[$h][0] = DOL_URL_ROOT.'/adherents/info_subscription.php?rowid='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; + $head = subscription_prepare_head($object); dol_fiche_head($head, 'general', $langs->trans("Subscription"), '', 'payment'); @@ -317,10 +289,10 @@ if ($rowid && $action != 'edit') print ''; print '
'.$langs->trans("Ref").'
'.$langs->trans("Ref").''; print $form->showrefnav($object, 'rowid', $linkback, 1); print '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref - print ''; + print ''; print ''; diff --git a/htdocs/adherents/subscription/index.html b/htdocs/adherents/subscription/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/adherents/info_subscription.php b/htdocs/adherents/subscription/info.php similarity index 66% rename from htdocs/adherents/info_subscription.php rename to htdocs/adherents/subscription/info.php index f9dc5ff17af..5c5799ec2a5 100644 --- a/htdocs/adherents/info_subscription.php +++ b/htdocs/adherents/subscription/info.php @@ -17,16 +17,16 @@ */ /** - * \file htdocs/adherents/info_subscription.php + * \file htdocs/adherents/subscription/info.php * \ingroup member - * \brief Page with information of subscriptions of a member + * \brief Page with information of subscriptions of a member */ -require '../main.inc.php'; +require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $langs->load("companies"); $langs->load("bills"); @@ -41,37 +41,24 @@ $rowid=isset($_GET["rowid"])?$_GET["rowid"]:$_POST["rowid"]; /* - * Visualisation de la fiche - * + * View */ llxHeader(); $form = new Form($db); -$subscription = new Cotisation($db); -$result=$subscription->fetch($rowid); - -$h = 0; -$head = array(); - -$head[$h][0] = DOL_URL_ROOT.'/adherents/fiche_subscription.php?rowid='.$subscription->id; -$head[$h][1] = $langs->trans("SubscriptionCard"); -$head[$h][2] = 'general'; -$h++; - -$head[$h][0] = DOL_URL_ROOT.'/adherents/info_subscription.php?rowid='.$subscription->id; -$head[$h][1] = $langs->trans("Info"); -$head[$h][2] = 'info'; -$h++; +$object = new Subscription($db); +$result = $object->fetch($rowid); +$head = subscription_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans("Subscription"), '', 'payment'); -$subscription->info($rowid); +$object->info($rowid); print '
'.$langs->trans("Ref").'
'.$langs->trans("Ref").''; print $form->showrefnav($object, 'rowid', $linkback, 1); print '
'; -dol_print_object_info($subscription); +dol_print_object_info($object); print '
'; print '
'; diff --git a/htdocs/adherents/cotisations.php b/htdocs/adherents/subscription/list.php similarity index 92% rename from htdocs/adherents/cotisations.php rename to htdocs/adherents/subscription/list.php index 2e4f4b1994f..6062bb12567 100644 --- a/htdocs/adherents/cotisations.php +++ b/htdocs/adherents/subscription/list.php @@ -18,14 +18,14 @@ */ /** - * \file htdocs/adherents/cotisations.php + * \file htdocs/adherents/subscription/list.php * \ingroup member - * \brief Page de consultation et insertion d'une cotisation + * \brief list of subscription */ -require '../main.inc.php'; +require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("members"); @@ -85,14 +85,15 @@ llxHeader('',$langs->trans("ListOfSubscriptions"),'EN:Module_Foundations|FR:Modu // List of subscriptions $sql = "SELECT d.rowid, d.login, d.firstname, d.lastname, d.societe,"; -$sql.= " c.rowid as crowid, c.cotisation,"; +$sql.= " c.rowid as crowid, c.subscription,"; $sql.= " c.dateadh,"; $sql.= " c.datef,"; $sql.= " c.fk_bank as bank, c.note,"; $sql.= " b.fk_account"; -$sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."cotisation as c"; +$sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."subscription as c"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON c.fk_bank=b.rowid"; $sql.= " WHERE d.rowid = c.fk_adherent"; +$sql.= " AND d.entity IN (".getEntity('adherent', 1).")"; if (isset($date_select) && $date_select != '') { $sql.= " AND c.dateadh LIKE '".$date_select."%'"; @@ -103,10 +104,10 @@ if ($search_ref) else $sql.=" AND 1 = 2"; // Always wrong } if ($search_lastname) $sql.= natural_search(array('d.firstname','d.lastname','d.societe'), $search_lastname); -if ($search_login) $sql.= natural_search('c.cotisation', $search_login); +if ($search_login) $sql.= natural_search('c.subscription', $search_login); if ($search_note) $sql.= natural_search('c.note', $search_note); if ($search_account > 0) $sql.= " AND b.fk_account = ".$search_account; -if ($search_amount) $sql.= natural_search('c.cotisation', $search_amount, 1); +if ($search_amount) $sql.= natural_search('c.subscription', $search_amount, 1); $sql.= $db->order($sortfield,$sortorder); $nbtotalofrecords = 0; @@ -166,7 +167,7 @@ if ($result) } print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"c.dateadh",$param,"",'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateEnd"),$_SERVER["PHP_SELF"],"c.datef",$param,"",'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Amount"),$_SERVER["PHP_SELF"],"c.cotisation",$param,"",'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Amount"),$_SERVER["PHP_SELF"],"c.subscription",$param,"",'align="right"',$sortfield,$sortorder); print_liste_field_titre(''); print "\n"; @@ -211,7 +212,7 @@ if ($result) // Static objects - $cotisation=new Cotisation($db); + $subscription=new Subscription($db); $adherent=new Adherent($db); $accountstatic=new Account($db); @@ -220,10 +221,10 @@ if ($result) while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); - $total+=$objp->cotisation; + $total+=$objp->subscription; - $cotisation->ref=$objp->crowid; - $cotisation->id=$objp->crowid; + $subscription->ref=$objp->crowid; + $subscription->id=$objp->crowid; $adherent->lastname=$objp->lastname; $adherent->firstname=$objp->firstname; @@ -236,7 +237,7 @@ if ($result) print ""; // Ref - print ''.$cotisation->getNomUrl(1).''; + print ''.$subscription->getNomUrl(1).''; // Lastname print ''.$adherent->getNomUrl(1).''; @@ -273,7 +274,7 @@ if ($result) print ''.dol_print_date($db->jdate($objp->datef),'day')."\n"; // Price - print ''.price($objp->cotisation).''; + print ''.price($objp->subscription).''; print ''; diff --git a/htdocs/adherents/type.php b/htdocs/adherents/type.php index dbc700a6778..ccb180a3288 100644 --- a/htdocs/adherents/type.php +++ b/htdocs/adherents/type.php @@ -3,7 +3,7 @@ * Copyright (C) 2003 Jean-Louis Bergamo * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2013 Florian Henry + * Copyright (C) 2013 Florian Henry * Copyright (C) 2015 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify @@ -23,7 +23,7 @@ /** * \file htdocs/adherents/type.php * \ingroup member - * \brief Member's type setup + * \brief Member's type setup */ require '../main.inc.php'; @@ -55,7 +55,7 @@ if (! $sortorder) { $sortorder="DESC"; } if (! $sortfield) { $sortfield="d.lastname"; } $label=GETPOST("libelle","alpha"); -$cotisation=GETPOST("cotisation","int"); +$subscription=GETPOST("subscription","int"); $vote=GETPOST("vote","int"); $comment=GETPOST("comment"); $mail_valid=GETPOST("mail_valid"); @@ -90,11 +90,11 @@ if ($action == 'add' && $user->rights->adherent->configurer) { $object = new AdherentType($db); - $object->libelle = trim($label); - $object->cotisation = trim($cotisation); - $object->note = trim($comment); - $object->mail_valid = trim($mail_valid); - $object->vote = trim($vote); + $object->libelle = trim($label); + $object->subscription = trim($subscription); + $object->note = trim($comment); + $object->mail_valid = trim($mail_valid); + $object->vote = trim($vote); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); @@ -127,12 +127,12 @@ if ($action == 'update' && $user->rights->adherent->configurer) if (! $cancel) { $object = new AdherentType($db); - $object->id = $rowid; - $object->libelle = trim($label); - $object->cotisation = trim($cotisation); - $object->note = trim($comment); - $object->mail_valid = trim($mail_valid); - $object->vote = trim($vote); + $object->id = $rowid; + $object->libelle = trim($label); + $object->subscription = trim($subscription); + $object->note = trim($comment); + $object->mail_valid = trim($mail_valid); + $object->vote = trim($vote); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels,$object); @@ -171,7 +171,7 @@ if (! $rowid && $action != 'create' && $action != 'edit') //dol_fiche_head(''); - $sql = "SELECT d.rowid, d.libelle, d.cotisation, d.vote"; + $sql = "SELECT d.rowid, d.libelle, d.subscription, d.vote"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent_type as d"; $sql.= " WHERE d.entity IN (".getEntity().")"; @@ -199,7 +199,7 @@ if (! $rowid && $action != 'create' && $action != 'edit') print ""; print ''.img_object($langs->trans("ShowType"),'group').' '.$objp->rowid.''; print ''.dol_escape_htmltag($objp->libelle).''; - print ''.yn($objp->cotisation).''; + print ''.yn($objp->subscription).''; print ''.yn($objp->vote).''; if ($user->rights->adherent->configurer) print 'rowid.'">'.img_edit().''; @@ -240,7 +240,7 @@ if ($action == 'create') print ''.$langs->trans("Label").''; print ''.$langs->trans("SubscriptionRequired").''; - print $form->selectyesno("cotisation",1,1); + print $form->selectyesno("subscription",1,1); print ''; print ''.$langs->trans("VoteAllowed").''; @@ -308,7 +308,7 @@ if ($rowid > 0) print ''.$langs->trans("Label").''.dol_escape_htmltag($object->libelle).''; print ''.$langs->trans("SubscriptionRequired").''; - print yn($object->cotisation); + print yn($object->subscription); print ''; print ''.$langs->trans("VoteAllowed").''; @@ -367,7 +367,7 @@ if ($rowid > 0) $sql = "SELECT d.rowid, d.login, d.firstname, d.lastname, d.societe, "; $sql.= " d.datefin,"; $sql.= " d.email, d.fk_adherent_type as type_id, d.morphy, d.statut,"; - $sql.= " t.libelle as type, t.cotisation"; + $sql.= " t.libelle as type, t.subscription"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."adherent_type as t"; $sql.= " WHERE d.fk_adherent_type = t.rowid "; $sql.= " AND d.entity IN (".getEntity().")"; @@ -546,10 +546,10 @@ if ($rowid > 0) // Statut print ''; - print $adh->LibStatut($objp->statut,$objp->cotisation,$datefin,2); + print $adh->LibStatut($objp->statut,$objp->subscription,$datefin,2); print ""; - // Date fin cotisation + // Date end subscription if ($datefin) { print ''; @@ -566,7 +566,7 @@ if ($rowid > 0) else { print ''; - if ($objp->cotisation == 'yes') + if ($objp->subscription == 'yes') { print $langs->trans("SubscriptionNotReceived"); if ($objp->statut > 0) print " ".img_warning(); @@ -638,7 +638,7 @@ if ($rowid > 0) print ''.$langs->trans("Label").''; print ''.$langs->trans("SubscriptionRequired").''; - print $form->selectyesno("cotisation",$object->cotisation,1); + print $form->selectyesno("subscription",$object->subscription,1); print ''; print ''.$langs->trans("VoteAllowed").''; diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php index 76b3b060925..9ea048c27fd 100644 --- a/htdocs/admin/agenda_other.php +++ b/htdocs/admin/agenda_other.php @@ -147,7 +147,7 @@ else if ($action == 'specimen') // For orders // Activate a model else if ($action == 'setmodel') { - print "sssd".$value; + //print "sssd".$value; $ret = addDocumentModel($value, $type, $label, $scandir); } @@ -203,7 +203,6 @@ dol_fiche_head($head, 'other', $langs->trans("Agenda"), 0, 'action'); * Documents models for supplier orders */ -print load_fiche_titre($langs->trans("AgendaModelModule"),'',''); // Define array def of models $def = array(); @@ -230,109 +229,114 @@ else dol_print_error($db); } -print ''."\n"; -print ''."\n"; -print ''."\n"; -print ''."\n"; -print ''."\n"; -print ''."\n"; -print ''; -print ''; -print ''."\n"; - -clearstatcache(); - -$var=true; -foreach ($dirmodels as $reldir) +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { - $dir = dol_buildpath($reldir."core/modules/action/doc/"); - - if (is_dir($dir)) + print load_fiche_titre($langs->trans("AgendaModelModule"),'',''); + + print '
'.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Status").''.$langs->trans("Default").''.$langs->trans("ShortInfo").''.$langs->trans("Preview").'
'."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''."\n"; + print ''; + print ''; + print ''."\n"; + + clearstatcache(); + + $var=true; + foreach ($dirmodels as $reldir) { - $handle=opendir($dir); - if (is_resource($handle)) + $dir = dol_buildpath($reldir."core/modules/action/doc/"); + + if (is_dir($dir)) { - while (($file = readdir($handle))!==false) + $handle=opendir($dir); + if (is_resource($handle)) { - if (preg_match('/\.modules\.php$/i',$file) && preg_match('/^(pdf_|doc_)/',$file)) + while (($file = readdir($handle))!==false) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); - - require_once $dir.'/'.$file; - $module = new $classname($db, new ActionComm($db)); - - $var=!$var; - print "\n"; - print "\n"; - print "\n"; - - // Active - if (in_array($name, $def)) - { - - print '"; - } - else - { - print '"; - } - - // Default - print ''; - - // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); - $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; - $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo,1,1); - print ''; - print ''; - - print "\n"; + if (preg_match('/\.modules\.php$/i',$file) && preg_match('/^(pdf_|doc_)/',$file)) + { + $name = substr($file, 4, dol_strlen($file) -16); + $classname = substr($file, 0, dol_strlen($file) -12); + + require_once $dir.'/'.$file; + $module = new $classname($db, new ActionComm($db)); + + $var=!$var; + print "\n"; + print "\n"; + print "\n"; + + // Active + if (in_array($name, $def)) + { + + print '"; + } + else + { + print '"; + } + + // Default + print ''; + + // Info + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); + $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo,1,1); + print ''; + print ''; + + print "\n"; + } } + closedir($handle); } - closedir($handle); } } + print '
'.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Status").''.$langs->trans("Default").''.$langs->trans("ShortInfo").''.$langs->trans("Preview").'
"; - print (empty($module->name)?$name:$module->name); - print "\n"; - require_once $dir.$file; - $module = new $classname($db,$specimenthirdparty); - if (method_exists($module,'info')) - print $module->info($langs); - else - print $module->description; - print "'."\n"; - if ($conf->global->ACTION_EVENT_ADDON_PDF != "$name") - { - print 'scandir.'&label='.urlencode($module->name).'&type=action">'; - print img_picto($langs->trans("Enabled"),'switch_on'); - print ''; - } - else - { - print img_picto($langs->trans("Enabled"),'switch_on'); - } - print "'."\n"; - print 'scandir.'&label='.urlencode($module->name).'&type=action">'.img_picto($langs->trans("Disabled"),'switch_off').''; - print "'; - if ($conf->global->ACTION_EVENT_ADDON_PDF == "$name") - { - print img_picto($langs->trans("Default"),'on'); - } - else - { - print 'scandir.'&label='.urlencode($module->name).'&type=action"" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').''; - } - print ''; - print $form->textwithpicto('',$htmltooltip,1,0); - print ''; - print ''.img_object($langs->trans("Preview"),'order').''; - print '
"; + print (empty($module->name)?$name:$module->name); + print "\n"; + require_once $dir.$file; + $module = new $classname($db,$specimenthirdparty); + if (method_exists($module,'info')) + print $module->info($langs); + else + print $module->description; + print "'."\n"; + if ($conf->global->ACTION_EVENT_ADDON_PDF != "$name") + { + print 'scandir.'&label='.urlencode($module->name).'&type=action">'; + print img_picto($langs->trans("Enabled"),'switch_on'); + print ''; + } + else + { + print img_picto($langs->trans("Enabled"),'switch_on'); + } + print "'."\n"; + print 'scandir.'&label='.urlencode($module->name).'&type=action">'.img_picto($langs->trans("Disabled"),'switch_off').''; + print "'; + if ($conf->global->ACTION_EVENT_ADDON_PDF == "$name") + { + print img_picto($langs->trans("Default"),'on'); + } + else + { + print 'scandir.'&label='.urlencode($module->name).'&type=action"" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').''; + } + print ''; + print $form->textwithpicto('',$htmltooltip,1,0); + print ''; + print ''.img_object($langs->trans("Preview"),'order').''; + print '

'; } -print '
'; $var=true; diff --git a/htdocs/admin/bank.php b/htdocs/admin/bank.php index 8a5c60c8483..58d97842017 100644 --- a/htdocs/admin/bank.php +++ b/htdocs/admin/bank.php @@ -28,7 +28,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; $langs->load("admin"); $langs->load("companies"); @@ -40,6 +41,10 @@ if (!$user->admin) accessforbidden(); $action = GETPOST('action','alpha'); +$value = GETPOST('value','alpha'); +$label = GETPOST('label','alpha'); +$scandir = GETPOST('scandir','alpha'); +$type = 'bankaccount'; /* @@ -60,14 +65,103 @@ if ($action == 'setbankorder') } } + +if ($action == 'specimen') +{ + $modele=GETPOST('module','alpha'); + + if ($modele == 'sepamandate') + { + $object = new CompanyBankAccount($db); + } + else + { + $object = new Account($db); + } + $object->initAsSpecimen(); + + // Search template files + $file=''; $classname=''; $filefound=0; + $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); + foreach($dirmodels as $reldir) + { + $file=dol_buildpath($reldir."core/modules/bank/doc/pdf_".$modele.".modules.php",0); + if (file_exists($file)) + { + $filefound=1; + $classname = "pdf_".$modele; + break; + } + } + + if ($filefound) + { + require_once $file; + + $module = new $classname($db); + + if ($module->write_file($object,$langs) > 0) + { + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=bank&file=SPECIMEN.pdf"); + return; + } + else + { + setEventMessages($module->error, null, 'errors'); + dol_syslog($module->error, LOG_ERR); + } + } + else + { + setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); + dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); + } +} + +// Activate a model +if ($action == 'set') +{ + $ret = addDocumentModel($value, $type, $label, $scandir); +} + +else if ($action == 'del') +{ + $ret = delDocumentModel($value, $type); + if ($ret > 0) + { + if ($conf->global->BANKADDON_PDF == "$value") dolibarr_del_const($db, 'BANKADDON_PDF',$conf->entity); + } +} +// Set default model +else if ($action == 'setdoc') +{ + if (dolibarr_set_const($db, "BANKADDON_PDF",$value,'chaine',0,'',$conf->entity)) + { + // The constant that was read before the new set + // We therefore requires a variable to have a coherent view + $conf->global->BANKADDON_PDF = $value; + } + + // On active le modele + $ret = delDocumentModel($value, $type); + if ($ret > 0) + { + $ret = addDocumentModel($value, $type, $label, $scandir); + } +} + + + /* * view */ -llxHeader("",$langs->trans("BankSetupModule")); - $form=new Form($db); +$dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); + +llxHeader("",$langs->trans("BankSetupModule")); + $linkback=''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("BankSetupModule"),$linkback,'title_setup'); @@ -79,7 +173,7 @@ $var=true; $var=! $var; //Show bank account order -print load_fiche_titre($langs->trans("BankOrderShow")); +print load_fiche_titre($langs->trans("BankOrderShow"), '', ''); print ''; print ''; @@ -137,6 +231,152 @@ while ($i < $nbofbank) print '
'."\n"; + +print '

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

' . $langs->trans("FeaturesSupported") . ':'; + $htmltooltip .= '
' . $langs->trans("Logo") . ': ' . yn($module->option_logo, 1, 1); + //$htmltooltip .= '
' . $langs->trans("PaymentMode") . ': ' . yn($module->option_modereg, 1, 1); + //$htmltooltip .= '
' . $langs->trans("PaymentConditions") . ': ' . yn($module->option_condreg, 1, 1); + $htmltooltip .= '
' . $langs->trans("MultiLanguage") . ': ' . yn($module->option_multilang, 1, 1); + // $htmltooltip.='
'.$langs->trans("Discounts").': '.yn($module->option_escompte,1,1); + // $htmltooltip.='
'.$langs->trans("CreditNote").': '.yn($module->option_credit_note,1,1); + //$htmltooltip .= '
' . $langs->trans("WatermarkOnDraftOrders") . ': ' . yn($module->option_draft_watermark, 1, 1); + + print ''; + + // Preview + print ''; + + print "\n"; + } + } + } + } + } + } + } +} +//} + + dol_fiche_end(); llxFooter(); diff --git a/htdocs/admin/commande.php b/htdocs/admin/commande.php index 2a1c4a1561d..c2f8cf2d4d6 100644 --- a/htdocs/admin/commande.php +++ b/htdocs/admin/commande.php @@ -273,12 +273,12 @@ else if ($action == 'set_WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER') * View */ +$form=new Form($db); + $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); llxHeader("",$langs->trans("OrdersSetup")); -$form=new Form($db); - $linkback=''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("OrdersSetup"),$linkback,'title_setup'); diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index d0841a06b91..bce8a063ecb 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -43,6 +43,7 @@ if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/acco $langs->load("errors"); $langs->load("admin"); +$langs->load("main"); $langs->load("companies"); $langs->load("resource"); $langs->load("holiday"); @@ -54,7 +55,10 @@ $confirm=GETPOST('confirm','alpha'); $id=GETPOST('id','int'); $rowid=GETPOST('rowid','alpha'); -if (!$user->admin) accessforbidden(); +$allowed=$user->admin; +if ($id == 7 && ! empty($user->rights->accounting->chartofaccount)) $allowed=1; // Tax page allowed to manager of chart account +if ($id == 10 && ! empty($user->rights->accounting->chartofaccount)) $allowed=1; // Vat page allowed to manager of chart account +if (! $allowed) accessforbidden(); $acts[0] = "activate"; $acts[1] = "disable"; @@ -73,6 +77,8 @@ $offset = $listlimit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; +$search_country_id = GETPOST('search_country_id','int'); + // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('admin')); @@ -80,7 +86,7 @@ $hookmanager->initHooks(array('admin')); // Put here declaration of dictionaries properties // Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,33,34,0,6,0,29,0,7,17,24,28,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,25,0,26,0,31,32,0); +$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,17,24,28,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,25,0,26,0,31,32,0); // Name of SQL tables of dictionaries $tabname=array(); @@ -114,7 +120,7 @@ $tabname[27]= MAIN_DB_PREFIX."c_stcomm"; $tabname[28]= MAIN_DB_PREFIX."c_holiday_types"; $tabname[29]= MAIN_DB_PREFIX."c_lead_status"; $tabname[30]= MAIN_DB_PREFIX."c_format_cards"; -$tabname[31]= MAIN_DB_PREFIX."accounting_system"; +//$tabname[31]= MAIN_DB_PREFIX."accounting_system"; $tabname[32]= MAIN_DB_PREFIX."c_accounting_category"; $tabname[33]= MAIN_DB_PREFIX."c_hrm_department"; $tabname[34]= MAIN_DB_PREFIX."c_hrm_function"; @@ -151,7 +157,7 @@ $tablib[27]= "DictionaryProspectStatus"; $tablib[28]= "DictionaryHolidayTypes"; $tablib[29]= "DictionaryOpportunityStatus"; $tablib[30]= "DictionaryFormatCards"; -$tablib[31]= "DictionaryAccountancysystem"; +//$tablib[31]= "DictionaryAccountancysystem"; $tablib[32]= "DictionaryAccountancyCategory"; $tablib[33]= "DictionaryDepartment"; $tablib[34]= "DictionaryFunction"; @@ -169,7 +175,7 @@ $tabsql[8] = "SELECT t.id as rowid, t.code as code, t.libelle, t.fk_country as $tabsql[9] = "SELECT c.code_iso as code, c.label, c.unicode, c.active FROM ".MAIN_DB_PREFIX."c_currencies AS c"; $tabsql[10]= "SELECT t.rowid, t.code, t.taux, t.localtax1_type, t.localtax1, t.localtax2_type, t.localtax2, c.label as country, c.code as country_code, t.fk_pays as country_id, t.recuperableonly, t.note, t.active, t.accountancy_code_sell, t.accountancy_code_buy FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c WHERE t.fk_pays=c.rowid"; $tabsql[11]= "SELECT t.rowid as rowid, t.element, t.source, t.code, t.libelle, t.position, t.active FROM ".MAIN_DB_PREFIX."c_type_contact AS t"; -$tabsql[12]= "SELECT c.rowid as rowid, c.code, c.libelle, c.libelle_facture, c.nbjour, c.fdm, c.decalage, c.active, c.sortorder FROM ".MAIN_DB_PREFIX.'c_payment_term AS c'; +$tabsql[12]= "SELECT c.rowid as rowid, c.code, c.libelle, c.libelle_facture, c.nbjour, c.type_cdr, c.decalage, c.active, c.sortorder FROM ".MAIN_DB_PREFIX.'c_payment_term AS c'; $tabsql[13]= "SELECT c.id as rowid, c.code, c.libelle, c.type, c.active, c.accountancy_code FROM ".MAIN_DB_PREFIX."c_paiement AS c"; $tabsql[14]= "SELECT e.rowid as rowid, e.code as code, e.libelle, e.price, e.organization, e.fk_pays as country_id, c.code as country_code, c.label as country, e.active FROM ".MAIN_DB_PREFIX."c_ecotaxe AS e, ".MAIN_DB_PREFIX."c_country as c WHERE e.fk_pays=c.rowid and c.active=1"; $tabsql[15]= "SELECT rowid as rowid, code, label as libelle, width, height, unit, active FROM ".MAIN_DB_PREFIX."c_paper_format"; @@ -188,7 +194,7 @@ $tabsql[27]= "SELECT id as rowid, code, libelle, active FROM ".MAIN_DB_PREF $tabsql[28]= "SELECT h.rowid as rowid, h.code, h.label, h.affect, h.delay, h.newbymonth, h.fk_country as country_id, c.code as country_code, c.label as country, h.active FROM ".MAIN_DB_PREFIX."c_holiday_types as h LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON h.fk_country=c.rowid"; $tabsql[29]= "SELECT rowid as rowid, code, label, percent, position, active FROM ".MAIN_DB_PREFIX."c_lead_status"; $tabsql[30]= "SELECT rowid, code, name, paper_size, orientation, metric, leftmargin, topmargin, nx, ny, spacex, spacey, width, height, font_size, custom_x, custom_y, active FROM ".MAIN_DB_PREFIX."c_format_cards"; -$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.active FROM ".MAIN_DB_PREFIX."accounting_system as s"; $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"; $tabsql[33]= "SELECT rowid, pos, code, label, active FROM ".MAIN_DB_PREFIX."c_hrm_department"; $tabsql[34]= "SELECT rowid, pos, code, label, c_level, active FROM ".MAIN_DB_PREFIX."c_hrm_function"; @@ -225,7 +231,7 @@ $tabsqlsort[27]="code ASC"; $tabsqlsort[28]="country ASC, code ASC"; $tabsqlsort[29]="position ASC"; $tabsqlsort[30]="code ASC"; -$tabsqlsort[31]="pcg_version ASC"; +//$tabsqlsort[31]="pcg_version ASC"; $tabsqlsort[32]="position ASC"; $tabsqlsort[33]="code ASC"; $tabsqlsort[34]="code ASC"; @@ -243,7 +249,7 @@ $tabfield[8] = "code,libelle,country_id,country".(! empty($conf->global->SOCIETE $tabfield[9] = "code,label,unicode"; $tabfield[10]= "country_id,country,code,taux,recuperableonly,localtax1_type,localtax1,localtax2_type,localtax2,accountancy_code_sell,accountancy_code_buy,note"; $tabfield[11]= "element,source,code,libelle,position"; -$tabfield[12]= "code,libelle,libelle_facture,nbjour,fdm,decalage,sortorder"; +$tabfield[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; $tabfield[13]= "code,libelle,type,accountancy_code"; $tabfield[14]= "code,libelle,price,organization,country_id,country"; $tabfield[15]= "code,libelle,width,height,unit"; @@ -262,7 +268,7 @@ $tabfield[27]= "code,libelle"; $tabfield[28]= "code,label,affect,delay,newbymonth,country_id,country"; $tabfield[29]= "code,label,percent,position"; $tabfield[30]= "code,name,paper_size,orientation,metric,leftmargin,topmargin,nx,ny,spacex,spacey,width,height,font_size,custom_x,custom_y"; -$tabfield[31]= "pcg_version,label"; +//$tabfield[31]= "pcg_version,label"; $tabfield[32]= "code,label,range_account,sens,category_type,formula,position,country_id,country"; $tabfield[33]= "code,label"; $tabfield[34]= "code,label"; @@ -280,7 +286,7 @@ $tabfieldvalue[8] = "code,libelle,country".(! empty($conf->global->SOCIETE_SORT_ $tabfieldvalue[9] = "code,label,unicode"; $tabfieldvalue[10]= "country,code,taux,recuperableonly,localtax1_type,localtax1,localtax2_type,localtax2,accountancy_code_sell,accountancy_code_buy,note"; $tabfieldvalue[11]= "element,source,code,libelle,position"; -$tabfieldvalue[12]= "code,libelle,libelle_facture,nbjour,fdm,decalage,sortorder"; +$tabfieldvalue[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; $tabfieldvalue[13]= "code,libelle,type,accountancy_code"; $tabfieldvalue[14]= "code,libelle,price,organization,country"; $tabfieldvalue[15]= "code,libelle,width,height,unit"; @@ -299,7 +305,7 @@ $tabfieldvalue[27]= "code,libelle"; $tabfieldvalue[28]= "code,label,affect,delay,newbymonth,country"; $tabfieldvalue[29]= "code,label,percent,position"; $tabfieldvalue[30]= "code,name,paper_size,orientation,metric,leftmargin,topmargin,nx,ny,spacex,spacey,width,height,font_size,custom_x,custom_y"; -$tabfieldvalue[31]= "pcg_version,label"; +//$tabfieldvalue[31]= "pcg_version,label"; $tabfieldvalue[32]= "code,label,range_account,sens,category_type,formula,position,country"; $tabfieldvalue[33]= "code,label"; $tabfieldvalue[34]= "code,label"; @@ -317,7 +323,7 @@ $tabfieldinsert[8] = "code,libelle,fk_country".(! empty($conf->global->SOCIETE_S $tabfieldinsert[9] = "code_iso,label,unicode"; $tabfieldinsert[10]= "fk_pays,code,taux,recuperableonly,localtax1_type,localtax1,localtax2_type,localtax2,accountancy_code_sell,accountancy_code_buy,note"; $tabfieldinsert[11]= "element,source,code,libelle,position"; -$tabfieldinsert[12]= "code,libelle,libelle_facture,nbjour,fdm,decalage,sortorder"; +$tabfieldinsert[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; $tabfieldinsert[13]= "code,libelle,type,accountancy_code"; $tabfieldinsert[14]= "code,libelle,price,organization,fk_pays"; $tabfieldinsert[15]= "code,label,width,height,unit"; @@ -336,7 +342,7 @@ $tabfieldinsert[27]= "code,libelle"; $tabfieldinsert[28]= "code,label,affect,delay,newbymonth,fk_country"; $tabfieldinsert[29]= "code,label,percent,position"; $tabfieldinsert[30]= "code,name,paper_size,orientation,metric,leftmargin,topmargin,nx,ny,spacex,spacey,width,height,font_size,custom_x,custom_y"; -$tabfieldinsert[31]= "pcg_version,label"; +//$tabfieldinsert[31]= "pcg_version,label"; $tabfieldinsert[32]= "code,label,range_account,sens,category_type,formula,position,fk_country"; $tabfieldinsert[33]= "code,label"; $tabfieldinsert[34]= "code,label"; @@ -375,7 +381,7 @@ $tabrowid[27]= "id"; $tabrowid[28]= ""; $tabrowid[29]= ""; $tabrowid[30]= ""; -$tabrowid[31]= ""; +//$tabrowid[31]= ""; $tabrowid[32]= ""; $tabrowid[33]= "rowid"; $tabrowid[34]= "rowid"; @@ -412,7 +418,7 @@ $tabcond[27]= ! empty($conf->societe->enabled); $tabcond[28]= ! empty($conf->holiday->enabled); $tabcond[29]= ! empty($conf->projet->enabled); $tabcond[30]= ! empty($conf->label->enabled); -$tabcond[31]= ! empty($conf->accounting->enabled); +//$tabcond[31]= ! empty($conf->accounting->enabled); $tabcond[32]= ! empty($conf->accounting->enabled); $tabcond[33]= ! empty($conf->hrm->enabled); $tabcond[34]= ! empty($conf->hrm->enabled); @@ -430,7 +436,7 @@ $tabhelp[8] = array('code'=>$langs->trans("EnterAnyCode"), 'position'=>$langs-> $tabhelp[9] = array('code'=>$langs->trans("EnterAnyCode"), 'unicode'=>$langs->trans("UnicodeCurrency")); $tabhelp[10] = array('code'=>$langs->trans("EnterAnyCode"), 'taux'=>$langs->trans("SellTaxRate"), 'recuperableonly'=>$langs->trans("RecuperableOnly"), 'localtax1_type'=>$langs->trans("LocalTaxDesc"), 'localtax2_type'=>$langs->trans("LocalTaxDesc")); $tabhelp[11] = array('code'=>$langs->trans("EnterAnyCode"), 'position'=>$langs->trans("PositionIntoComboList")); -$tabhelp[12] = array('code'=>$langs->trans("EnterAnyCode")); +$tabhelp[12] = array('code'=>$langs->trans("EnterAnyCode"), 'type_cdr'=>$langs->trans("TypeCdr")); $tabhelp[13] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[14] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[15] = array('code'=>$langs->trans("EnterAnyCode")); @@ -449,7 +455,7 @@ $tabhelp[27] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[28] = array('affect'=>$langs->trans("FollowedByACounter"),'delay'=>$langs->trans("MinimumNoticePeriod"), 'newbymonth'=>$langs->trans("NbAddedAutomatically")); $tabhelp[29] = array('code'=>$langs->trans("EnterAnyCode"), 'percent'=>$langs->trans("OpportunityPercent"), 'position'=>$langs->trans("PositionIntoComboList")); $tabhelp[30] = array('code'=>$langs->trans("EnterAnyCode"), 'name'=>$langs->trans("LabelName"), 'paper_size'=>$langs->trans("LabelPaperSize")); -$tabhelp[31] = array('pcg_version'=>$langs->trans("EnterAnyCode")); +//$tabhelp[31] = array('pcg_version'=>$langs->trans("EnterAnyCode")); $tabhelp[32] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[33] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[34] = array('code'=>$langs->trans("EnterAnyCode")); @@ -486,7 +492,7 @@ $tabfieldcheck[27] = array(); $tabfieldcheck[28] = array(); $tabfieldcheck[29] = array(); $tabfieldcheck[30] = array(); -$tabfieldcheck[31] = array(); +//$tabfieldcheck[31] = array(); $tabfieldcheck[32] = array(); $tabfieldcheck[33] = array(); $tabfieldcheck[34] = array(); @@ -577,10 +583,20 @@ if ($id == 10) } + +/* + * Actions + */ + +if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x')) +{ + $search_country_id = ''; +} + // Actions add or modify an entry into a dictionary if (GETPOST('actionadd') || GETPOST('actionmodify')) { - $listfield=explode(',',$tabfield[$id]); + $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); $listfieldinsert=explode(',',$tabfieldinsert[$id]); $listfieldmodify=explode(',',$tabfieldinsert[$id]); $listfieldvalue=explode(',',$tabfieldvalue[$id]); @@ -659,8 +675,8 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) } // Clean some parameters - if (isset($_POST["localtax1"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0'; // If empty, we force to 0 - if (isset($_POST["localtax2"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0'; // If empty, we force to 0 + if (! empty($_POST["localtax1_type"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0'; // If empty, we force to 0 + if (! empty($_POST["localtax2_type"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0'; // If empty, we force to 0 if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]=''; // If empty, we force to null if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]=''; // If empty, we force to null if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]=''; // If empty, we force to null @@ -699,14 +715,14 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $i=0; foreach ($listfieldinsert as $f => $value) { - if ($value == 'price' || preg_match('/^amount/i',$value) || preg_match('/^localtax/i',$value) || $value == 'taux') { + if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') { $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); } else if ($value == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } @@ -747,7 +763,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $i = 0; foreach ($listfieldmodify as $field) { - if ($field == 'price' || preg_match('/^amount/i',$field) || preg_match('/^localtax/i',$field) || $field == 'taux') { + if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') { $_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU'); } else if ($field == 'entity') { @@ -755,7 +771,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) } if ($i) $sql.=","; $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; + if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null"; // For vat, we want/accept code = '' else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } @@ -896,7 +912,19 @@ if ($id) $titre.=' - '.$langs->trans($tablib[$id]); $linkback=''.$langs->trans("BackToDictionaryList").''; } -print load_fiche_titre($titre,$linkback,'title_setup'); +$titlepicto='title_setup'; +if ($id == 10 && GETPOST('from') == 'accountancy') +{ + $titre=$langs->trans("MenuVatAccounts"); + $titlepicto='title_accountancy'; +} +if ($id == 7 && GETPOST('from') == 'accountancy') +{ + $titre=$langs->trans("MenuTaxAccounts"); + $titlepicto='title_accountancy'; +} + +print load_fiche_titre($titre,$linkback,$titlepicto); if (empty($id)) { @@ -921,6 +949,13 @@ if ($id) // Complete requete recherche valeurs avec critere de tri $sql=$tabsql[$id]; + if ($search_country_id > 0) + { + if (preg_match('/ WHERE /',$sql)) $sql.= " AND "; + else $sql.=" WHERE "; + $sql.= " c.rowid = ".$search_country_id; + } + if ($sortfield) { // If sort order is "country", we use country_code instead @@ -946,6 +981,8 @@ if ($id) print ''; print ''; + print ''; + print '
' . $langs->trans("Name") . '' . $langs->trans("Description") . '' . $langs->trans("Status") . "' . $langs->trans("Default") . "' . $langs->trans("ShortInfo") . '' . $langs->trans("Preview") . '
'; + print(empty($module->name) ? $name : $module->name); + print "\n"; + if (method_exists($module, 'info')) + print $module->info($langs); + else + print $module->description; + print '' . "\n"; + print ''; + print img_picto($langs->trans("Enabled"), 'switch_on'); + print ''; + print '' . "\n"; + print '' . img_picto($langs->trans("Disabled"), 'switch_off') . ''; + print "'; + if ($conf->global->BANKADDON_PDF == $name) { + print img_picto($langs->trans("Default"), 'on'); + } else { + print '' . img_picto($langs->trans("Disabled"), 'off') . ''; + } + print ''; + print $form->textwithpicto('', $htmltooltip, 1, 0); + print ''; + if ($module->type == 'pdf') { + print '' . img_object($langs->trans("Preview"), 'bill') . ''; + } else { + print img_object($langs->trans("PreviewNotAvailable"), 'generic'); + } + print '
'; // Form to add a new line @@ -970,12 +1007,12 @@ if ($id) if ($fieldlist[$field]=='taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); else $valuetoshow=$langs->trans("Amount"); - $align='right'; + $align='center'; } if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2";} + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $align="center"; } if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3";} + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $align="center"; } if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } if ($fieldlist[$field]=='type') { @@ -995,7 +1032,7 @@ if ($id) } if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } - if ($fieldlist[$field]=='fdm') { $valuetoshow=$langs->trans("AtEndOfMonth"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } @@ -1034,9 +1071,11 @@ if ($id) } if ($id == 4) print ''; - print ''; + print ''; + print ''; print ''; // Line to enter new values @@ -1048,7 +1087,7 @@ if ($id) { foreach ($fieldlist as $key=>$val) { - if (GETPOST($val)) + if (GETPOST($val) != '') $obj->$val=GETPOST($val); } } @@ -1058,7 +1097,7 @@ if ($id) $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error=$hookmanager->error; $errors=$hookmanager->errors; - if ($id == 3) unset($fieldlist[2]); + if ($id == 3) unset($fieldlist[2]); // Remove field ??? if ??? if (empty($reshook)) { @@ -1101,11 +1140,9 @@ if ($id) print ''; // Keep   to have a line with enough height } - print ''; - - // List of available values in database + // List of available record in database dol_syslog("htdocs/admin/dict", LOG_DEBUG); $resql=$db->query($sql); if ($resql) @@ -1113,94 +1150,132 @@ if ($id) $num = $db->num_rows($resql); $i = 0; $var=true; + + $param = '&id='.$id; + if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + $paramwithsearch = $param; + if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; + if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha'); + + // There is several pages + if ($num > $listlimit) + { + print ''; + } + + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield=1; // By defaut + $align="left"; + $sortable=1; + $valuetoshow=''; + /* + $tmparray=getLabelOfField($fieldlist[$field]); + $showfield=$tmp['showfield']; + $valuetoshow=$tmp['valuetoshow']; + $align=$tmp['align']; + $sortable=$tmp['sortable']; + */ + $valuetoshow=ucfirst($fieldlist[$field]); // By defaut + $valuetoshow=$langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } + if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } + if ($fieldlist[$field]=='taux') { + if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); + else $valuetoshow=$langs->trans("Amount"); + $align='center'; + } + if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $align="center"; $sortable=0; } + if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } + if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } + if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + { + $valuetoshow=$langs->trans("Label"); + if ($id != 25) $valuetoshow.="*"; + } + if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } + if ($fieldlist[$field]=='country') { $valuetoshow=$langs->trans("Country"); } + if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } + if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } + if ($fieldlist[$field]=='type_cdr') { $valuetoshow=$langs->trans("AtEndOfMonth"); $align="center"; } + if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } + if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } + if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } + if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } + if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); $sortable=0; } + if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); $sortable=0; } + if ($fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } + if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountsparent"); } + if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } + if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } + if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } + if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } + if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } + if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } + if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } + if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } + if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } + + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder); + } + } + // Favorite - Only activated on country dictionary + if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); + + print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder); + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; + + // Title line with search boxes + print ''; + foreach ($fieldlist as $field => $value) + { + $showfield=1; // By defaut + + if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + + if ($showfield) + { + if ($value == 'country') + { + print ''; + } + else + { + print ''; + } + } + } + if ($id == 4) print ''; + print ''; + print ''; + print ''; + if ($num) { - // There is several pages - if ($num > $listlimit) - { - print ''; - } - - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield=1; // Par defaut - $align="left"; - $sortable=1; - $valuetoshow=''; - /* - $tmparray=getLabelOfField($fieldlist[$field]); - $showfield=$tmp['showfield']; - $valuetoshow=$tmp['valuetoshow']; - $align=$tmp['align']; - $sortable=$tmp['sortable']; - */ - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='source') { $valuetoshow=$langs->trans("Contact"); } - if ($fieldlist[$field]=='price') { $valuetoshow=$langs->trans("PriceUHT"); } - if ($fieldlist[$field]=='taux') { - if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow=$langs->trans("Rate"); - else $valuetoshow=$langs->trans("Amount"); - $align='right'; - } - if ($fieldlist[$field]=='localtax1_type') { $valuetoshow=$langs->trans("UseLocalTax")." 2"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax1') { $valuetoshow=$langs->trans("Rate")." 2"; $sortable=0; } - if ($fieldlist[$field]=='localtax2_type') { $valuetoshow=$langs->trans("UseLocalTax")." 3"; $align="center"; $sortable=0; } - if ($fieldlist[$field]=='localtax2') { $valuetoshow=$langs->trans("Rate")." 3"; $sortable=0; } - if ($fieldlist[$field]=='organization') { $valuetoshow=$langs->trans("Organization"); } - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } - if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - $valuetoshow=$langs->trans("Label"); - if ($id != 25) $valuetoshow.="*"; - } - if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$langs->trans("LabelOnDocuments")."*"; } - if ($fieldlist[$field]=='country') { $valuetoshow=$langs->trans("Country"); } - if ($fieldlist[$field]=='recuperableonly') { $valuetoshow=$langs->trans("NPR"); $align="center"; } - if ($fieldlist[$field]=='nbjour') { $valuetoshow=$langs->trans("NbOfDays"); } - if ($fieldlist[$field]=='fdm') { $valuetoshow=$langs->trans("AtEndOfMonth"); } - if ($fieldlist[$field]=='decalage') { $valuetoshow=$langs->trans("Offset"); } - if ($fieldlist[$field]=='width') { $valuetoshow=$langs->trans("Width"); } - if ($fieldlist[$field]=='height') { $valuetoshow=$langs->trans("Height"); } - if ($fieldlist[$field]=='unit') { $valuetoshow=$langs->trans("MeasuringUnit"); } - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } - if ($fieldlist[$field]=='accountancy_code'){ $valuetoshow=$langs->trans("AccountancyCode"); } - if ($fieldlist[$field]=='accountancy_code_sell'){ $valuetoshow=$langs->trans("AccountancyCodeSell"); $sortable=0; } - if ($fieldlist[$field]=='accountancy_code_buy'){ $valuetoshow=$langs->trans("AccountancyCodeBuy"); $sortable=0; } - if ($fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } - if ($fieldlist[$field]=='account_parent') { $valuetoshow=$langs->trans("Accountsparent"); } - if ($fieldlist[$field]=='pcg_type') { $valuetoshow=$langs->trans("Pcg_type"); } - if ($fieldlist[$field]=='pcg_subtype') { $valuetoshow=$langs->trans("Pcg_subtype"); } - if ($fieldlist[$field]=='sortorder') { $valuetoshow=$langs->trans("SortOrder"); } - if ($fieldlist[$field]=='short_label') { $valuetoshow=$langs->trans("ShortLabel"); } - if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } - if ($fieldlist[$field]=='range_account') { $valuetoshow=$langs->trans("Range"); } - if ($fieldlist[$field]=='sens') { $valuetoshow=$langs->trans("Sens"); } - if ($fieldlist[$field]=='category_type') { $valuetoshow=$langs->trans("Calculated"); } - if ($fieldlist[$field]=='formula') { $valuetoshow=$langs->trans("Formula"); } - - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow,0,$_SERVER["PHP_SELF"],($sortable?$fieldlist[$field]:''),($page?'page='.$page.'&':'').'&id='.$id,"","align=".$align,$sortfield,$sortorder); - } - } - // Favorite - Only activated on country dictionary - if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"),0,$_SERVER["PHP_SELF"],"favorite",($page?'page='.$page.'&':'').'&id='.$id,"",'align="center"',$sortfield,$sortorder); - - print getTitleFieldOfList($langs->trans("Status"),0,$_SERVER["PHP_SELF"],"active",($page?'page='.$page.'&':'').'&id='.$id,"",'align="center"',$sortfield,$sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; - // Lines with values while ($i < $num) { @@ -1223,8 +1298,11 @@ if ($id) if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit'); - print ''; + print ''; } else { @@ -1238,6 +1316,7 @@ if ($id) { foreach ($fieldlist as $field => $value) { + $showfield=1; $align="left"; $valuetoshow=$obj->{$fieldlist[$field]}; @@ -1267,10 +1346,16 @@ if ($id) $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); } } - else if ($fieldlist[$field]=='recuperableonly' || $fieldlist[$field]=='fdm' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + else if ($fieldlist[$field]=='recuperableonly' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { $valuetoshow=yn($valuetoshow); $align="center"; } + else if ($fieldlist[$field]=='type_cdr') { + if(empty($valuetoshow)) $valuetoshow = $langs->trans('None'); + elseif($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); + elseif($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); + $align="center"; + } else if ($fieldlist[$field]=='price' || preg_match('/^amount/i',$fieldlist[$field])) { $valuetoshow=price($valuetoshow); } @@ -1368,9 +1453,11 @@ if ($id) $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); } - + else if ($fieldlist[$field]=='localtax1' || $fieldlist[$field]=='localtax2') { + $align="center"; + } else if ($fieldlist[$field]=='localtax1_type') { - if ($obj->localtax1 != 0) + if ($obj->localtax1 != 0) $valuetoshow=$localtax_typeList[$valuetoshow]; else $valuetoshow = ''; @@ -1383,22 +1470,9 @@ if ($id) $valuetoshow = ''; $align="center"; } - else if ($fieldlist[$field]=='localtax1') { + else if ($fieldlist[$field]=='taux') { $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - if ($obj->localtax1 == 0) - $valuetoshow = ''; - $align="right"; - } - else if ($fieldlist[$field]=='localtax2') { - $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - if ($obj->localtax2 == 0) - $valuetoshow = ''; - $align="right"; - } - else if (in_array($fieldlist[$field],array('taux','localtax1','localtax2'))) - { - $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - $align="right"; + $align="center"; } else if (in_array($fieldlist[$field],array('recuperableonly'))) { @@ -1429,7 +1503,9 @@ if ($id) $canbemodified=$iserasable; if ($obj->code == 'RECEP') $canbemodified=1; - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):'').'&id='.$id.'&'; + $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + if ($param) $url .= '&'.$param; + $url.='&'; // Favorite // Only activated on country dictionary @@ -1458,7 +1534,13 @@ if ($id) else print ''; // Delete link - if ($iserasable) print ''; + if ($iserasable) + { + print ''; + } else print ''; print "\n"; @@ -1578,7 +1660,7 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') } // For state page, we do not show the country input (we link to region, not country) print ''; } elseif ($fieldlist[$field] == 'country_id') @@ -1637,16 +1719,21 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') print 'user'; print ''; } - elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'fdm' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - print ''; } elseif (in_array($fieldlist[$field],array('nbjour','decalage','taux','localtax1','localtax2'))) { $align="left"; - if (in_array($fieldlist[$field],array('taux','localtax1','localtax2'))) $align="right"; // Fields aligned on right + if (in_array($fieldlist[$field],array('taux','localtax1','localtax2'))) $align="center"; // Fields aligned on right print ''; } elseif (in_array($fieldlist[$field], array('libelle_facture'))) { @@ -1699,12 +1786,14 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') print ''; } @@ -1714,10 +1803,10 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') $size=''; $class=''; if ($fieldlist[$field]=='code') $size='size="8" '; if ($fieldlist[$field]=='position') $size='size="4" '; - if ($fieldlist[$field]=='libelle') $size='centpercent'; - if ($fieldlist[$field]=='tracking') $class='centpercent'; + if ($fieldlist[$field]=='libelle') $class='quatrevingtpercent'; + if ($fieldlist[$field]=='tracking') $class='quatrevingtpercent'; if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" '; - print ''; + print ''; print ''; } } diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index 3b7facc9dc8..b9c994fba28 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -262,23 +262,6 @@ if ($action == 'setforcedate') } } -if ($action == 'set_INVOICE_AUTO_FILLJS') -{ - $freetext = GETPOST('INVOICE_AUTO_FILLJS'); // No alpha here, we want exact string - - $res = dolibarr_set_const($db, "INVOICE_AUTO_FILLJS",$freetext,'chaine',0,'',$conf->entity); - - if (! $res > 0) $error++; - - if (! $error) - { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else - { - setEventMessages($langs->trans("Error"), null, 'errors'); - } -} /* @@ -750,20 +733,6 @@ print '\n"; print ''; -// Add js auto fill amount on paiement form -$var=! $var; -print ''; -print ''; -print ''; -print '\n"; -print ''; - $var=! $var; print ''; print ''; diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index 989aa001131..42b5fc4056a 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -104,7 +104,7 @@ if ($action == 'update') else dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', implode(',',colorStringToArray(GETPOST('THEME_ELDY_TEXTLINK'),array())),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", $_POST["main_size_liste_limit"],'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_SIZE_SHORTLISTE_LIMIT", $_POST["main_size_shortliste_limit"],'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", $_POST["main_size_shortliste_limit"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_DISABLE_JAVASCRIPT", $_POST["main_disable_javascript"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_BUTTON_HIDE_UNAUTHORIZED", $_POST["MAIN_BUTTON_HIDE_UNAUTHORIZED"],'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_START_WEEK", $_POST["MAIN_START_WEEK"],'chaine',0,'',$conf->entity); @@ -225,7 +225,7 @@ if ($action == 'edit') // Edit // Max size of short lists on customer card $var=!$var; - print ''; + print ''; print ''; print ''; @@ -408,7 +408,7 @@ else // Show print ""; $var=!$var; - print ''; + print ''; print ''; print ""; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index b507ac89a50..01f2736d718 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -77,153 +77,25 @@ if ($action == 'update' && empty($_POST["cancel"])) dolibarr_set_const($db, "MAIN_MAIL_EMAIL_FROM", GETPOST("MAIN_MAIL_EMAIL_FROM"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_ERRORS_TO", GETPOST("MAIN_MAIL_ERRORS_TO"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_AUTOCOPY_TO", GETPOST("MAIN_MAIL_AUTOCOPY_TO"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, 'MAIN_MAIL_DEFAULT_FROMTYPE',GETPOST('MAIN_MAIL_DEFAULT_FROMTYPE'),'chaine',0,'',$conf->entity); header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; } -/* - * Add file in email form - */ -if (GETPOST('addfile') || GETPOST('addfilehtml')) -{ - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +// Actions to send emails +$id=0; +$actiontypecode=''; +$trigger_name=''; +$paramname='id'; +$mode='emailfortest'; +$trackid=(($action == 'testhtml')?"testhtml":"test"); +include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Set tmp user directory - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir = $vardir.'/temp'; - dol_add_file_process($upload_dir,0,0); +if ($action == 'presend' && GETPOST('trackid') == 'test') $action='test'; +if ($action == 'presend' && GETPOST('trackid') == 'testhtml') $action='testhtml'; - if ($_POST['addfile']) $action='test'; - if ($_POST['addfilehtml']) $action='testhtml'; -} - -/* - * Remove file in email form - */ -if (! empty($_POST['removedfile']) || ! empty($_POST['removedfilehtml'])) -{ - // Set tmp user directory - $vardir=$conf->user->dir_output."/".$user->id; - $upload_dir = $vardir.'/temp'; - - $keytodelete=isset($_POST['removedfile'])?$_POST['removedfile']:$_POST['removedfilehtml']; - $keytodelete--; - - $listofpaths=array(); - $listofnames=array(); - $listofmimes=array(); - if (! empty($_SESSION["listofpaths"])) $listofpaths=explode(';',$_SESSION["listofpaths"]); - if (! empty($_SESSION["listofnames"])) $listofnames=explode(';',$_SESSION["listofnames"]); - if (! empty($_SESSION["listofmimes"])) $listofmimes=explode(';',$_SESSION["listofmimes"]); - - if ($keytodelete >= 0) - { - $pathtodelete=$listofpaths[$keytodelete]; - $filetodelete=$listofnames[$keytodelete]; - $result = dol_delete_file($pathtodelete,1); - if ($result) - { - setEventMessages(array($langs->trans("FileWasRemoved"), $filetodelete), null, 'mesgs'); - - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - $formmail->remove_attached_files($keytodelete); - } - } - if ($_POST['removedfile'] || $action='send') $action='test'; - if ($_POST['removedfilehtml'] || $action='sendhtml') $action='testhtml'; -} - -/* - * Send mail - */ -if (($action == 'send' || $action == 'sendhtml') && ! GETPOST('addfile') && ! GETPOST('addfilehtml') && ! GETPOST('removedfile') && ! GETPOST('cancel')) -{ - $error=0; - - $email_from=''; - if (! empty($_POST["fromname"])) $email_from=$_POST["fromname"].' '; - if (! empty($_POST["frommail"])) $email_from.='<'.$_POST["frommail"].'>'; - - $errors_to = $_POST["errorstomail"]; - $sendto = $_POST["sendto"]; - $sendtocc = $_POST["sendtocc"]; - $sendtoccc = $_POST["sendtoccc"]; - $subject = $_POST['subject']; - $body = $_POST['message']; - $deliveryreceipt= $_POST["deliveryreceipt"]; - $trackid = GETPOST('trackid'); - - //Check if we have to decode HTML - if (!empty($conf->global->FCKEDITOR_ENABLE_MAILING) && dol_textishtml(dol_html_entity_decode($body, ENT_COMPAT | ENT_HTML401))) { - $body=dol_html_entity_decode($body, ENT_COMPAT | ENT_HTML401); - } - - // Create form object - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - $attachedfiles=$formmail->get_attached_files(); - $filepath = $attachedfiles['paths']; - $filename = $attachedfiles['names']; - $mimetype = $attachedfiles['mimes']; - - if (empty($_POST["frommail"])) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MailFrom")), null, 'errors'); - $action='test'; - $error++; - } - if (empty($sendto)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTo")), null, 'errors'); - $action='test'; - $error++; - } - if (! $error) - { - // Is the message in HTML? - $msgishtml=0; // Message is not HTML - if ($action == 'sendhtml') $msgishtml=1; // Force message to HTML - - // Pratique les substitutions sur le sujet et message - $subject=make_substitutions($subject,$substitutionarrayfortest); - $body=make_substitutions($body,$substitutionarrayfortest); - - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile( - $subject, - $sendto, - $email_from, - $body, - $filepath, - $mimetype, - $filename, - $sendtocc, - $sendtoccc, - $deliveryreceipt, - $msgishtml, - $errors_to, - '', - $trackid - ); - - $result=$mailfile->sendfile(); - - if ($result) - { - setEventMessages($langs->trans("MailSuccessfulySent",$mailfile->getValidAddress($email_from,2),$mailfile->getValidAddress($sendto,2)), null, 'mesgs'); - } - else - { - setEventMessages($langs->trans("ResultKo").'
'.$mailfile->error.' '.$result, null, 'errors'); - } - - $action=''; - } -} @@ -521,13 +393,27 @@ if ($action == 'edit') // Separator $var=!$var; print ''; - + // From $var=!$var; print ''; print ''; + // Default from type + $var=!$var; + $liste = array(); + $liste['user'] = $langs->trans('UserEmail'); + $liste['company'] = $langs->trans('CompanyEmail'); + + print ''; + + // Separator + $var=!$var; + print ''; + // From $var=!$var; print ''; @@ -539,13 +425,14 @@ if ($action == 'edit') print ''; print ''; - print '
'; + print ''; print ''; print '
 
'; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone'); + print ''; + $searchpitco=$form->showFilterAndCheckAddButtons(0); + print $searchpitco; + print '
'; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], '&id='.$id, ($num > $listlimit), ''); - print '
 '; - print ' '; + print ''; + print '
'; + print ''; + print '
 '.img_delete().''; + if ($user->admin) print ''.img_delete().''; + //else print ''.img_delete().''; // Some dictionnary can be edited by other profile than admin + print ' 
'; $fieldname='country'; - print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:'')), $fieldname, '', 28, 'maxwidth300'); + print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:'')), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); print ''; - print $form->selectyesno($fieldlist[$field],(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''),1); + elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + if ($fieldlist[$field] == 'type_cdr') print ''; + else print ''; + if ($fieldlist[$field] == 'type_cdr') { + print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + } else { + print $form->selectyesno($fieldlist[$field],(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''),1); + } print ''; - print ''; + print ''; print ''; if (! empty($conf->accounting->enabled)) { - $accountancy_account = (! empty($obj->$fieldlist[$field]) ? $obj->$fieldlist[$field] : 0); - print $formaccountancy->select_account($accountancy_account, $fieldlist[$field], 1, '', 1, 1); + $fieldname = $fieldlist[$field]; + $accountancy_account = (! empty($obj->$fieldname) ? $obj->$fieldname : 0); + print $formaccountancy->select_account($accountancy_account, $fieldlist[$field], 1, '', 1, 1, 'maxwidth200 maxwidthonsmartphone'); } else { - print ''; + $fieldname = $fieldlist[$field]; + print ''; } print '
'; -print $langs->trans("JSOnPaimentBill"); -print ''; -print $form->selectyesno("INVOICE_AUTO_FILLJS",$conf->global->INVOICE_AUTO_FILLJS,1); -print ''; -print ''; -print "
'.$langs->trans("DefaultMaxSizeShortList").'
'.$langs->trans("DefaultMaxSizeShortList").' 
'.$langs->trans("DefaultMaxSizeShortList").'' . $conf->global->MAIN_SIZE_SHORTLISTE_LIMIT . '
'.$langs->trans("DefaultMaxSizeShortList").'' . $conf->global->MAIN_SIZE_SHORTLIST_LIMIT . ' 
 
'.$langs->trans("MAIN_MAIL_EMAIL_FROM",ini_get('sendmail_from')?ini_get('sendmail_from'):$langs->transnoentities("Undefined")).'
'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; + print $form->selectarray('MAIN_MAIL_DEFAULT_FROMTYPE',$liste,$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE,0); + print '
 
'.$langs->trans("MAIN_MAIL_ERRORS_TO").'
'.$langs->trans("MAIN_MAIL_AUTOCOPY_TO").'
'; - print '
'; - print ''; - print '     '; - print ''; - print '
'; + print ''; + + print '
'; + print ''; + print '     '; + print ''; + print '
'; print ''; } @@ -647,7 +534,22 @@ else if (! empty($conf->global->MAIN_MAIL_EMAIL_FROM) && ! isValidEmail($conf->global->MAIN_MAIL_EMAIL_FROM)) print img_warning($langs->trans("ErrorBadEMail")); print ''; - // Errors To + // Default from type + $var=!$var; + print ''.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; + print ''; + if($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE === 'user'){ + print $langs->trans('UserEmail'); + } else { + print $langs->trans('CompanyEmail'); + } + print ''; + + // Separator + $var=!$var; + print ' '; + + // Errors To $var=!$var; print ''.$langs->trans("MAIN_MAIL_ERRORS_TO").''; print ''.$conf->global->MAIN_MAIL_ERRORS_TO; @@ -669,6 +571,7 @@ else } print ''; + print ''; if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) @@ -688,6 +591,7 @@ else print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); } + // Boutons actions print '
'; @@ -747,7 +651,7 @@ else $formmail = new FormMail($db); $formmail->fromname = (isset($_POST['fromname'])?$_POST['fromname']:$conf->global->MAIN_MAIL_EMAIL_FROM); $formmail->frommail = (isset($_POST['frommail'])?$_POST['frommail']:$conf->global->MAIN_MAIL_EMAIL_FROM); - $formmail->trackid='test'; + $formmail->trackid=(($action == 'testhtml')?"testhtml":"test"); $formmail->withfromreadonly=0; $formmail->withsubstit=0; $formmail->withfrom=1; @@ -767,7 +671,7 @@ else // Tableau des substitutions $formmail->substit=$substitutionarrayfortest; // Tableau des parametres complementaires du post - $formmail->param["action"]=($action == 'testhtml'?"sendhtml":"send"); + $formmail->param["action"]="send"; $formmail->param["models"]="body"; $formmail->param["mailid"]=0; $formmail->param["returnurl"]=$_SERVER["PHP_SELF"]; @@ -778,7 +682,7 @@ else $formmail->clear_attached_files(); } - print $formmail->get_form(($action == 'testhtml'?'addfilehtml':'addfile'),($action == 'testhtml'?'removefilehtml':'removefile')); + print $formmail->get_form('addfile','removefile'); print '
'; } diff --git a/htdocs/admin/menus/edit.php b/htdocs/admin/menus/edit.php index afe56aa8dcf..0a2669e960d 100644 --- a/htdocs/admin/menus/edit.php +++ b/htdocs/admin/menus/edit.php @@ -2,6 +2,7 @@ /* Copyright (C) 2007 Patrick Raguin * Copyright (C) 2007-2012 Laurent Destailleur * Copyright (C) 2009-2011 Regis Houssin + * Copyright (C) 2016 Meziane Sof * * 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 @@ -33,10 +34,14 @@ $langs->load('other'); if (! $user->admin) accessforbidden(); -$dirstandard = "/core/menus/standard"; -$dirsmartphone = "/core/menus/smartphone"; - -$dirmenu = array($dirstandard,$dirsmartphone); +$dirstandard = array(); +$dirsmartphone = array(); +$dirmenus=array_merge(array("/core/menus/"),(array) $conf->modules_parts['menus']); +foreach($dirmenus as $dirmenu) +{ + $dirstandard[]=$dirmenu.'standard'; + $dirsmartphone[]=$dirmenu.'smartphone'; +} $action=GETPOST('action'); @@ -244,7 +249,7 @@ if ($action == 'confirm_delete' && $_POST["confirm"] == 'yes') $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE rowid = ".GETPOST('menuId', 'int'); - $db->query($sql); + $result=$db->query($sql); if ($result == 0) { @@ -331,7 +336,7 @@ if ($action == 'create') // Handler print ''.$langs->trans('MenuHandler').''; print ''; - $formadmin->select_menu_families($menu_handler,'menu_handler',$dirmenu); + $formadmin->select_menu_families($menu_handler.(preg_match('/_menu/',$menu_handler)?'':'_menu'),'menu_handler',array_merge($dirstandard,$dirsmartphone)); print ''; print ''.$langs->trans('DetailMenuHandler').''; diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index 113d12570cb..5c1255a1c20 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -75,10 +75,28 @@ if ($search_version) $param.='&search_version='.urlencode($search_version); * Actions */ + +if (GETPOST('buttonreset')) +{ + $search_keyword=''; + $search_status=''; + $search_nature=''; + $search_version=''; +} + if ($action == 'set' && $user->admin) { - $result=activateModule($value); - if ($result) setEventMessages($result, null, 'errors'); + $resarray = activateModule($value); + if (! empty($resarray['errors'])) setEventMessages('', $resarray['errors'], 'errors'); + else + { + //var_dump($resarray);exit; + if ($resarray['nbperms'] > 0) + { + $msg = $langs->trans('ModuleEnabledAdminMustCheckRights'); + setEventMessages($msg, null, 'warnings'); + } + } header("Location: modules.php?mode=".$mode.$param.($page_y?'&page_y='.$page_y:'')); exit; } @@ -91,14 +109,6 @@ if ($action == 'reset' && $user->admin) exit; } -if (GETPOST('buttonreset')) -{ - $search_keyword=''; - $search_status=''; - $search_nature=''; - $search_version=''; -} - /* @@ -353,7 +363,7 @@ if ($mode != 'marketplace') //print '
'; } - print '


'; + print '



'; // Show list of modules @@ -494,8 +504,8 @@ if ($mode != 'marketplace') // Help print ''; $text=''; - if ($objMod->getDescLong()) $text.=$objMod->getDesc().'
'.$objMod->getDescLong().'
'; - else $text.=$objMod->getDesc().'
'; + if ($objMod->getDescLong()) $text.='
'.$objMod->getDesc().'

'.$objMod->getDescLong().'
'; + else $text.='
'.$objMod->getDesc().'

'; $textexternal=''; if ($objMod->isCoreOrExternalModule() == 'external') @@ -510,6 +520,11 @@ if ($mode != 'marketplace') { $text.='
'.$langs->trans("Origin").': '.$langs->trans("Core").'
'; } + $text.='
'.$langs->trans("LastActivationDate").': '; + if (! empty($conf->global->$const_name)) $text.=dol_print_date($objMod->getLastActivationDate(), 'dayhour'); + else $text.=$langs->trans("Disabled"); + $text.='
'; + $text.='
'.$langs->trans("AddRemoveTabs").': '; if (isset($objMod->tabs) && is_array($objMod->tabs) && count($objMod->tabs)) { @@ -605,7 +620,7 @@ if ($mode != 'marketplace') else $text.=$langs->trans("No"); $text.='
'.$langs->trans("AddMenus").': '; - if (isset($objMod->menu) && is_array($objMod->menu) && ! empty($objMod->menu)) + if (isset($objMod->menu) && ! empty($objMod->menu)) // objMod can be an array or just an int 1 { $text.=$langs->trans("Yes"); } @@ -640,22 +655,23 @@ if ($mode != 'marketplace') print $form->textwithpicto('', $text, 1, 'help', 'minheight20'); - // Picto warning - $version=$objMod->getVersion(0); - $versiontrans=$objMod->getVersion(1); - if (preg_match('/development/i', $version)) print img_warning($langs->trans("Development"), 'style="float: right"'); - if (preg_match('/experimental/i', $version)) print img_warning($langs->trans("Experimental"), 'style="float: right"'); - if (preg_match('/deprecated/i', $version)) print img_warning($langs->trans("Deprecated"), 'style="float: right"'); - - // Picto external - if ($textexternal) print img_picto($langs->trans("ExternalModule",$dirofmodule), 'external', 'style="float: right"'); - - print ''; // Version print ''; + + // Picto warning + $version=$objMod->getVersion(0); + $versiontrans=$objMod->getVersion(1); + if (preg_match('/development/i', $version)) print img_warning($langs->trans("Development"), 'style="float: left"'); + if (preg_match('/experimental/i', $version)) print img_warning($langs->trans("Experimental"), 'style="float: left"'); + if (preg_match('/deprecated/i', $version)) print img_warning($langs->trans("Deprecated"), 'style="float: left"'); + + // Picto external + if ($textexternal) print img_picto($langs->trans("ExternalModule",$dirofmodule), 'external', 'style="float: left"'); + print $versiontrans; + print "\n"; // Activate/Disable and Setup (2 columns) diff --git a/htdocs/admin/multicurrency.php b/htdocs/admin/multicurrency.php index 530f3bff5b7..2c9eba444b7 100644 --- a/htdocs/admin/multicurrency.php +++ b/htdocs/admin/multicurrency.php @@ -319,7 +319,7 @@ print ''; print ''.$form->selectCurrency('', 'code').''; print ' '; print ''; -print ' '; +print ' '; print ''; print ''; diff --git a/htdocs/admin/oauth.php b/htdocs/admin/oauth.php index 02a5ffc50e8..34aa49ea237 100644 --- a/htdocs/admin/oauth.php +++ b/htdocs/admin/oauth.php @@ -24,9 +24,8 @@ */ require '../main.inc.php'; - -// required Class require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // Define $urlwithroot @@ -44,224 +43,6 @@ if (!$user->admin) $action = GETPOST('action', 'alpha'); -// Supported OAUTH (a provider is supported when a file xxx_oauthcallback.php is available into htdocs/core/modules/oauth) -$supportedoauth2array=array('OAUTH_GOOGLE_NAME'=>'google'); - -// API access parameters OAUTH -$list = array ( - array( - 'OAUTH_AMAZON_NAME', - 'OAUTH_AMAZON_ID', - 'OAUTH_AMAZON_SECRET', - ), - array( - 'OAUTH_BITBUCKET_NAME', - 'OAUTH_BITBUCKET_ID', - 'OAUTH_BITBUCKET_SECRET', - ), - array( - 'OAUTH_BITLY_NAME', - 'OAUTH_BITLY_ID', - 'OAUTH_BITLY_SECRET', - ), - array( - 'OAUTH_BITRIX24_NAME', - 'OAUTH_BITRIX24_ID', - 'OAUTH_BITRIX24_SECRET', - ), - array( - 'OAUTH_BOX_NAME', - 'OAUTH_BOX_ID', - 'OAUTH_BOX_SECRET', - ), - array( - 'OAUTH_BUFFER_NAME', - 'OAUTH_BUFFER_ID', - 'OAUTH_BUFFER_SECRET', - ), - array( - 'OAUTH_DAILYMOTION_NAME', - 'OAUTH_DAILYMOTION_ID', - 'OAUTH_DAILYMOTION_SECRET', - ), - array( - 'OAUTH_DEVIANTART_NAME', - 'OAUTH_DEVIANTART_ID', - 'OAUTH_DEVIANTART_SECRET', - ), - array( - 'OAUTH_DROPBOX_NAME', - 'OAUTH_DROPBOX_ID', - 'OAUTH_DROPBOX_SECRET', - ), - array( - 'OAUTH_ETSY_NAME', - 'OAUTH_ETSY_ID', - 'OAUTH_ETSY_SECRET', - ), - array( - 'OAUTH_EVEONLINE_NAME', - 'OAUTH_EVEONLINE_ID', - 'OAUTH_EVEONLINE_SECRET', - ), - array( - 'OAUTH_FACEBOOK_NAME', - 'OAUTH_FACEBOOK_ID', - 'OAUTH_FACEBOOK_SECRET', - ), - array( - 'OAUTH_FITBIT_NAME', - 'OAUTH_FITBIT_ID', - 'OAUTH_FITBIT_SECRET', - ), - array( - 'OAUTH_FIVEHUNDREDPX_NAME', - 'OAUTH_FIVEHUNDREDPX_ID', - 'OAUTH_FIVEHUNDREDPX_SECRET', - ), - array( - 'OAUTH_FLICKR_NAME', - 'OAUTH_FLICKR_ID', - 'OAUTH_FLICKR_SECRET', - ), - array( - 'OAUTH_FOURSQUARE_NAME', - 'OAUTH_FOURSQUARE_ID', - 'OAUTH_FOURSQUARE_SECRET', - ), - array( - 'OAUTH_GITHUB_NAME', - 'OAUTH_GITHUB_ID', - 'OAUTH_GITHUB_SECRET', - ), - array( - 'OAUTH_GOOGLE_NAME', - 'OAUTH_GOOGLE_ID', - 'OAUTH_GOOGLE_SECRET', - 'OAUTH_GOOGLE_DESC', - ), - array( - 'OAUTH_HUBIC_NAME', - 'OAUTH_HUBIC_ID', - 'OAUTH_HUBIC_SECRET', - ), - array( - 'OAUTH_INSTAGRAM_NAME', - 'OAUTH_INSTAGRAM_ID', - 'OAUTH_INSTAGRAM_SECRET', - ), - array( - 'OAUTH_LINKEDIN_NAME', - 'OAUTH_LINKEDIN_ID', - 'OAUTH_LINKEDIN_SECRET', - ), - array( - 'OAUTH_MAILCHIMP_NAME', - 'OAUTH_MAILCHIMP_ID', - 'OAUTH_MAILCHIMP_SECRET', - ), - array( - 'OAUTH_MICROSOFT_NAME', - 'OAUTH_MICROSOFT_ID', - 'OAUTH_MICROSOFT_SECRET', - ), - array( - 'OAUTH_NEST_NAME', - 'OAUTH_NEST_ID', - 'OAUTH_NEST_SECRET', - ), - array( - 'OAUTH_NETATMO_NAME', - 'OAUTH_NETATMO_ID', - 'OAUTH_NETATMO_SECRET', - ), - array( - 'OAUTH_PARROTFLOWERPOWER_NAME', - 'OAUTH_PARROTFLOWERPOWER_ID', - 'OAUTH_PARROTFLOWERPOWER_SECRET', - ), - array( - 'OAUTH_PAYPAL_NAME', - 'OAUTH_PAYPAL_ID', - 'OAUTH_PAYPAL_SECRET', - ), - array( - 'OAUTH_POCKET_NAME', - 'OAUTH_POCKET_ID', - 'OAUTH_POCKET_SECRET', - ), - array( - 'OAUTH_QUICKBOOKS_NAME', - 'OAUTH_QUICKBOOKS_ID', - 'OAUTH_QUICKBOOKS_SECRET', - ), - array( - 'OAUTH_REDDIT_NAME', - 'OAUTH_REDDIT_ID', - 'OAUTH_REDDIT_SECRET', - ), - array( - 'OAUTH_REDMINE_NAME', - 'OAUTH_REDMINE_ID', - 'OAUTH_REDMINE_SECRET', - ), - array( - 'OAUTH_RUNKEEPER_NAME', - 'OAUTH_RUNKEEPER_ID', - 'OAUTH_RUNKEEPER_SECRET', - ), - array( - 'OAUTH_SCOOPIT_NAME', - 'OAUTH_SCOOPIT_ID', - 'OAUTH_SCOOPIT_SECRET', - ), - array( - 'OAUTH_SOUNDCLOUD_NAME', - 'OAUTH_SOUNDCLOUD_ID', - 'OAUTH_SOUNDCLOUD_SECRET', - ), - array( - 'OAUTH_SPOTIFY_NAME', - 'OAUTH_SPOTIFY_ID', - 'OAUTH_SPOTIFY_SECRET', - ), - array( - 'OAUTH_STRAVA_NAME', - 'OAUTH_STRAVA_ID', - 'OAUTH_STRAVA_SECRET', - ), - array( - 'OAUTH_TUMBLR_NAME', - 'OAUTH_TUMBLR_ID', - 'OAUTH_TUMBLR_SECRET', - ), - array( - 'OAUTH_TWITTER_NAME', - 'OAUTH_TWITTER_ID', - 'OAUTH_TWITTER_SECRET', - ), - array( - 'OAUTH_USTREAM_NAME', - 'OAUTH_USTREAM_ID', - 'OAUTH_USTREAM_SECRET', - ), - array( - 'OAUTH_VIMEO_NAME', - 'OAUTH_VIMEO_ID', - 'OAUTH_VIMEO_SECRET', - ), - array( - 'OAUTH_YAHOO_NAME', - 'OAUTH_YAHOO_ID', - 'OAUTH_YAHOO_SECRET', - ), - array( - 'OAUTH_YAMMER_NAME', - 'OAUTH_YAMMER_ID', - 'OAUTH_YAMMER_SECRET', - ), -); - /* * Actions @@ -303,10 +84,9 @@ print '
'; print ''; print ''; -/* - * Parameters - */ -dol_fiche_head(array(), '', '', 0, 'technic'); +$head = oauthadmin_prepare_head(); + +dol_fiche_head($head, 'services', '', 0, 'technic'); print $langs->trans("ListOfSupportedOauthProviders").'

'; @@ -314,14 +94,17 @@ print $langs->trans("ListOfSupportedOauthProviders").'

'; print ''; $var = true; +$i=0; foreach ($list as $key) { $supported=0; if (in_array($key[0], array_keys($supportedoauth2array))) $supported=1; if (! $supported) continue; // show only supported - - print ''; + + $i++; + + print ''; // Api Name $label = $langs->trans($key[0]); print ''; diff --git a/htdocs/admin/oauthlogintokens.php b/htdocs/admin/oauthlogintokens.php new file mode 100644 index 00000000000..b41ae78d4c7 --- /dev/null +++ b/htdocs/admin/oauthlogintokens.php @@ -0,0 +1,275 @@ + + * Copyright (C) 2014-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 + * 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/admin/oauthlogintoken.php + * \ingroup oauth + * \brief Setup page to configure oauth access to login information + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; +use OAuth\Common\Storage\DoliStorage; + +$langs->load("admin"); +$langs->load("printing"); +$langs->load("oauth"); + +if (! $user->admin) accessforbidden(); + +$action = GETPOST('action','alpha'); +$mode = GETPOST('mode','alpha'); +$value = GETPOST('value','alpha'); +$varname = GETPOST('varname', 'alpha'); +$driver = GETPOST('driver', 'alpha'); + +if (! empty($driver)) $langs->load($driver); + +if (!$mode) $mode='setup'; + + +/* + * Action + */ + +/*if (($mode == 'test' || $mode == 'setup') && empty($driver)) +{ + setEventMessages($langs->trans('PleaseSelectaDriverfromList'), null); + header("Location: ".$_SERVER['PHP_SELF'].'?mode=config'); + exit; +}*/ + +if ($action == 'setconst' && $user->admin) +{ + $error=0; + $db->begin(); + foreach ($_POST['setupdriver'] as $setupconst) { + //print '
'.print_r($setupconst, true).'
'; + $result=dolibarr_set_const($db, $setupconst['varname'],$setupconst['value'],'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + } + + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null); + } + else + { + $db->rollback(); + dol_print_error($db); + } + $action=''; +} + +if ($action == 'setvalue' && $user->admin) +{ + $db->begin(); + + $result=dolibarr_set_const($db, $varname, $value,'chaine',0,'',$conf->entity); + if (! $result > 0) $error++; + + if (! $error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null); + } + else + { + $db->rollback(); + dol_print_error($db); + } + $action = ''; +} + + +/* + * View + */ + +$form = new Form($db); + +llxHeader('',$langs->trans("PrintingSetup")); + +$linkback=''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans('ConfigOAuth'),$linkback,'title_setup'); + +$head=oauthadmin_prepare_head($mode); + +dol_fiche_head($head, 'tokengeneration', '', 0, 'technic'); + + +if ($mode == 'setup' && $user->admin) +{ + + print $langs->trans("OAuthSetupForLogin")."

\n"; + + foreach($list as $key) + { + $supported=0; + if (in_array($key[0], array_keys($supportedoauth2array))) $supported=1; + if (! $supported) continue; // show only supported + + print ''; + print ''; + print ''; + + + print '
'.$label.'
'."\n"; + $var=true; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $submit_enabled=0; + + print ''; + print ''.$langs->trans($key['varname']).''; + print ''; + print ''; + print ''."\n"; + + // Show value of token + if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') + { + // Token + print ''; + print ''; + print ''; + print ''; + print ''."\n"; + } + + print '
'.$langs->trans("Parameters").''.$langs->trans("Value").' 
'.$langs->trans($key['info']).''; + if ($key['varname'] == 'PRINTGCP_TOKEN_ACCESS') + { + // Delete remote tokens + if (! empty($key['delete'])) print ''.$langs->trans('DeleteAccess').'

'; + // Request remote token + print ''.$langs->trans('RequestAccess').'

'; + // Check remote access + print $langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME_GOOGLE).': https://security.google.com/settings/security/permissions'; + } + print '
'.$langs->trans("Token").''; + // Dolibarr storage + $storage = new DoliStorage($db, $conf); + try + { + $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME_GOOGLE); + } + catch(Exception $e) + { + // Return an error if token not found + } + if (is_object($tokenobj)) + { + //var_dump($tokenobj); + print $tokenobj->getAccessToken().'
'; + //print 'Refresh: '.$tokenobj->getRefreshToken().'
'; + //print 'EndOfLife: '.$tokenobj->getEndOfLife().'
'; + //var_dump($tokenobj->getExtraParams()); + /*print '
Extra:
';*/ + } + print '
'; + print '
'; + + if (! empty($driver)) + { + if ($submit_enabled) { + print '
'; + } + } + + print '
'; + } + +} + +if ($mode == 'test' && $user->admin) +{ + print $langs->trans('PrintTestDesc'.$driver)."

\n"; + + print ''; + if (! empty($driver)) + { + require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php'; + $classname = 'printing_'.$driver; + $langs->load($driver); + $printer = new $classname($db); + //print '
'.print_r($printer, true).'
'; + if (count($printer->getlist_available_printers())) { + if ($printer->listAvailablePrinters()==0) { + print $printer->resprint; + } else { + setEventMessages($printer->error, $printer->errors, 'errors'); + } + } + else { + print $langs->trans('PleaseConfigureDriverfromList'); + } + + } + + print '
'; + +} + +if ($mode == 'userconf' && $user->admin) +{ + print $langs->trans('PrintUserConfDesc'.$driver)."

\n"; + + print ''; + $var=true; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid'; + $resql = $db->query($sql); + while ($row=$db->fetch_array($resql)) { + $var=!$var; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + } + print '
'.$langs->trans("User").''.$langs->trans("PrintModule").''.$langs->trans("PrintDriver").''.$langs->trans("Printer").''.$langs->trans("PrinterLocation").''.$langs->trans("PrinterId").''.$langs->trans("NumberOfCopy").''.$langs->trans("Delete").'
'.$row['login'].''.$row['module'].''.$row['driver'].''.$row['printer_name'].''.$row['printer_location'].''.$row['printer_id'].''.$row['copy'].''.img_picto($langs->trans("Delete"), 'delete').'
'; +} + +dol_fiche_end(); + +llxFooter(); + +$db->close(); diff --git a/htdocs/admin/payment.php b/htdocs/admin/payment.php index 8ce904aad7c..93f7c301519 100644 --- a/htdocs/admin/payment.php +++ b/htdocs/admin/payment.php @@ -69,7 +69,7 @@ if ($action == 'setmod') dolibarr_set_const($db, "PAYMENT_ADDON",$value,'chaine',0,'',$conf->entity); } -if ($action == 'set_FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS') +if ($action == 'setparams') { $freetext = GETPOST('FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS'); // No alpha here, we want exact string @@ -77,16 +77,31 @@ if ($action == 'set_FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS') if (! $res > 0) $error++; - if (! $error) - { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } - else + if ($error) { setEventMessages($langs->trans("Error"), null, 'errors'); } + + /* + $freetext = GETPOST('INVOICE_AUTO_FILLJS'); // No alpha here, we want exact string + + $res = dolibarr_set_const($db, "INVOICE_AUTO_FILLJS",$freetext,'chaine',0,'',$conf->entity); + + if (! $res > 0) $error++; + + if ($error) + { + setEventMessages($langs->trans("Error"), null, 'errors'); + }*/ + + if (! $error) + { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + } + /* * View */ @@ -235,6 +250,10 @@ print "
"; print load_fiche_titre($langs->trans("OtherOptions"),'',''); +print '
'; +print ''; +print ''; + print ''; print ''; print ''; @@ -244,20 +263,32 @@ print "\n"; // Allow payments on different thirdparties bills but same parent company $var=! $var; -print ''; -print ''; -print ''; print '\n"; -print ''; + +// Add js auto fill amount on paiement form +/* always on now +$var=! $var; +print '\n"; +*/ print '
'.$langs->trans("Parameter").'
'; print $langs->trans("PaymentOnDifferentThirdBills"); print ''; print $form->selectyesno("FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS",$conf->global->FACTURE_PAYMENTS_ON_DIFFERENT_THIRDPARTIES_BILLS,1); print ''; -print ''; print "
'; +print $langs->trans("JSOnPaimentBill"); +print ''; +print $form->selectyesno("INVOICE_AUTO_FILLJS",$conf->global->INVOICE_AUTO_FILLJS,1); +print ''; +print "
'; +print '
'; +print ''; +print '
'; + +print ''; + dol_fiche_end(); diff --git a/htdocs/admin/prelevement.php b/htdocs/admin/prelevement.php index 0e82681c686..6d5c915dae2 100644 --- a/htdocs/admin/prelevement.php +++ b/htdocs/admin/prelevement.php @@ -36,6 +36,7 @@ $langs->load("withdrawals"); if (!$user->admin) accessforbidden(); $action = GETPOST('action','alpha'); +$type = 'paymentorder'; /* @@ -110,6 +111,71 @@ if ($action == "deletenotif") exit; } +/* +if ($action == 'specimen') +{ + $modele=GETPOST('module','alpha'); + + $commande = new Commande($db); + $commande->initAsSpecimen(); + + // Search template files + $file=''; $classname=''; $filefound=0; + $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); + foreach($dirmodels as $reldir) + { + $file=dol_buildpath($reldir."core/modules/paymentorders/doc/pdf_".$modele.".modules.php",0); + if (file_exists($file)) + { + $filefound=1; + $classname = "pdf_".$modele; + break; + } + } + + if ($filefound) + { + require_once $file; + + $module = new $classname($db); + + if ($module->write_file($commande,$langs) > 0) + { + header("Location: ".DOL_URL_ROOT."/document.php?modulepart=paymentorders&file=SPECIMEN.pdf"); + return; + } + else + { + setEventMessages($module->error, null, 'errors'); + dol_syslog($module->error, LOG_ERR); + } + } + else + { + setEventMessages($langs->trans("ErrorModuleNotFound"), null, 'errors'); + dol_syslog($langs->trans("ErrorModuleNotFound"), LOG_ERR); + } +} + +// Set default model +else if ($action == 'setdoc') +{ + if (dolibarr_set_const($db, "PAYMENTORDER_ADDON_PDF",$value,'chaine',0,'',$conf->entity)) + { + // The constant that was read before the new set + // We therefore requires a variable to have a coherent view + $conf->global->PAYMENTORDER_ADDON_PDF = $value; + } + + // On active le modele + $ret = delDocumentModel($value, $type); + if ($ret > 0) + { + $ret = addDocumentModel($value, $type, $label, $scandir); + } +} +*/ + /* * View @@ -117,6 +183,8 @@ if ($action == "deletenotif") $form=new Form($db); +$dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); + llxHeader('',$langs->trans("WithdrawalsSetup")); $linkback=''.$langs->trans("BackToModuleList").''; @@ -128,6 +196,7 @@ print '
'; print ''; print ''; + print ''; print ''; print ''; @@ -159,6 +228,172 @@ print '
entity; +$resql=$db->query($sql); +if ($resql) +{ + $i = 0; + $num_rows=$db->num_rows($resql); + while ($i < $num_rows) + { + $array = $db->fetch_array($resql); + array_push($def, $array[0]); + $i++; + } +} +else +{ + dol_print_error($db); +} + + +print "
'.$langs->trans("Parameter").''.$langs->trans("Value").'
\n"; +print "\n"; +print ''; +print ''; +print '\n"; +print '\n"; +print ''; +print ''; +print "\n"; + +clearstatcache(); + +$var=true; +foreach ($dirmodels as $reldir) +{ + foreach (array('','/doc') as $valdir) + { + $dir = dol_buildpath($reldir."core/modules/paymentorders".$valdir); + + if (is_dir($dir)) + { + $handle=opendir($dir); + if (is_resource($handle)) + { + while (($file = readdir($handle))!==false) + { + $filelist[]=$file; + } + closedir($handle); + arsort($filelist); + + foreach($filelist as $file) + { + if (preg_match('/\.modules\.php$/i',$file) && preg_match('/^(pdf_|doc_)/',$file)) + { + + if (file_exists($dir.'/'.$file)) + { + $name = substr($file, 4, dol_strlen($file) -16); + $classname = substr($file, 0, dol_strlen($file) -12); + + require_once $dir.'/'.$file; + $module = new $classname($db); + + $modulequalified=1; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0; + + if ($modulequalified) + { + $var = !$var; + print ''; + + // Active + if (in_array($name, $def)) + { + print ''; + } + else + { + print '"; + } + + // Default + print ''; + + // Info + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip.='
'.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); + if ($module->type == 'pdf') + { + $htmltooltip.='
'.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + } + $htmltooltip.='

'.$langs->trans("FeaturesSupported").':'; + $htmltooltip.='
'.$langs->trans("Logo").': '.yn($module->option_logo,1,1); + $htmltooltip.='
'.$langs->trans("PaymentMode").': '.yn($module->option_modereg,1,1); + $htmltooltip.='
'.$langs->trans("PaymentConditions").': '.yn($module->option_condreg,1,1); + $htmltooltip.='
'.$langs->trans("MultiLanguage").': '.yn($module->option_multilang,1,1); + //$htmltooltip.='
'.$langs->trans("Discounts").': '.yn($module->option_escompte,1,1); + //$htmltooltip.='
'.$langs->trans("CreditNote").': '.yn($module->option_credit_note,1,1); + $htmltooltip.='
'.$langs->trans("WatermarkOnDraftOrders").': '.yn($module->option_draft_watermark,1,1); + + + print ''; + + // Preview + print ''; + + print "\n"; + } + } + } + } + } + } + } +} + +*/ + + dol_fiche_end(); print '
'; diff --git a/htdocs/admin/resource.php b/htdocs/admin/resource.php new file mode 100644 index 00000000000..d8fdddd2bb5 --- /dev/null +++ b/htdocs/admin/resource.php @@ -0,0 +1,144 @@ + + * + * 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/admin/resource.php + * \ingroup resource + * \brief Setup page to configure resource module + */ + +require '../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/resource.lib.php'; +if (! empty($conf->resouce->enabled)) require_once DOL_DOCUMENT_ROOT . '/resource/class/html.formresource.class.php'; + +$langs->load("admin"); +$langs->load("resource"); + +// Security check +if (!$user->admin) + accessforbidden(); + +$action = GETPOST('action', 'alpha'); + + +/* + * Actions + */ + +if ($action == 'updateoptions') +{ + if (GETPOST('activate_RESOURCE_USE_SEARCH_TO_SELECT')) + { + if (dolibarr_set_const($db, "RESOURCE_USE_SEARCH_TO_SELECT", GETPOST('activate_RESOURCE_USE_SEARCH_TO_SELECT'), 'chaine', 0, '', $conf->entity)) + { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'errors'); + } + } +} + +/* + * View + */ + +llxHeader('',$langs->trans('ResourceSetup')); + +$form = new Form($db); + +$linkback=''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans('ResourceSetup'),$linkback,'title_setup'); + +$head=resource_admin_prepare_head(); + +dol_fiche_head($head, 'general', $langs->trans("ResourceSingular"), 0, 'action'); + +print ''; +print ''; +print ''; + +$var=true; +print '
'.$langs->trans("Name").''.$langs->trans("Description").''.$langs->trans("Status")."'.$langs->trans("Default")."'.$langs->trans("ShortInfo").''.$langs->trans("Preview").'
'; + print (empty($module->name)?$name:$module->name); + print "\n"; + if (method_exists($module,'info')) print $module->info($langs); + else print $module->description; + print ''."\n"; + print ''; + print img_picto($langs->trans("Enabled"),'switch_on'); + print ''; + print ''."\n"; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"),'switch_off').''; + print "'; + if ($conf->global->PAYMENTORDER_ADDON_PDF == $name) + { + print img_picto($langs->trans("Default"),'on'); + } + else + { + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"),'off').''; + } + print ''; + print $form->textwithpicto('',$htmltooltip,1,0); + print ''; + if ($module->type == 'pdf') + { + print ''.img_object($langs->trans("Preview"),'bill').''; + } + else + { + print img_object($langs->trans("PreviewNotAvailable"),'generic'); + } + print '
'; +print ''; +print ''."\n"; +print ''."\n"; +print ''; + + +// Utilisation formulaire Ajax sur choix produit +$var=!$var; +print ''; +print ''; +if (empty($conf->use_javascript_ajax)) +{ + print ''; +} +else +{ + print ''; + print ''; +} +print ''; + +$var=!$var; +print ''; +print ''; +print ''; +print ''; +print ''; + +$var=!$var; +print ''; +print ''; +print ''; +print ''; +print ''; + +print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'.$langs->trans("UseSearchToSelectResource").''; + print $langs->trans("NotAvailableWhenAjaxDisabled"); + print ''; + $arrval=array( + '0'=>$langs->trans("No"), + '1'=>$langs->trans("Yes").' ('.$langs->trans("NumberOfKeyToSearch",1).')', + '2'=>$langs->trans("Yes").' ('.$langs->trans("NumberOfKeyToSearch",2).')', + '3'=>$langs->trans("Yes").' ('.$langs->trans("NumberOfKeyToSearch",3).')', + ); + print $form->selectarray("activate_RESOURCE_USE_SEARCH_TO_SELECT",$arrval,$conf->global->RESOURCE_USE_SEARCH_TO_SELECT); + print ''; + print ''; + print '
'.$langs->trans('DisabledResourceLinkUser').''; +echo ajax_constantonoff('RESOURCE_HIDE_ADD_CONTACT_USER'); +print '
'.$langs->trans('DisabledResourceLinkContact').''; +echo ajax_constantonoff('RESOURCE_HIDE_ADD_CONTACT_THIPARTY'); +print '
'; + +print '
'; + + +//RESOURCE_HIDE_ADD_CONTACT_USER +//RESOURCE_HIDE_ADD_CONTACT_THIPARTY + +dol_fiche_end(); + + +llxFooter(); +$db->close(); diff --git a/htdocs/admin/resource_extrafields.php b/htdocs/admin/resource_extrafields.php new file mode 100644 index 00000000000..c3d90fac3e5 --- /dev/null +++ b/htdocs/admin/resource_extrafields.php @@ -0,0 +1,122 @@ + + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2016 Florian Henry + * + * 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/admin/resource_extrafields.php + * \ingroup agenda + * \brief Page to setup extra fields of resource + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/resource.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + + +if (!$user->admin) + accessforbidden(); + +$langs->load("admin"); +$langs->load("other"); +$langs->load("resource"); + +$extrafields = new ExtraFields($db); +$form = new Form($db); + +// List of supported format +$tmptype2label=ExtraFields::$type2label; +$type2label=array(''); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); + +$action=GETPOST('action', 'alpha'); +$attrname=GETPOST('attrname', 'alpha'); +$elementtype='resource'; //Must be the $table_element of the class that manage extrafield + +if (!$user->admin) accessforbidden(); + + +/* + * Actions + */ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + + +/* + * View + */ + +$textobject=$langs->transnoentitiesnoconv("ResourceSingular"); + +llxHeader('',$langs->trans("ResourceSetup")); + +$linkback=''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("ResourceSetup"),$linkback,'title_setup'); +print "
\n"; + +$head=resource_admin_prepare_head(); + +dol_fiche_head($head, 'attributes', $langs->trans("ResourceSingular"), 0, 'action'); + +require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; + +dol_fiche_end(); + + +// Buttons +if ($action != 'create' && $action != 'edit') +{ + print '
'; + print "".$langs->trans("NewAttribute").""; + print "
"; +} + + +/* ************************************************************************** */ +/* */ +/* Creation of an optional field */ +/* */ +/* ************************************************************************** */ + +if ($action == 'create') +{ + print "
"; + print load_fiche_titre($langs->trans('NewAttribute')); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; +} + +/* ************************************************************************** */ +/* */ +/* Edition of an optional field */ +/* */ +/* ************************************************************************** */ +if ($action == 'edit' && ! empty($attrname)) +{ + print "
"; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; +} + +llxFooter(); + +$db->close(); diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index 6faaff1e006..4f556f417be 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -49,6 +49,9 @@ if($action) { $res = dolibarr_set_const($db, "STOCK_USERSTOCK_AUTOCREATE", GETPOST('STOCK_USERSTOCK_AUTOCREATE','alpha'),'chaine',0,'',$conf->entity); } + if ($action == 'STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') { + $res = dolibarr_set_const($db, "STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE", GETPOST('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE','alpha'),'chaine',0,'',$conf->entity); + } if ($action == 'STOCK_ALLOW_NEGATIVE_TRANSFER') { $res = dolibarr_set_const($db, "STOCK_ALLOW_NEGATIVE_TRANSFER", GETPOST('STOCK_ALLOW_NEGATIVE_TRANSFER','alpha'),'chaine',0,'',$conf->entity); @@ -473,6 +476,21 @@ print ''; print "\n"; print "\n"; +$var=!$var; + +print ""; +print ''.$langs->trans("AllowAddLimitStockByWarehouse").''; + +print ''; +print "
"; +print ''; +print ""; +print $form->selectyesno("STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE",$conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE,1); +print ''; +print '
'; +print "\n"; +print "\n"; + print '
'; /* I keep the option/feature, but hidden to end users for the moment. If feature is used by module, no need to have users see it. diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php index 6fa692f47fc..540cd4a4b98 100644 --- a/htdocs/admin/supplier_invoice.php +++ b/htdocs/admin/supplier_invoice.php @@ -136,19 +136,23 @@ else if ($action == 'del') // Set default model else if ($action == 'setdoc') { - if (dolibarr_set_const($db, "INVOICE_SUPPLIER_ADDON_PDF",$value,'chaine',0,'',$conf->entity)) - { - // La constante qui a ete lue en avant du nouveau set - // on passe donc par une variable pour avoir un affichage coherent - $conf->global->INVOICE_SUPPLIER_ADDON_PDF = $value; - } + if (dolibarr_set_const($db, "INVOICE_SUPPLIER_ADDON_PDF",$value,'chaine',0,'',$conf->entity)) + { + // La constante qui a ete lue en avant du nouveau set + // on passe donc par une variable pour avoir un affichage coherent + $conf->global->INVOICE_SUPPLIER_ADDON_PDF = $value; + } - // On active le modele - $ret = delDocumentModel($value, $type); - if ($ret > 0) - { - $ret = addDocumentModel($value, $type, $label, $scandir); - } + // On active le modele + $ret = delDocumentModel($value, $type); + if ($ret > 0) + { + $ret = addDocumentModel($value, $type, $label, $scandir); + } +} +else if ($action == 'unsetdoc') +{ + dolibarr_del_const($db, "INVOICE_SUPPLIER_ADDON_PDF", $conf->entity); } if ($action == 'setmod') @@ -366,7 +370,7 @@ foreach ($dirmodels as $reldir) { while (($file = readdir($handle))!==false) { - if (preg_match('/\.modules\.php$/i',$file) && preg_match('/^(pdf_|doc_)/',$file)) + if (preg_match('/\.modules\.php$/i',$file) && preg_match('/^(pdf_|doc_)/',$file)) { $name = substr($file, 4, dol_strlen($file) -16); $classname = substr($file, 0, dol_strlen($file) -12); @@ -383,7 +387,7 @@ foreach ($dirmodels as $reldir) require_once $dir.$file; $module = new $classname($db,$specimenthirdparty); if (method_exists($module,'info')) print $module->info($langs); - else print $module->description; + else print $module->description; print "\n"; @@ -391,16 +395,17 @@ foreach ($dirmodels as $reldir) if (in_array($name, $def)) { print ''."\n"; - if ($conf->global->INVOICE_SUPPLIER_ADDON_PDF != "$name") - { + //if ($conf->global->INVOICE_SUPPLIER_ADDON_PDF != "$name") + //{ + // Even if choice is the default value, we allow to disable it: For supplier invoice, we accept to have no doc generation at all print 'scandir.'&label='.urlencode($module->name).'&type=invoice_supplier">'; print img_picto($langs->trans("Enabled"),'switch_on'); print ''; - } + /*} else { print img_picto($langs->trans("Enabled"),'switch_on'); - } + }*/ print ""; } else @@ -414,7 +419,9 @@ foreach ($dirmodels as $reldir) print ''; if ($conf->global->INVOICE_SUPPLIER_ADDON_PDF == "$name") { - print img_picto($langs->trans("Default"),'on'); + //print img_picto($langs->trans("Default"),'on'); + // Even if choice is the default value, we allow to disable it: For supplier invoice, we accept to have no doc generation at all + print 'scandir.'&label='.urlencode($module->name).'&type=invoice_supplier"" alt="'.$langs->trans("Disable").'">'.img_picto($langs->trans("Enabled"),'on').''; } else { diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php index b19831502f9..5d0cf665d7c 100644 --- a/htdocs/admin/supplier_order.php +++ b/htdocs/admin/supplier_order.php @@ -199,6 +199,23 @@ else if ($action == 'set_SUPPLIER_ORDER_OTHER') } } +// Activate ask for payment bank +else if ($action == 'set_BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER') +{ + $res = dolibarr_set_const($db, "BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER",$value,'chaine',0,'',$conf->entity); + + if (! $res > 0) $error++; + + if (! $error) + { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } + else + { + setEventMessages($langs->trans("Error"), null, 'errors'); + } +} + /* * View @@ -487,6 +504,38 @@ $var=false; $var=!$var; //} +// Ask for payment bank during supplier order +/* Kept as hidden for the moment +if ($conf->banque->enabled) +{ + $var=!$var; + print ''; + print $langs->trans("BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER").' '; + if (! empty($conf->use_javascript_ajax)) + { + print ajax_constantonoff('BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER'); + } + else + { + if (empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER)) + { + print ''.img_picto($langs->trans("Disabled"),'switch_off').''; + } + else + { + print ''.img_picto($langs->trans("Enabled"),'switch_on').''; + } + } + print ''; +} +else +{ + $var=!$var; + print ''; + print $langs->trans("BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER").' '.$langs->trans('NotAvailable').''; +} +*/ + print ''; print $langs->trans("FreeLegalTextOnOrders").' ('.$langs->trans("AddCRIfTooLong").')
'; $variablename='SUPPLIER_ORDER_FREE_TEXT'; diff --git a/htdocs/admin/system/about.php b/htdocs/admin/system/about.php index 3b2492fad65..a558a473957 100644 --- a/htdocs/admin/system/about.php +++ b/htdocs/admin/system/about.php @@ -100,8 +100,8 @@ print ''; print $langs->trans("Developpers").':'; print ''; //print "
\n"; @@ -110,7 +110,7 @@ print $langs->trans("OtherInformations").':'; print ''; print $langs->trans("Demo").':'; print ''; print $langs->trans("ModulesMarketPlaces").':'; print ''; @@ -178,14 +178,14 @@ print ''; print $langs->trans("Foundation").':'; print '
    '; -$url='http://wiki.dolibarr.org/index.php/Subscribe'; -if (preg_match('/^fr_/i',$langs->getDefaultLang())) $url='http://wiki.dolibarr.org/index.php/Adh%C3%A9rer'; -if (preg_match('/^es_/i',$langs->getDefaultLang())) $url='http://wiki.dolibarr.org/index.php/Subscribirse'; +$url='https://wiki.dolibarr.org/index.php/Subscribe'; +if (preg_match('/^fr_/i',$langs->getDefaultLang())) $url='https://wiki.dolibarr.org/index.php/Adh%C3%A9rer'; +if (preg_match('/^es_/i',$langs->getDefaultLang())) $url='https://wiki.dolibarr.org/index.php/Subscribirse'; print '
  • '.$langs->trans("SubscribeToFoundation").'
  • '; -print '
  • FaceBook
  • '; -print '
  • Twitter
  • '; -print '
  • Google Plus page
  • '; +print '
  • FaceBook
  • '; +print '
  • Twitter
  • '; +print '
  • Google Plus page
  • '; print '
'; @@ -193,13 +193,13 @@ print ''; print $langs->trans("OtherResources").':'; print '
    '; -$url='http://saas.dolibarr.org'; $title=$langs->trans("OfficialWebHostingService"); -if (preg_match('/^fr_/i',$langs->getDefaultLang())) $url='http://wiki.dolibarr.org/index.php/Solutions_de_Cloud'; -if (preg_match('/^es_/i',$langs->getDefaultLang())) $url='http://wiki.dolibarr.org/index.php/Soluciones_en_la_Nube'; +$url='https://saas.dolibarr.org'; $title=$langs->trans("OfficialWebHostingService"); +if (preg_match('/^fr_/i',$langs->getDefaultLang())) $url='https://wiki.dolibarr.org/index.php/Solutions_de_Cloud'; +if (preg_match('/^es_/i',$langs->getDefaultLang())) $url='https://wiki.dolibarr.org/index.php/Soluciones_en_la_Nube'; print '
  • '; print ''.$title.''; print '
  • '; -$url='http://partners.dolibarr.org'; $title=$langs->trans("ReferencedPreferredPartners"); +$url='https://partners.dolibarr.org'; $title=$langs->trans("ReferencedPreferredPartners"); print '
  • '; print ''.$title.''; print '
  • '; diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php index eeea93a2fea..2fe87a02e63 100644 --- a/htdocs/admin/system/dolibarr.php +++ b/htdocs/admin/system/dolibarr.php @@ -40,20 +40,22 @@ if (! $user->admin) $form=new Form($db); -llxHeader(); +$title=$langs->trans("InfoDolibarr"); -print load_fiche_titre($langs->trans("InfoDolibarr"),'','title_setup'); +llxHeader('', $title); + +print load_fiche_titre($title,'','title_setup'); // Version $var=true; print ''; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''; print '
    '.$langs->trans("Version").''.$langs->trans("Value").'
    '.$langs->trans("Version").''.$langs->trans("Value").'
    '.$langs->trans("VersionLastInstall").''.$conf->global->MAIN_VERSION_LAST_INSTALL.'
    '.$langs->trans("VersionLastInstall").''.$conf->global->MAIN_VERSION_LAST_INSTALL.'
    '.$langs->trans("VersionLastUpgrade").''.$conf->global->MAIN_VERSION_LAST_UPGRADE.'
    '.$langs->trans("VersionLastUpgrade").''.$conf->global->MAIN_VERSION_LAST_UPGRADE.'
    '.$langs->trans("VersionProgram").''.DOL_VERSION; +print '
    '.$langs->trans("VersionProgram").''.DOL_VERSION; // If current version differs from last upgrade if (empty($conf->global->MAIN_VERSION_LAST_UPGRADE)) { @@ -72,30 +74,30 @@ print '
    '; // Session $var=true; print ''; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print '\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; $var=!$var; -print ''."\n"; $var=!$var; -print ''; print "\n"; @@ -222,7 +222,7 @@ if ($mode == 'overwrite') print ''; print ''; // Limit to superadmin - if (! empty($conf->multicompany->enabled) && !$user->entity) + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print '\n"; print ''; @@ -371,7 +371,7 @@ if ($mode == 'searchkey') print_liste_field_titre($langs->trans("Language").' (en_US, es_MX, ...)',$_SERVER["PHP_SELF"],'lang,transkey','',$param,'',$sortfield,$sortorder).''; print_liste_field_titre($langs->trans("Key"),$_SERVER["PHP_SELF"],'transkey','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("CurrentTranslationString"),$_SERVER["PHP_SELF"],'transvalue','',$param,'',$sortfield,$sortorder); - if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre($langs->trans("Entity"),$_SERVER["PHP_SELF"],'entity,transkey','',$param,'',$sortfield,$sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre($langs->trans("Entity"),$_SERVER["PHP_SELF"],'entity,transkey','',$param,'',$sortfield,$sortorder); print ''; print "\n"; @@ -388,18 +388,18 @@ if ($mode == 'searchkey') print ''; // Action column - print ''; @@ -427,6 +427,10 @@ if ($mode == 'searchkey') $htmltext = $langs->trans("OriginalValueWas", $newlangfileonly->tab_translate[$key]); print $form->textwithpicto('', $htmltext, 1, 'warning'); } + /*if (! empty($conf->multicompany->enabled) && !$user->entity) + { + print $val; + }*/ print ''."\n"; } diff --git a/htdocs/admin/websites.php b/htdocs/admin/websites.php index ecc6b6a0166..b0c81ec18af 100644 --- a/htdocs/admin/websites.php +++ b/htdocs/admin/websites.php @@ -535,7 +535,8 @@ if ($id) { $showfield=1; $align="left"; - $valuetoshow=$obj->$fieldlist[$field]; + $fieldname=$fieldlist[$field]; + $valuetoshow=$obj->$fieldname; // Show value for field if ($showfield) print ''; @@ -613,14 +614,15 @@ function fieldListWebsites($fieldlist, $obj='', $tabname='', $context='') foreach ($fieldlist as $field => $value) { + $fieldname = $fieldlist[$field]; if ($fieldlist[$field] == 'lang') { print ''; } - elseif ($fieldlist[$field] == 'code' && isset($obj->$fieldlist[$field])) { - print ''; + elseif ($fieldlist[$field] == 'code' && isset($obj->$fieldname)) { + print ''; } else { @@ -631,7 +633,7 @@ function fieldListWebsites($fieldlist, $obj='', $tabname='', $context='') if ($fieldlist[$field]=='libelle') $size='size="32" '; if ($fieldlist[$field]=='tracking') $size='size="92" '; if ($fieldlist[$field]=='sortorder') $size='size="2" '; - print ''; + print ''; print ''; } } diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php index 717a25aa8b3..d9595cd7fb0 100644 --- a/htdocs/admin/workflow.php +++ b/htdocs/admin/workflow.php @@ -1,7 +1,7 @@ * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2005-2012 Laurent Destailleur + * Copyright (C) 2005-2016 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -73,13 +73,16 @@ print '
    '.$langs->trans("Session").''.$langs->trans("Value").'
    '.$langs->trans("Session").''.$langs->trans("Value").'
    '.$langs->trans("SessionSavePath").''.session_save_path().'
    '.$langs->trans("SessionSavePath").''.session_save_path().'
    '.$langs->trans("SessionName").''.session_name().'
    '.$langs->trans("SessionName").''.session_name().'
    '.$langs->trans("SessionId").''.session_id().'
    '.$langs->trans("SessionId").''.session_id().'
    '.$langs->trans("CurrentSessionTimeOut").''.ini_get('session.gc_maxlifetime').' '.$langs->trans("seconds"); +print '
    '.$langs->trans("CurrentSessionTimeOut").''.ini_get('session.gc_maxlifetime').' '.$langs->trans("seconds"); print ''; print $form->textwithpicto('',$langs->trans("SessionExplanation",ini_get("session.gc_probability"),ini_get("session.gc_divisor"))); print "
    '.$langs->trans("CurrentTheme").''.$conf->theme.'
    '.$langs->trans("CurrentTheme").''.$conf->theme.'
    '.$langs->trans("CurrentMenuHandler").''; +print '
    '.$langs->trans("CurrentMenuHandler").''; print $conf->standard_menu; print '
    '.$langs->trans("Screen").''; +print '
    '.$langs->trans("Screen").''; print $_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; print '
    '.$langs->trans("Session").''; +print '
    '.$langs->trans("Session").''; $i=0; foreach($_SESSION as $key => $val) { @@ -116,7 +118,7 @@ if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_S $var=true; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''."\n"; @@ -124,7 +126,7 @@ if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_S foreach($shmoparray as $key => $val) { $var=!$var; - print ''; + print ''; print ''; print ''; print ''."\n"; @@ -138,41 +140,41 @@ if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_S // Localisation $var=true; print '
    '.$langs->trans("LanguageFilesCachedIntoShmopSharedMemory").''.$langs->trans("LanguageFilesCachedIntoShmopSharedMemory").''.$langs->trans("NbOfEntries").''.$langs->trans("Address").'
    '.$key.'
    '.$key.''.count($val).''.dol_getshmopaddress($key).'
    '; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; // Thousands $var=!$var; $thousand=$langs->transnoentitiesnoconv("SeparatorThousand"); if ($thousand == 'SeparatorThousand') $thousand=' '; // ' ' does not work on trans method if ($thousand == 'None') $thousand=''; -print ''."\n"; +print ''."\n"; // Decimals $var=!$var; $dec=$langs->transnoentitiesnoconv("SeparatorDecimal"); -print ''."\n"; +print ''."\n"; // Show results of functions to see if everything works $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print "\n"; +print "\n"; if (($thousand != ',' && $thousand != '.') || ($thousand != ' ')) { $var=!$var; - print ""; + print ""; print "\n"; } $var=!$var; -print ''."\n"; +print ''."\n"; // Timezone $txt =$langs->trans("OSTZ").' (variable system TZ): '.(! empty($_ENV["TZ"])?$_ENV["TZ"]:$langs->trans("NotDefined")).'
    '."\n"; $txt.=$langs->trans("PHPTZ").' (php.ini date.timezone): '.(ini_get("date.timezone")?ini_get("date.timezone"):$langs->trans("NotDefined")).''."
    \n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php $txt.=$langs->trans("Dolibarr constant MAIN_SERVER_TZ").': '.(empty($conf->global->MAIN_SERVER_TZ)?$langs->trans("NotDefined"):$conf->global->MAIN_SERVER_TZ); //$txt.=$langs->trans("YouCanEditPHPTZ"); // deprecated $var=!$var; -print ''."\n"; // value defined in http://fr3.php.net/manual/en/timezones.europe.php $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; -print ''; +print ''; $var=!$var; -print ''; +print ''; $var=!$var; -print ''; +print ''; // Database timezone if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') { $var=!$var; - print ''."\n"; print ''."\n"; $var=!$var; -print ''."\n"; +print ''."\n"; $var=!$var; $filesystemencoding=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0 -print ''."\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php +print ''."\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php $var=!$var; $tmp=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0 if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1'; // By default for windows if (empty($tmp)) $tmp='utf-8'; // By default for other if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING; -print ''."\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php +print ''."\n"; // date.timezone must be in valued defined in http://fr3.php.net/manual/en/timezones.europe.php print '
    '.$langs->trans("LocalisationDolibarrParameters").''.$langs->trans("Value").'
    '.$langs->trans("LocalisationDolibarrParameters").''.$langs->trans("Value").'
    '.$langs->trans("LanguageBrowserParameter","HTTP_ACCEPT_LANGUAGE").''.$_SERVER["HTTP_ACCEPT_LANGUAGE"].'
    '.$langs->trans("LanguageBrowserParameter","HTTP_ACCEPT_LANGUAGE").''.$_SERVER["HTTP_ACCEPT_LANGUAGE"].'
    '.$langs->trans("CurrentUserLanguage").''.$langs->getDefaultLang().'
    '.$langs->trans("CurrentUserLanguage").''.$langs->getDefaultLang().'
    '.$langs->trans("CurrentValueSeparatorThousand").''.($thousand==' '?$langs->transnoentitiesnoconv("Space"):$thousand).'
    '.$langs->trans("CurrentValueSeparatorThousand").''.($thousand==' '?$langs->transnoentitiesnoconv("Space"):$thousand).'
    '.$langs->trans("CurrentValueSeparatorDecimal").''.$dec.'
    '.$langs->trans("CurrentValueSeparatorDecimal").''.$dec.'
      => price2num(1233.56+1)'.price2num(1233.56+1,'2').'
      => price2num(1233.56+1)'.price2num(1233.56+1,'2').'
      => price2num('."'1".$thousand."234".$dec."56')".price2num("1".$thousand."234".$dec."56",'2')."
      => price2num('."'1".$thousand."234".$dec."56')".price2num("1".$thousand."234".$dec."56",'2')."
      => price2num('."'1 234.56')".price2num("1 234.56",'2')."
      => price2num('."'1 234.56')".price2num("1 234.56",'2')."
      => price(1234.56)'.price(1234.56).'
      => price(1234.56)'.price(1234.56).'
    '.$langs->trans("CurrentTimeZone").''; // Timezone server PHP +print '
    '.$langs->trans("CurrentTimeZone").''; // Timezone server PHP $a=getServerTimeZoneInt('now'); $b=getServerTimeZoneInt('winter'); $c=getServerTimeZoneInt('summer'); @@ -185,18 +187,18 @@ $val.='       '.$langs->trans("DaylingSavingTime").': '.($dayligh print $form->textwithtooltip($val,$txt,2,1,img_info('')); print '
      => '.$langs->trans("CurrentHour").''.dol_print_date(dol_now(),'dayhour','tzserver').'
      => '.$langs->trans("CurrentHour").''.dol_print_date(dol_now(),'dayhour','tzserver').'
      => dol_print_date(0,"dayhourtext")'.dol_print_date(0,"dayhourtext").'
      => dol_print_date(0,"dayhourtext")'.dol_print_date(0,"dayhourtext").'
      => dol_get_first_day(1970,1,false)'.dol_get_first_day(1970,1,false).'     (=> dol_print_date() or idate() of this value = '.dol_print_date(dol_get_first_day(1970,1,false),'dayhour').')
      => dol_get_first_day(1970,1,false)'.dol_get_first_day(1970,1,false).'     (=> dol_print_date() or idate() of this value = '.dol_print_date(dol_get_first_day(1970,1,false),'dayhour').')
      => dol_get_first_day(1970,1,true)'.dol_get_first_day(1970,1,true).'     (=> dol_print_date() or idate() of this value = '.dol_print_date(dol_get_first_day(1970,1,true),'dayhour').')
      => dol_get_first_day(1970,1,true)'.dol_get_first_day(1970,1,true).'     (=> dol_print_date() or idate() of this value = '.dol_print_date(dol_get_first_day(1970,1,true),'dayhour').')
    '.$langs->trans("MySQLTimeZone").' (database)'; // Timezone server base + print '
    '.$langs->trans("MySQLTimeZone").' (database)'; // Timezone server base $sql="SHOW VARIABLES where variable_name = 'system_time_zone'"; $resql = $db->query($sql); if ($resql) @@ -209,7 +211,7 @@ if ($conf->db->type == 'mysql' || $conf->db->type == 'mysqli') // Client $var=!$var; $tz=(int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']; -print '
    '.$langs->trans("ClientTZ").''.($tz?($tz>=0?'+':'').$tz:'').' ('.($tz>=0?'+':'').($tz*60*60).')'; +print '
    '.$langs->trans("ClientTZ").''.($tz?($tz>=0?'+':'').$tz:'').' ('.($tz>=0?'+':'').($tz*60*60).')'; print '       '.$_SESSION['dol_tz_string']; print '       '.$langs->trans("DaylingSavingTime").': '; if ($_SESSION['dol_dst']>0) print yn(1); @@ -218,18 +220,18 @@ if (! empty($_SESSION['dol_dst_first'])) print '     ('.dol_print_date print '
      => '.$langs->trans("ClientHour").''.dol_print_date(dol_now(),'dayhour','tzuser').'
      => '.$langs->trans("ClientHour").''.dol_print_date(dol_now(),'dayhour','tzuser').'
    '.$langs->trans("File encoding").' (php.ini unicode.filesystem_encoding)'.$filesystemencoding.'
    '.$langs->trans("File encoding").' (php.ini unicode.filesystem_encoding)'.$filesystemencoding.'
      => '.$langs->trans("File encoding").''.$tmp.'
      => '.$langs->trans("File encoding").''.$tmp.'
    '; print '
    '; @@ -291,7 +293,7 @@ $configfileparameters=array( $var=true; print ''; print ''; -print ''; print ''; @@ -357,9 +359,9 @@ print '
    '; // Parameters in database print '
    '.$langs->trans("Parameters").' '; +print ''.$langs->trans("Parameters").' '; print $langs->trans("ConfigurationFile").' ('.$conffiletoshowshort.')'; print ''.$langs->trans("Parameter").'
    '; print ''; -print ''; +print ''; print ''; -if (empty($conf->multicompany->enabled) || !$user->entity) print ''; // If superadmin or multicompany disabled +if (empty($conf->multicompany->enabled) || !$user->entity) print ''; // If superadmin or multicompany disabled print "\n"; $sql = "SELECT"; @@ -394,9 +396,9 @@ if ($resql) $var=!$var; print ''; - print ''."\n"; - print ''."\n"; - if (empty($conf->multicompany->enabled) || !$user->entity) print ''."\n"; // If superadmin or multicompany disabled + print ''."\n"; + print ''."\n"; + if (empty($conf->multicompany->enabled) || !$user->entity) print ''."\n"; // If superadmin or multicompany disabled print "\n"; $i++; diff --git a/htdocs/admin/system/filecheck.php b/htdocs/admin/system/filecheck.php index 48eddfec155..5bea1b521ac 100644 --- a/htdocs/admin/system/filecheck.php +++ b/htdocs/admin/system/filecheck.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2005-2016 Laurent Destailleur * Copyright (C) 2007 Rodolphe Quiedeville * Copyright (C) 2007-2012 Regis Houssin * Copyright (C) 2015 Frederic France @@ -25,6 +25,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; $langs->load("admin"); @@ -42,6 +43,8 @@ llxHeader(); print load_fiche_titre($langs->trans("FileCheckDolibarr"),'','title_setup'); +print $langs->trans("FileCheckDesc").'

    '; + // Version $var = true; print '
    '.$langs->trans("Parameters").' '.$langs->trans("Database").''.$langs->trans("Parameters").' '.$langs->trans("Database").''.$langs->trans("Value").''.$langs->trans("Entity").''.$langs->trans("Entity").'
    '.$obj->name.''.$obj->value.''.$obj->entity.''.$obj->name.''.$obj->value.''.$obj->entity.'
    '; @@ -72,91 +75,142 @@ $file_list = array('missing' => array(), 'updated' => array()); // File to analyze //$xmlfile = DOL_DOCUMENT_ROOT.'/install/filelist-'.DOL_VERSION.'.xml'; -$xmlfile = DOL_DOCUMENT_ROOT.'/install/filelist.xml'; +$xmlshortfile = '/install/filelist-'.DOL_VERSION.'.xml'; +$xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; +$xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; -if (file_exists($xmlfile)) + +// Test if remote test is ok +$enableremotecheck = True; +if (preg_match('/beta|alpha/i', DOL_VERSION)) $enableremotecheck=False; + + +print ''; +print $langs->trans("MakeIntegrityAnalysisFrom").':
    '; +if (dol_is_file($xmlfile)) { - $xml = simplexml_load_file($xmlfile); - if ($xml) - { - if (is_object($xml->dolibarr_htdocs_dir[0])) - { - $file_list = array(); - $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0]); // Fill array $file_list - - print '
    '; - print ''; - print ''; - print ''; - print ''."\n"; - $var = true; - $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); - if (is_array($tmpfilelist) && count($tmpfilelist)) - { - foreach ($tmpfilelist as $file) - { - $var = !$var; - print ''; - print '' . "\n"; - print '' . "\n"; - print "\n"; - } - } - else - { - print ''; - } - print '
    ' . $langs->trans("FilesMissing") . '' . $langs->trans("ExpectedChecksum") . '
    '.$file['filename'].''.$file['expectedmd5'].'
    '.$langs->trans("None").'
    '; - - print '
    '; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''."\n"; - $var = true; - $tmpfilelist = dol_sort_array($file_list['updated'], 'filename'); - if (is_array($tmpfilelist) && count($tmpfilelist)) - { - foreach ($tmpfilelist as $file) - { - $var = !$var; - print ''; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print "\n"; - } - } - else - { - print ''; - } - print '
    ' . $langs->trans("FilesUpdated") . '' . $langs->trans("ExpectedChecksum") . '' . $langs->trans("CurrentChecksum") . '' . $langs->trans("Size") . '' . $langs->trans("DateModification") . '
    '.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size(dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename'])).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']),'dayhour').'
    '.$langs->trans("None").'
    '; - } - else - { - print 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile; - $error++; - } - } - else - { - print 'Error: Failed to parse XML for input file '.$xmlfile; - $error++; - } + print ' '.$langs->trans("LocalSignature").' = '.$xmlshortfile.'
    '; } else { - print $langs->trans('XmlNotFound') . ': ' . $xmlfile; - $error++; + print ' '.$langs->trans("LocalSignature").' = '.$xmlshortfile.' ('.$langs->trans("AvailableOnlyOnPackagedVersions").')
    '; } +if ($enableremotecheck) +{ + print ' '.$langs->trans("RemoteSignature").' = '.$xmlremote.'
    '; +} +else +{ + print ' '.$langs->trans("RemoteSignature").' = '.$xmlremote.' ('.$langs->trans("FeatureAvailableOnlyOnStable").')
    '; +} +print '
    '; +print ''; +print '
    '; +print '
    '; + +if (GETPOST('target') == 'local') +{ + if (dol_is_file($xmlfile)) + { + $xml = simplexml_load_file($xmlfile); + } + else + { + print $langs->trans('XmlNotFound') . ': ' . $xmlfile; + $error++; + } +} +if (GETPOST('target') == 'remote') +{ + $xmlarray = getURLContent($xmlremote); + + // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) + if (! $xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') + { + $xmlfile = $xmlarray['content']; + $xml = simplexml_load_file($xmlfile); + } + else + { + $errormsg=$langs->trans('XmlNotFound') . ': ' . $xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; + setEventMessages($errormsg, null, 'errors'); + $error++; + } +} + + +if ($xml) +{ + if (is_object($xml->dolibarr_htdocs_dir[0])) + { + $file_list = array(); + $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0]); // Fill array $file_list + + print ''; + print ''; + print ''; + print ''; + print ''."\n"; + $var = true; + $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); + if (is_array($tmpfilelist) && count($tmpfilelist)) + { + foreach ($tmpfilelist as $file) + { + $var = !$var; + print ''; + print '' . "\n"; + print '' . "\n"; + print "\n"; + } + } + else + { + print ''; + } + print '
    ' . $langs->trans("FilesMissing") . '' . $langs->trans("ExpectedChecksum") . '
    '.$file['filename'].''.$file['expectedmd5'].'
    '.$langs->trans("None").'
    '; + + print '
    '; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''."\n"; + $var = true; + $tmpfilelist = dol_sort_array($file_list['updated'], 'filename'); + if (is_array($tmpfilelist) && count($tmpfilelist)) + { + foreach ($tmpfilelist as $file) + { + $var = !$var; + print ''; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print "\n"; + } + } + else + { + print ''; + } + print '
    ' . $langs->trans("FilesUpdated") . '' . $langs->trans("ExpectedChecksum") . '' . $langs->trans("CurrentChecksum") . '' . $langs->trans("Size") . '' . $langs->trans("DateModification") . '
    '.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size(dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename'])).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']),'dayhour').'
    '.$langs->trans("None").'
    '; + } + else + { + print 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile; + $error++; + } +} + + + llxFooter(); diff --git a/htdocs/admin/tools/export.php b/htdocs/admin/tools/export.php index 5ace954045a..12b41110ac2 100644 --- a/htdocs/admin/tools/export.php +++ b/htdocs/admin/tools/export.php @@ -121,7 +121,9 @@ $utils = new Utils($db); if ($what == 'mysql') { - $cmddump=GETPOST("mysqldump"); // Do not sanitize here with 'alpha', will be sanitize later by escapeshellarg + $cmddump=GETPOST("mysqldump"); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg + $cmddump=dol_sanitizePathName($cmddump); + if (! empty($dolibarr_main_restrict_os_commands)) { $arrayofallowedcommand=explode(',', $dolibarr_main_restrict_os_commands); @@ -168,7 +170,8 @@ if ($what == 'mysqlnobin') // POSTGRESQL if ($what == 'postgresql') { - $cmddump=GETPOST("postgresqldump"); // Do not sanitize here with 'alpha', will be sanitize later by escapeshellarg + $cmddump=GETPOST("postgresqldump"); // Do not sanitize here with 'alpha', will be sanitize later by dol_sanitizePathName and escapeshellarg + $cmddump=dol_sanitizePathName($cmddump); if (! $errormsg && $cmddump) { diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index bf313be16c2..43f2953ccda 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -204,7 +204,7 @@ if ($mode == 'overwrite') print_liste_field_titre($langs->trans("Language").' (en_US, es_MX, ...)',$_SERVER["PHP_SELF"],'lang,transkey','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Key"),$_SERVER["PHP_SELF"],'transkey','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("NewTranslationStringToShow"),$_SERVER["PHP_SELF"],'transvalue','',$param,'',$sortfield,$sortorder); - if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre($langs->trans("Entity"),$_SERVER["PHP_SELF"],'entity,transkey','',$param,'',$sortfield,$sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre($langs->trans("Entity"),$_SERVER["PHP_SELF"],'entity,transkey','',$param,'',$sortfield,$sortorder); print '
    '; print ''; @@ -230,10 +230,10 @@ if ($mode == 'overwrite') print ''; } else - { + {*/ print ''; print ''; - } + //} print ''; print "
    '; print ''; // Limit to superadmin - if (! empty($conf->multicompany->enabled) && !$user->entity) + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''; print ''; } else - { + {*/ print ''; - } + //} print ''; + print ''; $searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); print $searchpitco; print '
    '.$valuetoshow.''; print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT,'lang'); print '
    '."\n"; clearstatcache(); $workflowcodes=array( - 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array('family'=>'create', 'position'=>10, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), + // Automatic creation + 'WORKFLOW_PROPAL_AUTOCREATE_ORDER'=>array('family'=>'create', 'position'=>10, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), 'WORKFLOW_ORDER_AUTOCREATE_INVOICE'=>array('family'=>'create', 'position'=>20, 'enabled'=>'! empty($conf->commande->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'bill'), + // Automatic classification 'WORKFLOW_ORDER_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify', 'position'=>30, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order','warning'=>'WarningCloseAlways'), 'WORKFLOW_INVOICE_CLASSIFY_BILLED_PROPAL'=>array('family'=>'classify', 'position'=>30, 'enabled'=>'! empty($conf->propal->enabled) && ! empty($conf->facture->enabled)', 'picto'=>'order','warning'=>'WarningCloseAlways'), // For the following 2 options, if module invoice is disabled, they does not exists, so "Classify billed" for order must be done manually from order card. 'WORKFLOW_INVOICE_CLASSIFY_BILLED_ORDER'=>array('family'=>'classify', 'position'=>40, 'enabled'=>'! empty($conf->facture->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'bill','warning'=>'WarningCloseAlways'), 'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER'=>array('family'=>'classify', 'position'=>50, 'enabled'=>'! empty($conf->facture->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'bill','warning'=>'WarningCloseAlways'), + 'WORKFLOW_ORDER_CLASSIFY_SHIPPED_SHIPPING'=>array('family'=>'classify', 'position'=>30, 'enabled'=>'! empty($conf->expedition->enabled) && ! empty($conf->commande->enabled)', 'picto'=>'order'), ); if (! empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow'])) @@ -107,7 +110,11 @@ foreach($workflowcodes as $key => $params) if ($oldfamily != $family) { print ''."\n"; - print ' '; + print ' '; print ' '; print "\n"; $oldfamily = $family; diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index 08209b03668..8142b564c1e 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -1,6 +1,6 @@ - * Copyright (C) 2005-2010 Laurent Destailleur + * Copyright (C) 2005-2016 Laurent Destailleur * Copyright (C) 2011 Juanjo Menent * Copyright (C) 2012 Regis Houssin * Copyright (C) 2015 Jean-François Ferry @@ -27,6 +27,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $langs->load("admin"); @@ -42,8 +43,16 @@ if ($action == 'setproductionmode') if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', $conf->entity) > 0) { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; + $result = dol_mkdir($conf->api->dir_temp); + if ($result < 0) + { + setEventMessages($langs->trans("ErrorFaildToCreateDir", $conf->api->dir_temp), null, 'errors'); + } + else + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } } else { @@ -70,7 +79,7 @@ print '
    '.$langs->trans("Description").''; + if ($family == 'create') print $langs->trans("AutomaticCreation"); + elseif ($family == 'classify') print $langs->trans("AutomaticClassification"); + else print $langs->trans("Description"); + print ''.$langs->trans("Status").'
    '; print ''; print ""; -print ""; +print '"; print ""; print ""; @@ -111,9 +120,15 @@ print '
    '; // Explorer print ''.$langs->trans("ApiExporerIs").':
    '; -$url=DOL_MAIN_URL_ROOT.'/api/index.php/explorer'; -print img_picto('','object_globe.png').' '.$url."
    \n"; - +if (dol_is_dir(DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/explorer')) +{ + $url=DOL_MAIN_URL_ROOT.'/api/index.php/explorer'; + print img_picto('','object_globe.png').' '.$url."
    \n"; +} +else +{ + print $langs->trans("NotAvailableWithThisDistribution"); +} llxFooter(); $db->close(); diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 550fd790d5e..45f2be3e4da 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -1,5 +1,6 @@ + * 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 @@ -91,6 +92,12 @@ class DolibarrApi // Remove linkedObjects. We should already have linkedObjectIds that avoid huge responses unset($object->linkedObjects); + unset($object->lignes); // should be lines + + unset($object->statuts); + unset($object->statuts_short); + unset($object->statuts_logo); + // Remove the $oldcopy property because it is not supported by the JSON // encoder. The following error is generated when trying to serialize // it: "Error encoding/decoding JSON: Type is not supported" @@ -155,4 +162,60 @@ class DolibarrApi return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray,$resource_id,$dbtablename,$feature2,$dbt_keyfield,$dbt_select); } + + /** + * Return if a $sqlfilters parameter is valid + * + * @param string $sqlfilters sqlfilter string + * @return boolean True if valid, False if not valid + */ + function _checkFilters($sqlfilters) + { + //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters); + $tmp=$sqlfilters; + $ok=0; + $i=0; $nb=count($tmp); + $counter=0; + while ($i < $nb) + { + if ($tmp[$i]=='(') $counter++; + if ($tmp[$i]==')') $counter--; + if ($counter < 0) + { + $error="Bad sqlfilters=".$sqlfilters; + dol_syslog($error, LOG_WARNING); + return false; + } + $i++; + } + return true; + } + + /** + * Function to forge a SQL criteria + * + * @param array $matches Array of found string by regex search + * @return string Forged criteria. Example: "t.field like 'abc%'" + */ + static function _forge_criteria_callback($matches) + { + global $db; + + //dol_syslog("Convert matches ".$matches[1]); + if (empty($matches[1])) return ''; + $tmp=explode(':',$matches[1]); + if (count($tmp) < 3) return ''; + + $tmpescaped=$tmp[2]; + if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) + { + $tmpescaped = "'".$db->escape($regbis[1])."'"; + } + else + { + $tmpescaped = $db->escape($tmpescaped); + } + return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped; + } } diff --git a/htdocs/api/class/api_access.class.php b/htdocs/api/class/api_access.class.php index bebf9a6667b..68ec526ec7e 100644 --- a/htdocs/api/class/api_access.class.php +++ b/htdocs/api/class/api_access.class.php @@ -1,5 +1,6 @@ + * 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 diff --git a/htdocs/api/class/api_dictionnarycountries.class.php b/htdocs/api/class/api_dictionnarycountries.class.php new file mode 100644 index 00000000000..9b7b409ef19 --- /dev/null +++ b/htdocs/api/class/api_dictionnarycountries.class.php @@ -0,0 +1,183 @@ + + * 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.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; + +/** + * API class for countries + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class DictionnaryCountries extends DolibarrApi +{ + private $translations = null; + + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of countries. + * + * The names of the countries will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by country ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $lang Code of the language the label of the countries must be translated to + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return List of countries + * + * @throws RestException + */ + function index($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; + $sql.=" WHERE 1 = 1"; + // 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.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + for ($i = 0; $i < min($num, ($limit <= 0 ? $num : $limit)); $i++) { + $obj = $this->db->fetch_object($result); + $country = new Ccountry($this->db); + if ($country->fetch($obj->rowid) > 0) { + // Translate the name of the country if needed + // and then apply the filter if there is one. + $this->translateLabel($country, $lang); + + if (empty($filter) || stripos($country->label, $filter) !== FALSE) { + $list[] = $this->_cleanObjectDatas($country); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of countries : '.$country->error); + } + + return $list; + } + + /** + * Get country by ID. + * + * @param int $id ID of country + * @param string $lang Code of the language the name of the + * country must be translated to + * + * @throws RestException + */ + function get($id, $lang = '') + { + $country = new Ccountry($this->db); + + if ($country->fetch($id) < 0) { + throw new RestException(503, 'Error when retrieving country : '.$country->error); + } + else if ($country->fetch($id) == 0) { + throw new RestException(404, 'country not found'); + } + + $this->translateLabel($country, $lang); + + return $this->_cleanObjectDatas($country); + } + + /** + * 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->error); + unset($object->errors); + + return $object; + } + + /** + * Translate the name of the country to the given language. + * + * @param Ccountry $country Country + * @param string $lang Code of the language the name of the + * country must be translated to + */ + private function translateLabel($country, $lang) + { + if (!empty($lang)) { + // Load the translations if this is a new language. + if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { + global $conf; + $this->translations = new Translate('', $conf); + $this->translations->setDefaultLang($lang); + $this->translations->load('dict'); + } + if ($country->code) { + $key = 'Country'.$country->code; + $translation = $this->translations->trans($key); + if ($translation != $key) { + $country->label = html_entity_decode($translation); + } + } + } + } +} diff --git a/htdocs/api/class/api_dictionnarytowns.class.php b/htdocs/api/class/api_dictionnarytowns.class.php new file mode 100644 index 00000000000..b5813d07792 --- /dev/null +++ b/htdocs/api/class/api_dictionnarytowns.class.php @@ -0,0 +1,101 @@ + + * 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.'/main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; + +/** + * API class for towns (content of the ziptown dictionary) + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class DictionnaryTowns extends DolibarrApi +{ + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of towns. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $zipcode To filter on zipcode + * @param string $town To filter on city name + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return List of towns + * + * @throws RestException + */ + function index($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; + $sql.= " WHERE t.active = 1"; + if ($zipcode) $sql.=" AND t.zip LIKE '%" . $this->db->escape($zipcode) . "%'"; + if ($town) $sql.=" AND t.town LIKE '%" . $this->db->escape($town) . "%'"; + // 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.= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + for ($i = 0; $i < min($num, ($limit <= 0 ? $num : $limit)); $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); + } + + return $list; + } + +} diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php index 1fa08b96179..3617eb899b1 100644 --- a/htdocs/api/class/api_login.class.php +++ b/htdocs/api/class/api_login.class.php @@ -1,5 +1,6 @@ + * 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 @@ -96,7 +97,7 @@ class Login 'success' => array( 'code' => 200, 'token' => $token, - 'message' => 'Welcome ' . $login.($reset?' - Token is new':' - Token was generated by a previous call') + 'message' => 'Welcome ' . $login.($reset?' - Token is new':' - This is your token (generated by a previous call)') ) ); } diff --git a/htdocs/api/index.php b/htdocs/api/index.php index 63fb8783530..80cfb5485df 100644 --- a/htdocs/api/index.php +++ b/htdocs/api/index.php @@ -1,5 +1,6 @@ + * 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 @@ -22,10 +23,10 @@ * \file htdocs/api/indexphp * * @todo User authentication with api_key - * - * */ + if (! defined("NOLOGIN")) define("NOLOGIN",'1'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); $res=0; if (! $res && file_exists("../main.inc.php")) $res=include '../main.inc.php'; @@ -82,18 +83,33 @@ foreach ($modulesdir as $dir) { if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i",$file,$reg)) { - $module = $part = strtolower($reg[1]); - - if ($module == 'categorie') { - $part = 'categories'; - } - if ($module == 'facture') { - $part = 'compta/facture'; - } + $module = strtolower($reg[1]); + $moduledirforclass = $module; + $moduleforperm = $module; + + if ($module == 'propale') { + $moduledirforclass = 'comm/propal'; + $moduleforperm='propal'; + } + elseif ($module == 'agenda') { + $moduledirforclass = 'comm/action'; + } + elseif ($module == 'adherent') { + $moduledirforclass = 'adherents'; + } + elseif ($module == 'banque') { + $moduledirforclass = 'compta/bank'; + } + elseif ($module == 'categorie') { + $moduledirforclass = 'categories'; + } + elseif ($module == 'facture') { + $moduledirforclass = 'compta/facture'; + } // Defined if module is enabled $enabled=true; - if (empty($conf->$module->enabled)) $enabled=false; + if (empty($conf->$moduleforperm->enabled)) $enabled=false; if ($enabled) { @@ -105,7 +121,7 @@ foreach ($modulesdir as $dir) * @todo : take care of externals module! * @todo : use getElementProperties() function ? */ - $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/'; + $dir_part = DOL_DOCUMENT_ROOT.'/'.$moduledirforclass.'/class/'; $handle_part=@opendir(dol_osencode($dir_part)); if (is_resource($handle_part)) @@ -120,7 +136,7 @@ foreach ($modulesdir as $dir) if (class_exists($classname)) { dol_syslog("Found deprecated API classname=".$classname." into ".$dir); - $api->r->addAPIClass($classname, ''); + $api->r->addAPIClass($classname, '/'); } } elseif (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i",$file_searched,$reg)) diff --git a/htdocs/barcode/codeinit.php b/htdocs/barcode/codeinit.php index d47e5aaecd3..ebe121301b7 100644 --- a/htdocs/barcode/codeinit.php +++ b/htdocs/barcode/codeinit.php @@ -143,7 +143,7 @@ if ($action == 'initbarcodeproducts') $nextvalue=$modBarCodeProduct->getNextValue($productstatic,''); //print 'Set value '.$nextvalue.' to product '.$productstatic->id." ".$productstatic->ref." ".$productstatic->type."
    \n"; - $result=$productstatic->setValueFrom('barcode', $nextvalue); + $result=$productstatic->setValueFrom('barcode', $nextvalue, '', '', 'date', '', $user, 'PRODUCT_MODIFY'); $nbtry++; if ($result > 0) $nbok++; diff --git a/htdocs/cashdesk/tpl/facturation1.tpl.php b/htdocs/cashdesk/tpl/facturation1.tpl.php index 8ddd7e48a85..d20eb4c3299 100644 --- a/htdocs/cashdesk/tpl/facturation1.tpl.php +++ b/htdocs/cashdesk/tpl/facturation1.tpl.php @@ -48,7 +48,7 @@ $langs->load("cashdesk"); onfocus="javascript: this.select(); verifResultat('resultats_dhtml', this.value, global->BARCODE_USE_SEARCH_TO_SELECT) ? (int) $conf->global->BARCODE_USE_SEARCH_TO_SELECT : 1) ?>);" onBlur="javascript: document.getElementById('resultats_dhtml').innerHTML = '';"/> -
    \n"; + print ' \n"; $i++; } echo " \n"; diff --git a/htdocs/comm/action/info.php b/htdocs/comm/action/info.php index 7c2001d925d..d1338142173 100644 --- a/htdocs/comm/action/info.php +++ b/htdocs/comm/action/info.php @@ -50,19 +50,41 @@ $result = restrictedArea($user, 'agenda', $id, 'actioncomm&societe', 'myactions| $help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('',$langs->trans("Agenda"),$help_url); -$act = new ActionComm($db); -$act->fetch($id); -$act->info($act->id); +$object = new ActionComm($db); +$object->fetch($id); +$object->info($object->id); -$head=actions_prepare_head($act); +$head=actions_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans("Action"),0,'action'); +$linkback = img_picto($langs->trans("BackToList"),'object_list','class="hideonsmartphone pictoactionview"'); +$linkback.= ''.$langs->trans("BackToList").''; + +// Link to other agenda views +$out=''; +$out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); +$out.=''.$langs->trans("ViewPerUser").''; +$out.='
    '; +$out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); +$out.=''.$langs->trans("ViewCal").''; +$out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); +$out.=''.$langs->trans("ViewWeek").''; +$out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); +$out.=''.$langs->trans("ViewDay").''; + +$linkback.=$out; + +dol_banner_tab($object, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); + +print '
    '; + +print '
    '; print '
    ".$langs->trans("Parameter")."".$langs->trans("Value")."'.$langs->trans("Value")." 
    + load("cashdesk"); */ ?> - '.$top_liste_produits.''."\n"; @@ -80,7 +80,7 @@ $langs->load("cashdesk"); $label = $tab_designations[$i]['label']; - print ''."\n"; diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index cab36132944..616ffcc31cd 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -93,16 +93,17 @@ class Categories extends DolibarrApi * * Get a list of categories * - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @return array Array of category objects + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') + * @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 category objects * * @throws RestException */ - function index($type = '', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -111,21 +112,24 @@ class Categories extends DolibarrApi throw new RestException(401); } - $sql = "SELECT s.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie as s"; - $sql.= ' WHERE s.entity IN ('.getEntity('categorie', 1).')'; + $sql = "SELECT t.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."categorie as t"; + $sql.= ' WHERE t.entity IN ('.getEntity('categorie', 1).')'; if (!empty($type)) { - $sql.= ' AND s.type='.array_search($type,Categories::$TYPES); + $sql.= ' AND t.type='.array_search($type,Categories::$TYPES); } - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + // Add sql filters + if ($sqlfilters) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + 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) @@ -142,7 +146,7 @@ class Categories extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); @@ -167,17 +171,17 @@ class Categories extends DolibarrApi * Note: This method is not directly exposed in the API, it is used * in the GET /xxx/{id}/categories requests. * - * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number + * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') * @param int $item Id of the item to get categories for * @return array Array of category objects * * @access private */ - function getListForItem($type, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $item = 0) { + function getListForItem($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type='customer', $item = 0) { global $db, $conf; $obj_ret = array(); @@ -228,7 +232,7 @@ class Categories extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); @@ -258,6 +262,7 @@ class Categories extends DolibarrApi if(! DolibarrApiAccess::$user->rights->categorie->creer) { throw new RestException(401); } + // Check mandatory fields $result = $this->_validate($request_data); @@ -337,7 +342,7 @@ class Categories extends DolibarrApi /** * Validate fields before create or update object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * * @throws RestException diff --git a/htdocs/categories/class/api_deprecated_category.class.php b/htdocs/categories/class/api_deprecated_category.class.php index 656c769bed3..106927a1a33 100644 --- a/htdocs/categories/class/api_deprecated_category.class.php +++ b/htdocs/categories/class/api_deprecated_category.class.php @@ -147,7 +147,7 @@ class CategoryApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); @@ -228,7 +228,7 @@ class CategoryApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); @@ -471,7 +471,7 @@ class CategoryApi extends DolibarrApi /** * Validate fields before create or update object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * * @throws RestException diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index e1a17798e25..6880dbd0aa3 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -5,7 +5,7 @@ * Copyright (C) 2006-2012 Regis Houssin * Copyright (C) 2006-2012 Laurent Destailleur * Copyright (C) 2007 Patrick Raguin - * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2013-2016 Juanjo Menent * Copyright (C) 2013-2016 Philippe Grand * Copyright (C) 2015 Marcos García * Copyright (C) 2015 Raphaël Doursenaud @@ -637,17 +637,19 @@ class Categorie extends CommonObject { if ($this->db->num_rows($resql) > 0) { - $objparent = $this->db->fetch_object($resql); + $objparent = $this->db->fetch_object($resql); if (!empty($objparent->fk_parent)) { $cat = new Categorie($this->db); - $cat->id=$objparent->fk_parent; - $result=$cat->add_type($obj, $type); - if ($result < 0) - { - $this->error=$cat->error; - $error++; + $cat->id = $objparent->fk_parent; + if (!$cat->containsObject($type, $obj->id)) { + $result = $cat->add_type($obj, $type); + if ($result < 0) + { + $this->error = $cat->error; + $error++; + } } } } diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index 07c586e3b11..d44407324c0 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -173,7 +173,7 @@ print ''; print ''; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index cd1c9ecfd1b..d38270b8827 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005 Simon TOSSER * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2010-2013 Juanjo Menent @@ -98,9 +98,11 @@ $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('actioncard','globalcard')); + /* * Actions */ + $listUserAssignedUpdated = false; // Remove user to assigned list if (GETPOST('removedassigned') || GETPOST('removedassigned') == '0') @@ -644,8 +646,8 @@ if ($action == 'create') if ($backtopage) print ''; if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) print ''; - if (GETPOST("actioncode") == 'AC_RDV') print load_fiche_titre($langs->trans("AddActionRendezVous")); - else print load_fiche_titre($langs->trans("AddAnAction")); + if (GETPOST("actioncode") == 'AC_RDV') print load_fiche_titre($langs->trans("AddActionRendezVous"), '', 'title_agenda'); + else print load_fiche_titre($langs->trans("AddAnAction"), '', 'title_agenda'); dol_fiche_head(); @@ -763,9 +765,9 @@ if ($action == 'create') $events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1',1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); //For external user force the company to user company if (!empty($user->societe_id)) { - print $form->select_thirdparty_list($user->societe_id,'socid','',1,1,0,$events); + print $form->select_thirdparty_list($user->societe_id, 'socid', '', 1, 1, 0, $events); } else { - print $form->select_thirdparty_list('','socid','',1,1,0,$events); + print $form->select_thirdparty_list('', 'socid', '', 'SelectThirdParty', 1, 0, $events); } } @@ -850,12 +852,13 @@ if ($id > 0) { $result1=$object->fetch($id); $result2=$object->fetch_thirdparty(); + $result2=$object->fetch_projet(); $result3=$object->fetch_contact(); $result4=$object->fetch_userassigned(); $result5=$object->fetch_optionals($id,$extralabels); + + if ($listUserAssignedUpdated || $donotclearsession) { - if($listUserAssignedUpdated || $donotclearsession) { - $datep=dol_mktime($fulldayevent?'00':$aphour, $fulldayevent?'00':$apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); $datef=dol_mktime($fulldayevent?'23':$p2hour, $fulldayevent?'59':$p2min, $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); @@ -1098,8 +1101,10 @@ if ($id > 0) print ''; print ''; @@ -1120,8 +1125,8 @@ if ($id > 0) $langs->load("projects"); - print ''; @@ -1139,11 +1144,11 @@ if ($id > 0) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print ''; - print ''; + print ''; } // Description - print ''; // Other attributes - $parameters=array('colspan'=>' colspan="3"', 'colspanvalue'=>'3', 'id'=>$object->id); + $parameters=array('id'=>$object->id); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook if (empty($reshook) && ! empty($extrafields->attribute_label)) { @@ -1183,33 +1188,51 @@ if ($id > 0) print $formconfirm; } + $linkback =img_picto($langs->trans("BackToList"),'object_list','class="hideonsmartphone pictoactionview"'); + $linkback.= ''.$langs->trans("BackToList").''; + + // Link to other agenda views + $out=''; + $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewPerUser").''; + $out.='
    '; + $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewCal").''; + $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewWeek").''; + $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewDay").''; + $linkback.=$out; + + dol_banner_tab($object, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); + + print '
    '; + // Affichage fiche action en mode visu print '
    '.$langs->trans("Categories").''; if (! empty($conf->use_javascript_ajax)) { - print ''; + print ''; } print '
    '.$langs->trans("ActionOnCompany").''; print '
    '; - $events=array(); + $events=array(); // 'method'=parameter action of url, 'url'=url to call that return new list of contacts $events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1',1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); + // TODO Refresh also list of project if $conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY not defined with list linked to socid ? + // FIXME If we change company, we may get a project that does not match print $form->select_company($object->socid, 'socid', '', 'SelectThirdParty', 1, 0, $events, 0); print '
    '; print '
    '.$langs->trans("Project").''; - $numprojet=$formproject->select_projects($object->socid, $object->fk_project, 'projectid'); + print '
    '.$langs->trans("Project").''; + $numprojet=$formproject->select_projects(($object->socid > 0 ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0); if ($numprojet==0) { print '   '.$langs->trans("AddProject").''; @@ -1130,7 +1135,7 @@ if ($id > 0) } // Priority - print '
    '.$langs->trans("Priority").''; + print '
    '.$langs->trans("Priority").''; print ''; print '
    '.$langs->trans("LinkedObject").''.dolGetElementUrl($object->fk_element,$object->elementtype,1).'
    '.dolGetElementUrl($object->fk_element,$object->elementtype,1).'
    '.$langs->trans("Description").''; + print '
    '.$langs->trans("Description").''; // Editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor=new DolEditor('note',$object->note,'',200,'dolibarr_notes','In',true,true,$conf->fckeditor->enabled,ROWS_5,90); @@ -1151,7 +1156,7 @@ if ($id > 0) print '
    '; - $linkback = ''.$langs->trans("BackToList").''; - // Ref - print ''; + print '';*/ // Type if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - print ''; + print ''; } // Title - print ''; + //print ''; // Full day event - print ''; + print ''; $rowspan=4; if (empty($conf->global->AGENDA_DISABLE_LOCATION)) $rowspan++; // Date start - print ''; // Status - print ''; + print '';*/ // Location if (empty($conf->global->AGENDA_DISABLE_LOCATION)) @@ -1235,7 +1258,7 @@ if ($id > 0) } // Assigned to - print ''; @@ -1432,46 +1455,6 @@ if ($id > 0) if ($action != 'edit') { - // Link to agenda views - print '
    '; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"').' '; - print ''."\n"; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"').' '; - print ''."\n"; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"').' '; - print ''."\n"; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"').' '; - print ''."\n"; - print '
    '; - if (empty($conf->global->AGENDA_DISABLE_BUILDDOC)) { print '
     

    '; @@ -1489,7 +1472,7 @@ if ($id > 0) $var=true; - $somethingshown=$formfile->show_documents('agenda',$object->id,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,0,0,'','','',$object->default_lang); + print $formfile->showdocuments('agenda',$object->id,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,0,0,'','','',$object->default_lang); print '
    '; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index c4739845042..419b32cdea4 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -37,7 +37,8 @@ class ActionComm extends CommonObject 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 $picto='action'; + /** * Id of the event * @var int @@ -513,7 +514,7 @@ class ActionComm extends CommonObject $sql.= " a.fk_contact, a.percent as percentage,"; $sql.= " a.fk_element, a.elementtype,"; $sql.= " a.priority, a.fulldayevent, a.location, a.punctual, a.transparency,"; - $sql.= " c.id as type_id, c.code as type_code, c.libelle, c.color as type_color,"; + $sql.= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; $sql.= " s.nom as socname,"; $sql.= " u.firstname, u.lastname as lastname"; $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; @@ -534,17 +535,18 @@ class ActionComm extends CommonObject { $obj = $this->db->fetch_object($resql); - $this->id = $obj->id; - $this->ref = $obj->ref; - $this->ref_ext = $obj->ref_ext; + $this->id = $obj->id; + $this->ref = $obj->ref; + $this->ref_ext = $obj->ref_ext; - // Properties of parent table llx_c_actioncomm (will be deprecated in future) - $this->type_id = $obj->type_id; - $this->type_code = $obj->type_code; + // Properties of parent table llx_c_actioncomm + $this->type_id = $obj->type_id; + $this->type_code = $obj->type_code; $this->type_color = $obj->type_color; + $this->type_picto = $obj->type_picto; $transcode=$langs->trans("Action".$obj->type_code); - $type_libelle=($transcode!="Action".$obj->type_code?$transcode:$obj->libelle); - $this->type = $type_libelle; + $type_label=($transcode!="Action".$obj->type_code?$transcode:$obj->type_label); + $this->type = $type_label; $this->code = $obj->code; $this->label = $obj->label; @@ -1017,18 +1019,19 @@ class ActionComm extends CommonObject */ function getLibStatut($mode,$hidenastatus=0) { - return $this->LibStatut($this->percentage,$mode,$hidenastatus); + return $this->LibStatut($this->percentage,$mode,$hidenastatus,$this->datep); } /** * Return label of action status * * @param int $percent Percent - * @param int $mode 0=Long label, 1=Short label, 2=Picto+Short label, 3=Picto, 4=Picto+Short label, 5=Short label+Picto, 6=Very short label+Picto + * @param int $mode 0=Long label, 1=Short label, 2=Picto+Short label, 3=Picto, 4=Picto+Short label, 5=Short label+Picto, 6=Picto+Long label, 7=Very short label+Picto * @param int $hidenastatus 1=Show nothing if status is "Not applicable" + * @param int $datestart Date start of event * @return string Label */ - function LibStatut($percent,$mode,$hidenastatus=0) + function LibStatut($percent,$mode,$hidenastatus=0,$datestart='') { global $langs; @@ -1076,11 +1079,19 @@ class ActionComm extends CommonObject } else if ($mode == 6) { - if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'),'statut9'); - else if ($percent==0) return '0% '.img_picto($langs->trans('StatusActionToDo'),'statut1'); - else if ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%','statut3'); - else if ($percent >= 100) return img_picto($langs->trans('StatusActionDone'),'statut6'); + if ($percent==-1 && ! $hidenastatus) return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'),'statut9'); + else if ($percent==0) return $langs->trans('StatusActionToDo').' (0%) '.img_picto($langs->trans('StatusActionToDo'),'statut1'); + else if ($percent > 0 && $percent < 100) return $langs->trans('StatusActionInProcess').' ('.$percent.'%) '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%','statut3'); + else if ($percent >= 100) return $langs->trans('StatusActionDone').' (100%) '.img_picto($langs->trans('StatusActionDone'),'statut6'); } + else if ($mode == 7) + { + if ($percent==-1 && ! $hidenastatus) return img_picto($langs->trans('StatusNotApplicable'),'statut9'); + else if ($percent==0) return '0% '.img_picto($langs->trans('StatusActionToDo'),'statut1'); + else if ($percent > 0 && $percent < 100) return $percent.'% '.img_picto($langs->trans('StatusActionInProcess').' - '.$percent.'%','statut3'); + else if ($percent >= 100) return img_picto($langs->trans('StatusActionDone'),'statut6'); + } + return ''; } @@ -1093,13 +1104,17 @@ class ActionComm extends CommonObject * @param string $classname Force style class on a link * @param string $option ''=Link to action, 'birthday'=Link to contact * @param int $overwritepicto 1=Overwrite picto + * @param int $notooltip 1=Disable tooltip * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$maxlength=0,$classname='',$option='',$overwritepicto=0) + function getNomUrl($withpicto=0,$maxlength=0,$classname='',$option='',$overwritepicto=0, $notooltip=0) { - global $conf,$langs, $hookmanager; + global $conf, $langs, $user, $hookmanager; + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + $result=''; + $tooltip = '' . $langs->trans('ShowAction'.$objp->code) . ''; if (! empty($this->ref)) $tooltip .= '
    ' . $langs->trans('Ref') . ': ' . $this->ref; @@ -1109,27 +1124,43 @@ class ActionComm extends CommonObject $tooltip .= '
    ' . $langs->trans('Title') . ': ' . $label; if (! empty($this->location)) $tooltip .= '
    ' . $langs->trans('Location') . ': ' . $this->location; - + + $linkclose=''; if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && $this->type_color) - $linkclose = ' style="background-color:#'.$this->type_color.'" class="'.$classname.' classfortooltip" title="'.dol_escape_htmltag($tooltip, 1).'">'; - else - $linkclose = ' class="'.$classname.' classfortooltip" title="'.dol_escape_htmltag($tooltip, 1).'">'; + $linkclose = ' style="background-color:#'.$this->type_color.'"'; - if (! is_object($hookmanager)) + if (empty($notooltip) && $user->rights->propal->lire) { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowSupplierProposal"); + $linkclose.=' alt="'.dol_escape_htmltag($tooltip, 1).'"'; + } + $linkclose.=' title="'.dol_escape_htmltag($tooltip, 1).'"'; + $linkclose.=' class="'.$classname.' classfortooltip"'; + + if (! is_object($hookmanager)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager=new HookManager($this->db); + } + $hookmanager->initHooks(array('actiondao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose); } - $hookmanager->initHooks(array('actiondao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - $linkclose = ($hookmanager->resPrint ? $hookmanager->resPrint : $linkclose); - + else $linkclose.=' class="'.$classname.'"'; + + $url=''; if ($option=='birthday') - $link = 'id; else - $link = 'id; + + $linkstart = ''; $linkend=''; + //print 'rrr'.$this->libelle.'-'.$withpicto; if ($withpicto == 2) @@ -1152,10 +1183,10 @@ 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.=$link.img_object($langs->trans("ShowAction").': '.$libelle, ($overwritepicto?$overwritepicto:'action'), 'class="classfortooltip"').$linkend; + $result.=$linkstart.img_object(($notooltip?'':$langs->trans("ShowAction").': '.$libelle), ($overwritepicto?$overwritepicto:'action'), ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend; } if ($withpicto==1) $result.=' '; - $result.=$link.$libelleshort.$linkend; + $result.=$linkstart.$libelleshort.$linkend; return $result; } diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php new file mode 100644 index 00000000000..db828656966 --- /dev/null +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -0,0 +1,294 @@ + + * 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.'/comm/action/class/actioncomm.class.php'; + +/** + * API class for Agenda Events + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class AgendaEvents extends DolibarrApi +{ + + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + ); + + /** + * @var Event $actioncomm {@type ActionComm} + */ + public $actioncomm; + + + /** + * Constructor + */ + function __construct() + { + global $db, $conf; + $this->db = $db; + $this->actioncomm = new ActionComm($this->db); + } + + /** + * Get properties of a Agenda Events object + * + * Return an array with Agenda Events informations + * + * @param int $id ID of Agenda Events + * @return array|mixed Data without useless information + * + * @throws RestException + */ + function get($id) + { + if(! DolibarrApiAccess::$user->rights->agenda->myactions->read) { + throw new RestException(401, "Insuffisant rights to read an event"); + } + + $result = $this->actioncomm->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Agenda Events not found'); + } + + if(! DolibarrApiAccess::$user->rights->agenda->allactions->read && $this->actioncomm->ownerid != DolibarrApiAccess::$user->id) { + throw new RestException(401, "Insuffisant rights to read event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id); + } + + if( ! DolibarrApi::_checkAccessToResource('agenda',$this->actioncomm->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $this->actioncomm->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->actioncomm); + } + + /** + * List Agenda Events + * + * Get a list of Agenda Events + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $user_ids User ids filter field (owners of event). 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 Agenda Events objects + */ + function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 0, $page = 0, $user_ids = 0, $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + + // case of external user, $societe param is ignored and replaced by user's socid + //$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe; + + $sql = "SELECT t.id as rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as t"; + $sql.= ' WHERE t.entity IN ('.getEntity('actioncomm', 1).')'; + if ($user_ids) $sql.=" AND t.fk_user_action IN (".$user_ids.")"; + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $db->plimit($limit + 1, $offset); + } + + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + while ($i < min($num, ($limit <= 0 ? $num : $limit))) + { + $obj = $db->fetch_object($result); + $actioncomm_static = new ActionComm($db); + if($actioncomm_static->fetch($obj->rowid)) { + $obj_ret[] = parent::_cleanObjectDatas($actioncomm_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve Agenda Event list'); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No Agenda Event found'); + } + return $obj_ret; + } + + /** + * Create Agenda Event object + * + * @param array $request_data Request data + * @return int ID of Agenda Event + */ + function post($request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->agenda->myactions->create) { + throw new RestException(401, "Insuffisant rights to create your Agenda Event"); + } + if(! DolibarrApiAccess::$user->rights->agenda->allactions->create && DolibarrApiAccess::$user->id != $request_data['userownerid']) { + throw new RestException(401, "Insuffisant rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id); + } + + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach($request_data as $field => $value) { + $this->actioncomm->$field = $value; + } + /*if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->expensereport->lines = $lines; + }*/ + if ($this->actioncomm->create(DolibarrApiAccess::$user) <= 0) { + $errormsg = $this->actioncomm->error; + throw new RestException(500, $errormsg ? $errormsg : "Error while creating actioncomm"); + } + + return $this->actioncomm->id; + } + + + /** + * Update Agenda Event general fields (won't touch lines of expensereport) + * + * @param int $id Id of Agenda Event to update + * @param array $request_data Datas + * + * @return int + */ + /* + function put($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->agenda->myactions->create) { + throw new RestException(401, "Insuffisant rights to create your Agenda Event"); + } + if(! DolibarrApiAccess::$user->rights->agenda->allactions->create && DolibarrApiAccess::$user->id != $request_data['userownerid']) { + throw new RestException(401, "Insuffisant rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id); + } + + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + foreach($request_data as $field => $value) { + $this->expensereport->$field = $value; + } + + if($this->expensereport->update($id, DolibarrApiAccess::$user,1,'','','update')) + return $this->get($id); + + return false; + } + */ + + /** + * Delete Agenda Event + * + * @param int $id Agenda Event ID + * + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->agenda->myactions->delete) { + throw new RestException(401, "Insuffisant rights to delete your Agenda Event"); + } + + $result = $this->actioncomm->fetch($id); + + if(! DolibarrApiAccess::$user->rights->agenda->allactions->delete && DolibarrApiAccess::$user->id != $this->actioncomm->userownerid) { + throw new RestException(401, "Insuffisant rights to delete an Agenda Event of owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id); + } + + if( ! $result ) { + throw new RestException(404, 'Agenda Event not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('actioncomm',$this->actioncomm->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if( ! $this->actioncomm->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete Agenda Event : '.$this->actioncomm->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Agenda Event deleted' + ) + ); + + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate($data) + { + $event = array(); + foreach (Events::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $event[$field] = $data[$field]; + + } + return $event; + } +} diff --git a/htdocs/comm/action/class/cactioncomm.class.php b/htdocs/comm/action/class/cactioncomm.class.php index 5e14b45665b..237a1043ac6 100644 --- a/htdocs/comm/action/class/cactioncomm.class.php +++ b/htdocs/comm/action/class/cactioncomm.class.php @@ -35,9 +35,11 @@ class CActionComm var $code; var $type; - var $libelle; + var $libelle; // deprecated + var $label; var $active; var $color; + var $picto; var $type_actions=array(); @@ -60,7 +62,7 @@ class CActionComm */ function fetch($id) { - $sql = "SELECT id, code, type, libelle, color, active"; + $sql = "SELECT id, code, type, libelle as label, color, active, picto"; $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; if (is_numeric($id)) $sql.= " WHERE id=".$id; else $sql.= " WHERE code='".$id."'"; @@ -76,7 +78,8 @@ class CActionComm $this->id = $obj->id; $this->code = $obj->code; $this->type = $obj->type; - $this->libelle = $obj->libelle; + $this->libelle = $obj->label; // deprecated + $this->label = $obj->label; $this->active = $obj->active; $this->color = $obj->color; @@ -114,7 +117,7 @@ class CActionComm $repid = array(); $repcode = array(); - $sql = "SELECT id, code, libelle, module, type, color"; + $sql = "SELECT id, code, libelle as label, module, type, color, picto"; $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; $sql.= " WHERE 1=1"; if ($active != '') $sql.=" AND active=".$active; @@ -155,8 +158,8 @@ class CActionComm if ($onlyautoornot && $code == 'AC_OTH') $code='AC_MANUAL'; if ($onlyautoornot && $code == 'AC_OTH_AUTO') $code='AC_AUTO'; $transcode=$langs->trans("Action".$code); - $repid[$obj->id] = ($transcode!="Action".$code?$transcode:$langs->trans($obj->libelle)); - $repcode[$obj->code] = ($transcode!="Action".$code?$transcode:$langs->trans($obj->libelle)); + $repid[$obj->id] = ($transcode!="Action".$code?$transcode:$langs->trans($obj->label)); + $repcode[$obj->code] = ($transcode!="Action".$code?$transcode:$langs->trans($obj->label)); if ($onlyautoornot && preg_match('/^module/',$obj->type) && $obj->module) $repcode[$obj->code].=' ('.$langs->trans("Module").': '.$obj->module.')'; } $i++; diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index e8e5c388eb4..4691673a831 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -123,30 +123,49 @@ if ($object->id > 0) dol_fiche_head($head, 'documents', $langs->trans("Action"),0,'action'); + $linkback = img_picto($langs->trans("BackToList"),'object_list','class="hideonsmartphone pictoactionview"'); + $linkback.= ''.$langs->trans("BackToList").''; + + // Link to other agenda views + $out=''; + $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewPerUser").''; + $out.='
    '; + $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewCal").''; + $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewWeek").''; + $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewDay").''; + + $linkback.=$out; + + dol_banner_tab($object, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); + + print '
    '; + // Affichage fiche action en mode visu print '
    '.$langs->trans("Ref").''; + /*print '
    '.$langs->trans("Ref").''; print $form->showrefnav($object, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); - print '
    '.$langs->trans("Type").''.$object->type.'
    '.$langs->trans("Type").''.$object->type.'
    '.$langs->trans("Title").''.dol_htmlentities($object->label).'
    '.$langs->trans("Title").''.dol_htmlentities($object->label).'
    '.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent, 3).'
    '.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent, 3).'
    '.$langs->trans("DateActionStart").''; + print '
    '.$langs->trans("DateActionStart").''; if (! $object->fulldayevent) print dol_print_date($object->datep,'dayhour'); else print dol_print_date($object->datep,'day'); if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); @@ -1224,9 +1247,9 @@ if ($id > 0) print '
    '.$langs->trans("Status").' / '.$langs->trans("Percentage").''; + /*print '
    '.$langs->trans("Status").' / '.$langs->trans("Percentage").''; print $object->getLibStatut(4); - print '
    '.$langs->trans("ActionAssignedTo").''; + print '
    '.$langs->trans("ActionAssignedTo").''; $listofuserid=array(); if (empty($donotclearsession)) { @@ -1291,7 +1314,7 @@ if ($id > 0) // Third party - Contact if ($conf->societe->enabled) { - print '
    '.$langs->trans("ActionOnCompany").''.($object->thirdparty->id?$object->thirdparty->getNomUrl(1):$langs->trans("None")); + print '
    '.$langs->trans("ActionOnCompany").''.($object->thirdparty->id?$object->thirdparty->getNomUrl(1):$langs->trans("None")); if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') { if ($object->thirdparty->fetch($object->thirdparty->id)) @@ -1323,7 +1346,7 @@ if ($id > 0) // Project if (! empty($conf->projet->enabled)) { - print '
    '.$langs->trans("Project").''; + print '
    '.$langs->trans("Project").''; if ($object->fk_project) { $project=new Project($db); @@ -1334,7 +1357,7 @@ if ($id > 0) } // Priority - print '
    '.$langs->trans("Priority").''; + print '
    '.$langs->trans("Priority").''; print ($object->priority?$object->priority:''); print '
    '; - $linkback = ''.$langs->trans("BackToList").''; - // Ref - print ''; + print '';*/ // Type if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - print ''; + print ''; } // Title - print ''; + //print ''; // Full day event - print ''; + print ''; // Date start - print ''; // Status - print ''; + print '';*/ // Location if (empty($conf->global->AGENDA_DISABLE_LOCATION)) @@ -172,7 +191,7 @@ if ($object->id > 0) } // Assigned to - print ''; - print '
    '.$langs->trans("Ref").''; + /*print '
    '.$langs->trans("Ref").''; print $form->showrefnav($object, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); - print '
    '.$langs->trans("Type").''.$object->type.'
    '.$langs->trans("Type").''.$object->type.'
    '.$langs->trans("Title").''.$object->label.'
    '.$langs->trans("Title").''.$object->label.'
    '.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent, 3).'
    '.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent, 3).'
    '.$langs->trans("DateActionStart").''; + print '
    '.$langs->trans("DateActionStart").''; if (! $object->fulldayevent) print dol_print_date($object->datep,'dayhour'); else print dol_print_date($object->datep,'day'); if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); @@ -161,9 +180,9 @@ if ($object->id > 0) print '
    '.$langs->trans("Status").' / '.$langs->trans("Percentage").''; + /*print '
    '.$langs->trans("Status").' / '.$langs->trans("Percentage").''; print $object->getLibStatut(4); - print '
    '.$langs->trans("ActionAffectedTo").''; + print '
    '.$langs->trans("ActionAffectedTo").''; $listofuserid=array(); if (empty($donotclearsession)) { @@ -206,11 +225,15 @@ if ($object->id > 0) } print '


    '; + print '
    '; + + print '

    '; + + print ''; // Third party - Contact - print ''; + print ''; print ''; print '
    '.$langs->trans("ActionOnCompany").''.($object->thirdparty->id?$object->thirdparty->getNomUrl(1):$langs->trans("None")); + print '
    '.$langs->trans("ActionOnCompany").''.($object->thirdparty->id?$object->thirdparty->getNomUrl(1):$langs->trans("None")); if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') { if ($object->thirdparty->fetch($object->thirdparty->id)) @@ -281,7 +304,7 @@ if ($object->id > 0) } - print '
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '; @@ -289,54 +312,6 @@ if ($object->id > 0) dol_fiche_end(); - - if ($action != 'edit') - { - // Link to agenda views - print '
    '; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"').' '; - print '
    '."\n"; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarweek','class="hideonsmartphone pictoactionview"').' '; - print '
    '."\n"; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarday','class="hideonsmartphone pictoactionview"').' '; - print '
    '."\n"; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarperuser','class="hideonsmartphone pictoactionview"').' '; - print '
    '."\n"; - print '
    '; - - print '
    '; - print "

    "; - } - - $modulepart = 'actions'; $permission = $user->rights->agenda->myactions->create||$user->rights->agenda->allactions->create; $param = '&id=' . $object->id; diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index f70b8d171a1..9b6f837f951 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -970,7 +970,15 @@ if (empty($action) || $action == 'show_month') // View by month $i=0; while ($i < 7) { - echo '
    '.$langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7))."'; + $numdayinweek=(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7); + if (! empty($conf->dol_optimize_smallscreen)) + { + $labelshort=array(0=>'SundayMin',1=>'MondayMin',2=>'TuesdayMin',3=>'WednesdayMin',4=>'ThursdayMin',5=>'FridayMin',6=>'SaturdayMin'); + print $langs->trans($labelshort[$numdayinweek]); + } + else print $langs->trans("Day".$numdayinweek); + print "
    '; -dol_print_object_info($act); +dol_print_object_info($object); print '
    '; -print ''; +dol_fiche_end(); llxFooter(); $db->close(); diff --git a/htdocs/comm/action/listactions.php b/htdocs/comm/action/listactions.php index b927244821e..ec4fba12980 100644 --- a/htdocs/comm/action/listactions.php +++ b/htdocs/comm/action/listactions.php @@ -55,6 +55,7 @@ else $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE)); } if ($actioncode == '' && empty($actioncodearray)) $actioncode=(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE); +$search_title=GETPOST('search_title','alpha'); $dateselect=dol_mktime(0, 0, 0, GETPOST('dateselectmonth'), GETPOST('dateselectday'), GETPOST('dateselectyear')); $datestart=dol_mktime(0, 0, 0, GETPOST('datestartmonth'), GETPOST('datestartday'), GETPOST('datestartyear')); @@ -106,13 +107,6 @@ if (! $user->rights->agenda->allactions->read || $filter=='mine') // If no permi $filtert=$user->id; } -// Purge search criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers -{ - $datestart=''; - $dateend=''; -} - // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('agendalist')); @@ -133,6 +127,18 @@ if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) exit; } +$parameters=array('id'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +{ + $actioncode=''; + $search_title=''; + $datestart=''; + $dateend=''; +} /* @@ -201,6 +207,7 @@ if ($status == '-1') { $sql.= " AND a.percent = -1"; } // Not applicable if ($status == '50') { $sql.= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started if ($status == 'done' || $status == '100') { $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; } if ($status == 'todo') { $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; } +if ($search_title) $sql.=natural_search("a.label", $search_title); // We must filter on assignement table if ($filtert > 0 || $usergroup > 0) { @@ -309,8 +316,10 @@ if ($resql) $i = 0; print ''; print ''; - print_liste_field_titre($langs->trans("Action"),$_SERVER["PHP_SELF"],"a.label",$param,"","",$sortfield,$sortorder); - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"c.libelle",$param,"","",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"a.id",$param,"","",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Title"),$_SERVER["PHP_SELF"],"a.label",$param,"","",$sortfield,$sortorder); + //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"c.libelle",$param,"","",$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateStart"),$_SERVER["PHP_SELF"],"a.datep",$param,'','align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateEnd"),$_SERVER["PHP_SELF"],"a.datep2",$param,'','align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom",$param,"","",$sortfield,$sortorder); @@ -322,11 +331,12 @@ if ($resql) print ''; print ''; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { + print ''; + //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + //{ print ''; //print ''; - } + //} print ''; @@ -367,23 +377,41 @@ if ($resql) $var=!$var; + $actionstatic->id=$obj->id; + $actionstatic->ref=$obj->id; + $actionstatic->type_code=$obj->type_code; + $actionstatic->type_label=$obj->type_label; + $actionstatic->type_picto=$obj->type_picto; + $actionstatic->label=$obj->label; + print ""; // Action (type) print ''; + // Action (type) + print ''; + + // Type + print ''; + if ($actionstatic->type_picto) print img_picto('', $actionstatic->type_picto); + else { + if ($actionstatic->type_code == 'AC_TEL') print img_picto('', 'object_phoning').' '; + if ($actionstatic->type_code == 'AC_FAX') print img_picto('', 'object_phoning_fax').' '; + if ($actionstatic->type_code == 'AC_EMAIL') print img_picto('', 'object_email').' '; + } } + $labeltype=$obj->type_code; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype='AC_OTH'; + if (! empty($arraylist[$labeltype])) $labeltype=$arraylist[$labeltype]; + print dol_trunc($labeltype,28); + print ''; // Start date print ''; // Status/Percent - print ''; + $datep=$db->jdate($obj->datep); + print ''; print ''; diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 39e4ae13f60..e9883a78ec7 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -9,7 +9,6 @@ * Copyright (C) 2013 Alexandre Spangaro * Copyright (C) 2015 Frederic France * 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 * the Free Software Foundation; either version 3 of the License, or @@ -63,7 +62,6 @@ $result = restrictedArea($user,'societe',$id,'&societe'); $action = GETPOST('action'); $mode = GETPOST("mode"); -$modesearch = GETPOST("mode_search"); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); @@ -90,7 +88,7 @@ $hookmanager->initHooks(array('commcard','globalcard')); * Actions */ -$parameters = array('socid' => $id); +$parameters = array('id' => $id, 'socid' => $id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); @@ -202,41 +200,15 @@ $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('',$title,$help_url); -/* -if ($mode == 'search') -{ - if ($modesearch == 'soc') - { - // TODO move to DAO class - $sql = "SELECT s.rowid"; - if (!$user->rights->societe->client->voir && !$id) $sql .= ", sc.fk_soc, sc.fk_user "; - $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE lower(s.nom) like '%".strtolower($socname)."%'"; - if (!$user->rights->societe->client->voir && !$id) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - } - - $resql=$db->query($sql); - if ($resql) - { - if ( $db->num_rows($resql) == 1) - { - $obj = $db->fetch_object($resql); - $id = $obj->rowid; - } - $db->free($resql); - } -} -*/ - if ($id > 0) { $head = societe_prepare_head($object); dol_fiche_head($head, 'customer', $langs->trans("ThirdParty"),0,'company'); - - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; @@ -244,14 +216,14 @@ if ($id > 0) print '
    '; print $form->select_date($datestart, 'datestart', 0, 0, 1, '', 1, 0, 1); print '
    '; - $actionstatic->id=$obj->id; - $actionstatic->type_code=$obj->type_code; - $actionstatic->type_label=$obj->type_label; - $actionstatic->label=$obj->label; - print $actionstatic->getNomUrl(1,36); + print $actionstatic->getNomUrl(1,-1); print ''; + print $actionstatic->label; + print ''; if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - $labeltype=$obj->type_code; - if (! empty($arraylist[$labeltype])) $labeltype=$arraylist[$labeltype]; - print ''.dol_trunc($labeltype,28).''; @@ -433,13 +461,14 @@ if ($resql) if ($obj->fk_user_action > 0) { $userstatic->fetch($obj->fk_user_action); - print $userstatic->getLoginUrl(1); + print $userstatic->getNomUrl(1); } else print ' '; print ''.$actionstatic->LibStatut($obj->percent,6).''.$actionstatic->LibStatut($obj->percent,3,1,$datep).'
    '; // Prospect/Customer - print ''; // Prefix if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { - print ''; } @@ -261,7 +233,7 @@ if ($id > 0) $langs->load("compta"); print ''; @@ -269,7 +241,7 @@ if ($id > 0) print ''; print ''; print ''; @@ -278,12 +250,12 @@ if ($id > 0) // Skype if (! empty($conf->skype->enabled)) { - print ''; + print ''; } // Assujeti a TVA ou pas print ''; - print ''; print ''; @@ -291,20 +263,20 @@ if ($id > 0) // Local Taxes if ($mysoc->useLocalTax(1)) { - print ''; } if ($mysoc->useLocalTax(2)) { - print ''; } // TVA Intra - print ''; @@ -316,7 +288,7 @@ if ($id > 0) print ''; print '
    '.$langs->trans('ProspectCustomer').''; + print '
    '.$langs->trans('ProspectCustomer').''; print $object->getLibCustProspStatut(); print '
    '.$langs->trans("Prefix").''; + print '
    '.$langs->trans("Prefix").''; print ($object->prefix_comm?$object->prefix_comm:' '); print '
    '; - print $langs->trans('CustomerCode').''; + print $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 ''; print $form->editfieldval("CustomerAccountancyCode",'customeraccountancycode',$object->code_compta,$object,$user->rights->societe->creer); print '
    '.$langs->trans('Skype').''.dol_print_skype($object->skype,0,$object->id,'AC_SKYPE').'
    '.$langs->trans('Skype').''.dol_print_skype($object->skype,0,$object->id,'AC_SKYPE').'
    '.$langs->trans('VATIsUsed').''; + print ''.$langs->trans('VATIsUsed').''; print yn($object->tva_assuj); print '
    '.$langs->trans("LocalTax1IsUsedES").''; + print '
    '.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; print yn($object->localtax1_assuj); print '
    '.$langs->trans("LocalTax2IsUsedES").''; + print '
    '.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; print yn($object->localtax2_assuj); print '
    '.$langs->trans('VATIntra').''; + print '
    '.$langs->trans('VATIntra').''; print $object->tva_intra; print '
    '; if (($action != 'editconditions') && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('SetConditions'),1).'
    '; - print '
    '; + print ''; if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id',1); @@ -335,7 +307,7 @@ if ($id > 0) print ''; if (($action != 'editmode') && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('SetMode'),1).'
    '; - print ''; + print ''; if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->mode_reglement_id,'mode_reglement_id'); @@ -350,11 +322,11 @@ if ($id > 0) // Compte bancaire par défaut print ''; print ''; print '
    '; - print $langs->trans('BankAccount'); + print $langs->trans('PaymentBankAccount'); print ''; if (($action != 'editbankaccount') && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
    '; - print ''; + print ''; if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->fk_account,'fk_account',1); @@ -377,7 +349,7 @@ if ($id > 0) print ''.img_edit($langs->trans("Modify")).''; } print ''; - print ''.($object->remise_percent?''.$object->remise_percent.'%':'').''; + print ''.($object->remise_percent?''.$object->remise_percent.'%':'').''; print ''; // Absolute discounts (Discounts-Drawbacks-Rebates) @@ -392,7 +364,7 @@ if ($id > 0) } print ''; print ''; - print ''; + print ''; $amount_discount=$object->getAvailableDiscounts(); if ($amount_discount < 0) dol_print_error($db,$object->error); if ($amount_discount > 0) print ''.price($amount_discount,1,$langs,1,-1,-1,$conf->currency).''; @@ -400,20 +372,6 @@ if ($id > 0) print ''; print ''; - if ($object->client) - { - print ''; - print ''; - print $form->editfieldkey("OutstandingBill",'outstanding_limit',$object->outstanding_limit,$object,$user->rights->societe->creer); - print ''; - $limit_field_type = (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; - print $form->editfieldval("OutstandingBill",'outstanding_limit',$object->outstanding_limit,$object,$user->rights->societe->creer,$limit_field_type,($object->outstanding_limit != '' ? price($object->outstanding_limit) : '')); - //if (empty($object->outstanding_limit)) print $langs->trans("NoLimit"); - - print ''; - print ''; - } - // Multiprice level if (! empty($conf->global->PRODUIT_MULTIPRICES)) { @@ -426,7 +384,7 @@ if ($id > 0) print ''.img_edit($langs->trans("Modify")).''; } print ''; - print ''; + print ''; print $object->price_level; $keyforlabel='PRODUIT_MULTIPRICES_LABEL'.$object->price_level; if (! empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); @@ -434,36 +392,6 @@ if ($id > 0) print ''; } - if ($object->client == 2 || $object->client == 3) - { - // Level of prospect - print ''; - print ''; - print '
    '; - print $langs->trans('ProspectLevel'); - print ''; - if ($action != 'editlevel' && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('Modify'),1).'
    '; - print ''; - if ($action == 'editlevel') - $formcompany->form_prospect_level($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->fk_prospectlevel,'prospect_level_id',1); - else - print $object->getLibProspLevel(); - print ""; - print ''; - - // Status - $object->loadCacheOfProspStatus(); - print ''.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); - print '    
    '; - foreach($object->cacheprospectstatus as $key => $val) - { - $titlealt='default'; - if (! empty($val['code']) && ! in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt=$val['label']; - if ($object->stcomm_id != $val['id']) print ''.img_action($titlealt,$val['code']).''; - } - print '
    '; - } - // Preferred shipping Method if (! empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) { print ''; @@ -472,7 +400,7 @@ if ($id > 0) print ''; if (($action != 'editshipping') && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('SetMode'),1).''; print ''; - print ''; + print ''; if ($action == 'editshipping') { $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->shipping_method_id,'shipping_method_id'); @@ -489,7 +417,7 @@ if ($id > 0) if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { $langs->load("categories"); print '' . $langs->trans("CustomersCategoriesShort") . ''; - print ''; + print ''; print $form->showCategories( $object->id, 'customer', 1 ); print ""; } @@ -511,8 +439,9 @@ if ($id > 0) { $langs->load("members"); $langs->load("users"); - print ''.$langs->trans("LinkedToDolibarrMember").''; - print ''; + + print ''.$langs->trans("LinkedToDolibarrMember").''; + print ''; $adh=new Adherent($db); $result=$adh->fetch('','',$object->id); if ($result > 0) @@ -530,12 +459,48 @@ if ($id > 0) print ""; - + if ($object->client == 2 || $object->client == 3) + { + print '
    '; + + print '
    '; + print ''; + + // Level of prospect + print '"; + print ''; + + // Status + $object->loadCacheOfProspStatus(); + print ''; + print "
    '; + print ''; + print '
    '; + print $langs->trans('ProspectLevel'); + print ''; + if ($action != 'editlevel' && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('Modify'),1).'
    '; + print '
    '; + if ($action == 'editlevel') + $formcompany->form_prospect_level($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->fk_prospectlevel,'prospect_level_id',1); + else + print $object->getLibProspLevel(); + print "
    '.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); + print '     '; + print '
    '; + foreach($object->cacheprospectstatus as $key => $val) + { + $titlealt='default'; + if (! empty($val['code']) && ! in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt=$val['label']; + if ($object->stcomm_id != $val['id']) print ''.img_action($titlealt,$val['code']).''; + } + print '
    "; + } + print '
    '; // Nbre max d'elements des petites listes - $MAXLIST=$conf->global->MAIN_SIZE_SHORTLISTE_LIMIT; + $MAXLIST=$conf->global->MAIN_SIZE_SHORTLIST_LIMIT; // Lien recap $outstandingBills = $object->get_OutstandingBill(); @@ -546,14 +511,33 @@ if ($id > 0) } print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + + // Max outstanding bill + if ($object->client) + { + print ''; + print ''; + print ''; + } + + // Outstanding bill + print ''; print ''; - print ''; + print ''; print ''; + print '
    '.$langs->trans("Summary").''.$langs->trans("ShowCustomerPreview").''.$langs->trans("ShowCustomerPreview").'
    '; + print $form->editfieldkey("OutstandingBill",'outstanding_limit',$object->outstanding_limit,$object,$user->rights->societe->creer); + print ''; + $limit_field_type = (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; + print $form->editfieldval("OutstandingBill",'outstanding_limit',$object->outstanding_limit,$object,$user->rights->societe->creer,$limit_field_type,($object->outstanding_limit != '' ? price($object->outstanding_limit) : '')); + //if (empty($object->outstanding_limit)) print $langs->trans("NoLimit"); + + print '
    '.$langs->trans("CurrentOutstandingBill").''.price($outstandingBills).$warn.''.price($outstandingBills).$warn.'
    '; print '
    '; @@ -588,7 +572,7 @@ if ($id > 0) print ''; print ''; - print ''; print '
    '; + print ''; print ''; @@ -670,7 +654,7 @@ if ($id > 0) print '
    '.$langs->trans("LastPropals",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllPropals").' '.$num.''; print ''; print '
    '.$langs->trans("LastPropals",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllPropals").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').'
    '; print ''; - print ''; print '
    '; + print ''; print ''; - + */ + // Company + /* print ''; - print ''; + print '';*/ // Lin for thirdparty discounts - print ''; print '
    '.$langs->trans("LastCustomerOrders",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' '.$num.''; print ''; //if($num2 > 0) print ''; //else print ''; @@ -739,7 +723,7 @@ if ($id > 0) print '
    '.$langs->trans("LastCustomerOrders",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').''.img_picto($langs->trans("CreateInvoiceForThisCustomer"),'object_bill').''.img_picto($langs->trans("NoOrdersToInvoice"),'object_bill').'
    '; print ''; - print ''; print ''; } $i = 0; @@ -859,7 +843,7 @@ if ($id > 0) print '
    '; + print ''; print ''; @@ -798,7 +782,7 @@ if ($id > 0) print ''; print ''; + print '
    '.$langs->trans("LastSendings",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllSendings").' '.$num.''; print ''; print '
    '.$langs->trans("LastSendings",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllSendings").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').'
    '; - print '
    '.$langs->trans("LastContracts",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllContracts").' '.$num.'
    '.$langs->trans("AllContracts").' '.$num.'
    '; print ''; - print ''; + print ''; print ''; $var=!$var; } @@ -924,7 +908,7 @@ if ($id > 0) print '
    '.$langs->trans("LastInterventions",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllInterventions").' '.$num.'
    '.$langs->trans("LastInterventions",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllInterventions").' '.$num.'
    '; print ''; - print '
    '; + print ''; print ''; diff --git a/htdocs/comm/mailing/list.php b/htdocs/comm/mailing/list.php index 7542782f6e7..bd94dd83f5c 100644 --- a/htdocs/comm/mailing/list.php +++ b/htdocs/comm/mailing/list.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2005-2016 Laurent Destailleur * Copyright (C) 2005-2010 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -125,11 +125,11 @@ if ($result) print ''; print ''; // Title print ''; print ''; if (! $filteremail) print ''; @@ -145,7 +145,7 @@ if ($result) $email=new Mailing($db); - while ($i < min($num,$conf->liste_limit)) + while ($i < min($num,$limit)) { $obj = $db->fetch_object($result); diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index fb7756fc162..2f054374868 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -27,11 +27,13 @@ * along with this program. If not, see . */ + /** * \file htdocs/comm/propal/card.php * \ingroup propale * \brief Page of commercial proposals card and list */ + require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; @@ -141,6 +143,35 @@ if (empty($reshook)) else { if ($object->id > 0) { + if (!empty($conf->global->PROPAL_CLONE_DATE_DELIVERY)) { + //Get difference between old and new delivery date and change lines according to difference + $date_delivery = dol_mktime(12, 0, 0, + GETPOST('date_deliverymonth', 'int'), + GETPOST('date_deliveryday', 'int'), + GETPOST('date_deliveryyear', 'int') + ); + if (!empty($object->date_livraison) && !empty($date_delivery)) + { + //Attempt to get the date without possible hour rounding errors + $old_date_delivery = dol_mktime(12, 0, 0, + dol_print_date($object->date_livraison, '%m'), + dol_print_date($object->date_livraison, '%d'), + dol_print_date($object->date_livraison, '%Y') + ); + //Calculate the difference and apply if necessary + $difference = $date_delivery - $old_date_delivery; + if ($difference != 0) + { + $object->date_livraison = $date_delivery; + foreach ($object->lines as $line) + { + if (isset($line->date_start)) $line->date_start = $line->date_start + $difference; + if (isset($line->date_end)) $line->date_end = $line->date_end + $difference; + } + } + } + } + $result = $object->createFromClone($socid); if ($result > 0) { header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result); @@ -250,9 +281,13 @@ if (empty($reshook)) } // Positionne ref client - else if ($action == 'set_ref_client' && $user->rights->propal->creer) + else if ($action == 'setref_client' && $user->rights->propal->creer) { - $object->set_ref_client($user, $_POST['ref_client']); + $result = $object->set_ref_client($user, GETPOST('ref_client')); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Set incoterm @@ -357,16 +392,6 @@ if (empty($reshook)) $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); } - for($i = 1; $i <= $conf->global->PRODUCT_SHOW_WHEN_CREATE; $i ++) - { - if ($_POST['idprod' . $i]) { - $xid = 'idprod' . $i; - $xqty = 'qty' . $i; - $xremise = 'remise' . $i; - $object->add_product($_POST[$xid], $_POST[$xqty], $_POST[$xremise]); - } - } - // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels, $object); if ($ret < 0) { @@ -620,6 +645,7 @@ if (empty($reshook)) $trigger_name='PROPAL_SENTBYMAIL'; $paramname='id'; $mode='emailfromproposal'; + $trackid='pro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; @@ -1543,9 +1569,10 @@ if ($action == 'create') if (empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print ''; - if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE) || ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) print '
    '.$langs->trans("LastCustomersBills",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllBills").' '.$num.''; print ''; print '
    '.$langs->trans("LastCustomersBills",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllBills").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').'
    '; - print ''; + print ''; print ''; - print ''; + print ''; print '  
    '; if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { + print '
    '; + // For backward compatibility print ''; print ''; @@ -1578,42 +1605,11 @@ if ($action == 'create') } print ''; - if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) - print ''; - print ''; print ''; } - if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) - { - print ''; - } - if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE) || ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) print '
     
    ' . $langs->trans("CreateEmptyPropal") . '
    '; - if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) { - $lib = $langs->trans("ProductsAndServices"); - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - for($i = 1; $i <= $conf->global->PRODUCT_SHOW_WHEN_CREATE; $i ++) { - print ''; - print ''; - print ''; - print ''; - } - print "
    ' . $lib . '' . $langs->trans("Qty") . '' . $langs->trans("ReductionShort") . '
    '; - // multiprix - if ($conf->global->PRODUIT_MULTIPRICES && $soc->price_level) - $form->select_produits('', "idprod" . $i, '', $conf->product->limit_size, $soc->price_level); - else - $form->select_produits('', "idprod" . $i, '', $conf->product->limit_size); - print '%
    "; - } - print '
    '; + if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print '
    '; dol_fiche_end(); @@ -1663,6 +1659,9 @@ if ($action == 'create') // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => // 1), 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)'))); + if (!empty($conf->global->PROPAL_CLONE_DATE_DELIVERY) && !empty($object->date_livraison)) { + $formquestion[] = array('type' => 'date','name' => 'date_delivery','label' => $langs->trans("DeliveryDate"),'value' => $object->date_livraison); + } // Paiement incomplet. On demande si motif = escompte ou autre $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ClonePropal'), $langs->trans('ConfirmClonePropal', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } @@ -1720,23 +1719,77 @@ if ($action == 'create') // Print form confirm print $formconfirm; - print ''; + // Proposal card + $linkback = '' . $langs->trans("BackToList") . ''; - // Ref + + $morehtmlref='
    '; + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->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->propal->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); + + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + + // Ref + /* print ''; + */ // Ref customer + /* print '
    ' . $langs->trans('Ref') . ''; print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); print '
    '; print ''; if ($action != 'refclient' && ! empty($object->brouillon)) print ''; - print ''; - print '
    '; print $langs->trans('RefCustomer') . '' . img_edit($langs->trans('Modify')) . '
    '; + print '
    '; print '
    '; if ($user->rights->propal->creer && $action == 'refclient') { print '
    '; @@ -1750,13 +1803,15 @@ if ($action == 'create') } print '
    ' . $langs->trans('Company') . '' . $soc->getNomUrl(1) . '
    ' . $langs->trans('Discounts') . ''; + print '
    ' . $langs->trans('Discounts') . ''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); else @@ -1792,7 +1847,7 @@ if ($action == 'create') if ($action != 'editdate' && ! empty($object->brouillon)) print 'id . '">' . img_edit($langs->trans('SetDate'), 1) . '
    '; - print '
    '; + print ''; if (! empty($object->brouillon) && $action == 'editdate') { print ''; print ''; @@ -1818,7 +1873,7 @@ if ($action == 'create') if ($action != 'editecheance' && ! empty($object->brouillon)) print 'id . '">' . img_edit($langs->trans('SetConditions'), 1) . '
    '; - print '
    '; + print ''; if (! empty($object->brouillon) && $action == 'editecheance') { print ''; print ''; @@ -1846,7 +1901,7 @@ if ($action == 'create') if ($action != 'editconditions' && ! empty($object->brouillon)) print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetConditions'), 1) . '
    '; - print ''; + print ''; if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { @@ -1859,7 +1914,7 @@ if ($action == 'create') $langs->load('deliveries'); print ''; print $form->editfieldkey($langs->trans('DeliveryDate'), 'date_livraison', $object->date_livraison, $object, $user->rights->propal->creer, 'datepicker'); - print ''; + print ''; print $form->editfieldval($langs->trans('DeliveryDate'), 'date_livraison', $object->date_livraison, $object, $user->rights->propal->creer, 'datepicker'); print ''; print ''; @@ -1874,7 +1929,7 @@ if ($action == 'create') if ($action != 'editavailability' && ! empty($object->brouillon)) print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetAvailability'), 1) . ''; print ''; - print ''; + print ''; if ($action == 'editavailability') { $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'availability_id', 1); } else { @@ -1893,7 +1948,7 @@ if ($action == 'create') if ($action != 'editshippingmethod' && $user->rights->propal->creer) print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).''; print ''; - print ''; + print ''; if ($action == 'editshippingmethod') { $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); } else { @@ -1911,7 +1966,7 @@ if ($action == 'create') if ($action != 'editdemandreason' && ! empty($object->brouillon)) print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetDemandReason'), 1) . ''; print ''; - print ''; + print ''; if ($action == 'editdemandreason') { $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'demand_reason_id', 1); } else { @@ -1922,14 +1977,14 @@ if ($action == 'create') // Payment mode print ''; - print ''; + print ''; print ''; if ($action != 'editmode' && ! empty($object->brouillon)) print ''; print '
    '; print $langs->trans('PaymentMode'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMode'), 1) . '
    '; - print ''; + print ''; if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id'); } else { @@ -1942,14 +1997,14 @@ if ($action == 'create') { // Multicurrency code print ''; - print ''; + print ''; print ''; if ($action != 'editmulticurrencycode' && ! empty($object->brouillon)) print ''; print '
    '; print fieldLabel('Currency','multicurrency_code'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
    '; - print ''; + print ''; if ($action == 'editmulticurrencycode') { $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); } else { @@ -1959,14 +2014,14 @@ if ($action == 'create') // Multicurrency rate print ''; - print ''; + print ''; print ''; if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon)) print ''; print '
    '; print fieldLabel('CurrencyRate','multicurrency_tx'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
    '; - print ''; + print ''; if ($action == 'editmulticurrencyrate') { $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { @@ -1976,6 +2031,7 @@ if ($action == 'create') } // Project + /* if (! empty($conf->projet->enabled)) { $langs->load("projects"); @@ -2009,14 +2065,14 @@ if ($action == 'create') } } print ''; - } + }*/ if ($soc->outstanding_limit) { // Outstanding Bill print ''; print $langs->trans('OutstandingBill'); - print ''; + print ''; print price($soc->get_OutstandingBill()) . ' / '; print price($soc->outstanding_limit, 0, $langs, 1, - 1, - 1, $conf->currency); print ''; @@ -2033,7 +2089,7 @@ if ($action == 'create') if ($action != 'editbankaccount' && $user->rights->propal->creer) print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; print ''; - print ''; + print ''; if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { @@ -2054,7 +2110,7 @@ if ($action == 'create') else print ' '; print ''; print ''; - print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -2067,71 +2123,81 @@ if ($action == 'create') } // Other attributes - $cols = 5; + $cols = 2; include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + print ''; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + { + // Multicurrency Amount HT + print ''; + print ''; + print ''; + + // Multicurrency Amount VAT + print ''; + print ''; + print ''; + + // Multicurrency Amount TTC + print ''; + print ''; + print ''; + } + // Amount HT - print ''; - print ''; - - // Margin Infos - if (! empty($conf->margin->enabled)) - { - $rowspan=4; - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) $rowspan++; - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) $rowspan++; - print ''; - } + print ''; + print ''; print ''; - + // Amount VAT - print ''; - print ''; + print ''; + print ''; print ''; - + // Amount Local Taxes if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } - + // Amount TTC - print ''; - print ''; + print ''; + print ''; print ''; - - if (!empty($conf->multicurrency->enabled)) - { - // Multicurrency Amount HT - print ''; - print ''; - print ''; - - // Multicurrency Amount VAT - print ''; - print ''; - print ''; - - // Multicurrency Amount TTC - print ''; - print ''; - print ''; - } - + // Statut - 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('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)) . '
    ' . $langs->trans('AmountHT') . '' . price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency) . ''; - $formmargin->displayMarginInfos($object); - print '
    ' . $langs->trans('AmountHT') . '' . price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountVAT') . '' . price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountVAT') . '' . price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, '', $langs, 0, - 1, - 1, $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('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . $langs->trans('Status') . '' . $object->getLibStatut(4) . '

    '; + //print '' . $langs->trans('Status') . '' . $object->getLibStatut(4) . ''; + + print ''; + + // Margin Infos + if (! empty($conf->margin->enabled)) + { + $formmargin->displayMarginInfos($object); + } + + print '
    '; + print '
    '; + print '
    '; + + print '

    '; if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; @@ -2326,8 +2392,6 @@ if ($action == 'create') if ($action != 'presend') { print '
    '; - // print '
    '; - // print ''; // ancre /* * Documents generes @@ -2340,7 +2404,7 @@ if ($action == 'create') $var = true; - $somethingshown = $formfile->show_documents('propal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + print $formfile->showdocuments('propal', $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('propal')); @@ -2348,14 +2412,12 @@ if ($action == 'create') 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, 'propal', $socid); - // print '
    '; print '
    '; } @@ -2407,10 +2469,12 @@ if ($action == 'create') 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 = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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='pro'.$object->id; if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php new file mode 100644 index 00000000000..84a7a1a1a1c --- /dev/null +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -0,0 +1,506 @@ + + * 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.'/comm/propal/class/propal.class.php'; + +/** + * API class for orders + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class Proposals extends DolibarrApi +{ + + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid' + ); + + /** + * @var propal $propal {@type propal} + */ + public $propal; + + /** + * Constructor + */ + function __construct() + { + global $db, $conf; + $this->db = $db; + $this->propal = new Propal($this->db); + } + + /** + * Get properties of a commercial proposal object + * + * Return an array with commercial proposal informations + * + * @param int $id ID of commercial proposal + * @return array|mixed data without useless information + * + * @throws RestException + */ + function get($id) + { + if(! DolibarrApiAccess::$user->rights->propal->lire) { + 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); + } + + $this->propal->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->propal); + } + + /** + * List commercial proposals + * + * Get a list of commercial proposals + * + * @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 commercial proposal 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 order objects + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + // case of external user, $thirdpartyid 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 + 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."propal 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('propal', 1).')'; + 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); + } + + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + while ($i < min($num, ($limit <= 0 ? $num : $limit))) + { + $obj = $db->fetch_object($result); + $propal_static = new Propal($db); + if($propal_static->fetch($obj->rowid)) { + $obj_ret[] = parent::_cleanObjectDatas($propal_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve propal list'); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No order found'); + } + return $obj_ret; + } + + /** + * Create commercial proposal object + * + * @param array $request_data Request data + * @return int ID of propal + */ + function post($request_data = NULL) + { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + foreach($request_data as $field => $value) { + $this->propal->$field = $value; + } + /*if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->propal->lines = $lines; + }*/ + if ($this->propal->create(DolibarrApiAccess::$user) <= 0) { + $errormsg = $this->propal->error; + throw new RestException(500, $errormsg ? $errormsg : "Error while creating order"); + } + + return $this->propal->id; + } + + /** + * Get lines of a commercial proposal + * + * @param int $id Id of commercial proposal + * + * @url GET {id}/lines + * + * @return int + */ + function getLines($id) { + if(! DolibarrApiAccess::$user->rights->propal->lire) { + 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); + } + $this->propal->getLinesArray(); + $result = array(); + foreach ($this->propal->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + + /** + * Add a line to given commercial proposal + * + * @param int $id Id of commercial proposal to update + * @param array $request_data Commercial proposal line data + * + * @url POST {id}/lines + * + * @return int + */ + function postLine($id, $request_data = NULL) { + 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); + } + $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, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $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->array_options, + $request_data->fk_unit, + $this->element, + $request_data->id + ); + + if ($updateRes > 0) { + return $this->get($id)->line->rowid; + + } + return false; + } + + /** + * Update a line of given commercial proposal + * + * @param int $id Id of commercial proposal to update + * @param int $lineid Id of line to update + * @param array $request_data Commercial proposal line data + * + * @url PUT {id}/lines/{lineid} + * + * @return object + */ + function putLine($id, $lineid, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Proposal not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->propal->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $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->fk_unit + ); + + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } + + /** + * Delete a line of given commercial proposal + * + * + * @param int $id Id of commercial proposal to update + * @param int $lineid Id of line to delete + * + * @url DELETE {id}/lines/{lineid} + * + * @return int + */ + function delLine($id, $lineid) { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Proposal not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->propal->deleteline($lineid); + if ($updateRes == 1) { + return $this->get($id); + } + return false; + } + + /** + * Update commercial proposal general fields (won't touch lines of commercial proposal) + * + * @param int $id Id of commercial proposal to update + * @param array $request_data Datas + * + * @return int + */ + function put($id, $request_data = NULL) { + if(! DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + + $result = $this->propal->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Proposal not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('propal',$this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + foreach($request_data as $field => $value) { + $this->propal->$field = $value; + } + + if($this->propal->update($id, DolibarrApiAccess::$user,1,'','','update')) + return $this->get($id); + + return false; + } + + /** + * Delete commercial proposal + * + * @param int $id Commercial proposal ID + * + * @return array + */ + function delete($id) + { + if(! DolibarrApiAccess::$user->rights->propal->supprimer) { + 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); + } + + if( ! $this->propal->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete Commercial Proposal : '.$this->propal->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal deleted' + ) + ); + + } + + /** + * Validate a commercial proposal + * + * @param int $id Commercial proposal ID + * @param int $notrigger Use {} + * + * @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->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->valid(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 Commercial Proposal: '.$this->propal->error); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Commercial Proposal validated' + ) + ); + } + + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + function _validate($data) + { + $propal = array(); + foreach (Orders::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $propal[$field] = $data[$field]; + + } + return $propal; + } +} diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 6523688fd8d..dc297e9df12 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -49,7 +49,8 @@ class Propal extends CommonObject 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 $picto='propal'; + /** * {@inheritdoc} */ @@ -388,8 +389,8 @@ class Propal extends CommonObject * @param int $date_end End date of the line * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param string $origin 'order', ... - * @param int $origin_id Id of origin object + * @param string $origin 'order', ... + * @param int $origin_id Id of origin object * @return int >0 if OK, <0 if KO * * @see add_product @@ -453,7 +454,14 @@ class Propal extends CommonObject // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); - $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. + } $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx); @@ -495,6 +503,8 @@ class Propal extends CommonObject $this->line->label=$label; $this->line->desc=$desc; $this->line->qty=$qty; + + $this->line->vat_src_code=$vat_src_code; $this->line->tva_tx=$txtva; $this->line->localtax1_tx=$txlocaltax1; $this->line->localtax2_tx=$txlocaltax2; @@ -628,7 +638,14 @@ class Propal extends CommonObject // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); - $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. + } $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx); $total_ht = $tabprice[0]; @@ -680,6 +697,8 @@ class Propal extends CommonObject $this->line->remise_percent = $remise_percent; $this->line->subprice = $pu; $this->line->info_bits = $info_bits; + + $this->line->vat_src_code = $vat_src_code; $this->line->total_ht = $total_ht; $this->line->total_tva = $total_tva; $this->line->total_localtax1 = $total_localtax1; @@ -778,7 +797,7 @@ class Propal extends CommonObject * this->ref can be set or empty. If empty, we will use "(PROVid)" * * @param User $user User that create - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >=0 if OK */ function create($user, $notrigger=0) @@ -928,7 +947,7 @@ class Propal extends CommonObject for ($i=0;$i<$num;$i++) { - // Reset fk_parent_line for no child products and special product + // Reset fk_parent_line for line that are not child lines or special product if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) { $fk_parent_line = 0; } @@ -944,7 +963,7 @@ class Propal extends CommonObject $this->lines[$i]->remise_percent, 'HT', 0, - 0, + $this->lines[$i]->info_bits, $this->lines[$i]->product_type, $this->lines[$i]->rang, $this->lines[$i]->special_code, @@ -1160,6 +1179,7 @@ class Propal extends CommonObject $clonedObj->ref = $modPropale->getNextValue($objsoc,$clonedObj); // Create clone + $result=$clonedObj->create($user); if ($result < 0) $error++; else @@ -1503,8 +1523,8 @@ class Propal extends CommonObject * Set status to validated * * @param User $user Object user that validate - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers - * @return int <0 if KO, >=0 if OK + * @param int $notrigger 1=Does not execute triggers, 0=execute triggers + * @return int <0 if KO, 0=Nothing done, >=0 if OK */ function valid($user, $notrigger=0) { @@ -1513,98 +1533,110 @@ class Propal extends CommonObject global $conf; $error=0; - $now=dol_now(); - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) + // Protection + if ($this->statut == self::STATUS_VALIDATED) { - $this->db->begin(); + dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); + return 0; + } + + if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate)))) + { + $this->error='ErrorPermissionDenied'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + } - // Numbering module definition - $soc = new Societe($this->db); - $soc->fetch($this->socid); + $now=dol_now(); + + $this->db->begin(); - // Define new ref - if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { - $num = $this->getNextNumRef($soc); - } - else - { - $num = $this->ref; - } - $this->newref = $num; + // Numbering module definition + $soc = new Societe($this->db); + $soc->fetch($this->socid); - $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; - $sql.= " SET ref = '".$num."',"; - $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; - $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; + // Define new ref + if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life + { + $num = $this->getNextNumRef($soc); + } + else + { + $num = $this->ref; + } + $this->newref = $num; - dol_syslog(get_class($this)."::valid", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) - { - dol_print_error($this->db); - $error++; - } + $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; + $sql.= " SET ref = '".$num."',"; + $sql.= " fk_statut = ".self::STATUS_VALIDATED.", date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; + $sql.= " WHERE rowid = ".$this->id." AND fk_statut = ".self::STATUS_DRAFT; - // Trigger calls - if (! $error && ! $notrigger) - { - // Call trigger - $result=$this->call_trigger('PROPAL_VALIDATE',$user); - if ($result < 0) { $error++; } - // End call triggers - } + dol_syslog(get_class($this)."::valid", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + dol_print_error($this->db); + $error++; + } - if (! $error) - { - $this->oldref = $this->ref; + // Trigger calls + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('PROPAL_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { - // Rename of propal directory ($this->ref = old ref, $num = new ref) - // to not lose the linked files - $oldref = dol_sanitizeFileName($this->ref); - $newref = dol_sanitizeFileName($num); - $dirsource = $conf->propal->dir_output.'/'.$oldref; - $dirdest = $conf->propal->dir_output.'/'.$newref; + if (! $error) + { + $this->oldref = $this->ref; - if (file_exists($dirsource)) - { - dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { - dol_syslog("Rename ok"); - // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); - foreach($listoffiles as $fileentry) - { - $dirsource=$fileentry['name']; - $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); - $dirsource=$fileentry['path'].'/'.$dirsource; - $dirdest=$fileentry['path'].'/'.$dirdest; - @rename($dirsource, $dirdest); - } - } - } - } + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) + { + // Rename of propal directory ($this->ref = old ref, $num = new ref) + // to not lose the linked files + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->propal->dir_output.'/'.$oldref; + $dirdest = $conf->propal->dir_output.'/'.$newref; - $this->ref=$num; - $this->brouillon=0; - $this->statut = self::STATUS_VALIDATED; - $this->user_valid_id=$user->id; - $this->datev=$now; + if (file_exists($dirsource)) + { + dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); + if (@rename($dirsource, $dirdest)) + { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -1; - } + $this->ref=$num; + $this->brouillon=0; + $this->statut = self::STATUS_VALIDATED; + $this->user_valid_id=$user->id; + $this->datev=$now; + + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; } } @@ -1614,7 +1646,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param int $date Date - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_date($user, $date, $notrigger=0) @@ -1681,7 +1713,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param int $date_fin_validite End of validity date - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_echeance($user, $date_fin_validite, $notrigger=0) @@ -1741,7 +1773,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param int $date_livraison Delivery date - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ function set_date_livraison($user, $date_livraison, $notrigger=0) @@ -1801,7 +1833,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param int $id Availability id - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_availability($user, $id, $notrigger=0) @@ -1861,7 +1893,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param int $id Input reason id - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_demand_reason($user, $id, $notrigger=0) @@ -1923,7 +1955,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param string $ref_client Customer reference - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ function set_ref_client($user, $ref_client, $notrigger=0) @@ -1986,7 +2018,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param double $remise Amount discount - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ function set_remise_percent($user, $remise, $notrigger=0) @@ -2051,7 +2083,7 @@ class Propal extends CommonObject * * @param User $user Object user that modify * @param double $remise Amount discount - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ function set_remise_absolue($user, $remise, $notrigger=0) @@ -2119,7 +2151,7 @@ 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= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function reopen($user, $statut, $note='', $notrigger=0) @@ -2180,7 +2212,7 @@ 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= execuete triggers + * @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) @@ -2277,7 +2309,7 @@ class Propal extends CommonObject * Class invoiced the Propal * * @param User $user Object user - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 si ko, >0 si ok */ function classifyBilled(User $user, $notrigger=0) @@ -2347,7 +2379,7 @@ class Propal extends CommonObject * Set draft status * * @param User $user Object user that modify - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_draft($user, $notrigger=0) @@ -2575,7 +2607,7 @@ class Propal extends CommonObject * Delete proposal * * @param User $user Object user that delete - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int 1 if ok, otherwise if error */ function delete($user, $notrigger=0) @@ -2698,7 +2730,7 @@ class Propal extends CommonObject * Change the delivery time * * @param int $availability_id Id of new delivery time - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int >0 if OK, <0 if KO */ function availability($availability_id, $notrigger=0) @@ -2765,7 +2797,7 @@ class Propal extends CommonObject * Change source demand * * @param int $demand_reason_id Id of new source demand - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int >0 si ok, <0 si ko */ function demand_reason($demand_reason_id, $notrigger=0) @@ -2890,19 +2922,19 @@ class Propal extends CommonObject /** * Return label of status of proposal (draft, validated, ...) * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto * @return string Label */ function getLibStatut($mode=0) { - return $this->LibStatut($this->statut,$mode); + return $this->LibStatut($this->statut, $mode); } /** * Return label of a status (draft, validated, ...) * * @param int $statut id statut - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @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 */ function LibStatut($statut,$mode=1) @@ -2921,8 +2953,9 @@ class Propal extends CommonObject if ($mode == 2) return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut]; if ($mode == 3) return img_picto($this->labelstatut[$statut], $statuttrans); if ($mode == 4) return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut]; - if ($mode == 5) return ''.$this->labelstatut_short[$statut].' '.img_picto($this->labelstatut_short[$statut],$statuttrans); - } + if ($mode == 5) return ''.$this->labelstatut_short[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); + if ($mode == 6) return ''.$this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); + } /** @@ -3199,47 +3232,67 @@ class Propal extends CommonObject * @param int $withpicto Add picto into link * @param string $option Where point the link ('expedition', 'document', ...) * @param string $get_params Parametres added to url + * @param int $notooltip 1=Disable tooltip * @return string String with URL */ - function getNomUrl($withpicto=0,$option='', $get_params='') + function getNomUrl($withpicto=0,$option='', $get_params='', $notooltip=0) { - global $langs, $conf; + global $langs, $conf, $user; + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + $result=''; - $label = '' . $langs->trans("ShowPropal") . ''; - if (! empty($this->ref)) - $label.= '
    '.$langs->trans('Ref').': '.$this->ref; - if (! empty($this->ref_client)) - $label.= '
    '.$langs->trans('RefCustomer').': '.$this->ref_client; - if (! empty($this->total_ht)) - $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_tva)) - $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_ttc)) - $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; - if ($option == '') { - $link = ''; + if (! empty($this->ref)) + $label.= '
    '.$langs->trans('Ref').': '.$this->ref; + if (! empty($this->ref_client)) + $label.= '
    '.$langs->trans('RefCustomer').': '.$this->ref_client; + if (! empty($this->total_ht)) + $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_ttc)) + $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if ($option == '') { + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + } + if ($option == 'compta') { // deprecated + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$this->id. $get_params; + } + if ($option == 'expedition') { + $url = DOL_URL_ROOT.'/expedition/propal.php?id='.$this->id. $get_params; + } + if ($option == 'document') { + $url = DOL_URL_ROOT.'/comm/propal/document.php?id='.$this->id. $get_params; + } } - if ($option == 'compta') { // deprecated - $link = '
    rights->propal->lire) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowPropal"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; } + + $linkstart = ''; $linkend=''; - $picto='propal'; - - if ($withpicto) - $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + $result.=($linkstart.img_object(($notooltip?'':$label), $this->picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$link.$this->ref.$linkend; + $result.=$linkstart.$this->ref.$linkend; return $result; } @@ -3253,14 +3306,14 @@ class Propal extends CommonObject // For other object, here we call fetch_lines. But fetch_lines does not exists on proposal $sql = 'SELECT pt.rowid, pt.label as custom_label, pt.description, pt.fk_product, pt.fk_remise_except,'; - $sql.= ' pt.qty, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; + $sql.= ' pt.qty, pt.vat_src_code, pt.tva_tx, pt.remise_percent, pt.subprice, pt.info_bits,'; $sql.= ' pt.total_ht, pt.total_tva, pt.total_ttc, pt.fk_product_fournisseur_price as fk_fournprice, pt.buy_price_ht as pa_ht, pt.special_code, pt.localtax1_tx, pt.localtax2_tx,'; $sql.= ' pt.date_start, pt.date_end, pt.product_type, pt.rang, pt.fk_parent_line,'; $sql.= ' pt.fk_unit,'; $sql.= ' p.label as product_label, p.ref, p.fk_product_type, p.rowid as prodid,'; $sql.= ' p.description as product_desc,'; - $sql.= ' p.entity'; - $sql.= ' ,pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc'; + $sql.= ' p.entity,'; + $sql.= ' pt.fk_multicurrency, pt.multicurrency_code, pt.multicurrency_subprice, pt.multicurrency_total_ht, pt.multicurrency_total_tva, pt.multicurrency_total_ttc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'propaldet as pt'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON pt.fk_product=p.rowid'; $sql.= ' WHERE pt.fk_propal = '.$this->id; @@ -3295,6 +3348,8 @@ class Propal extends CommonObject $this->lines[$i]->subprice = $obj->subprice; $this->lines[$i]->fk_remise_except = $obj->fk_remise_except; $this->lines[$i]->remise_percent = $obj->remise_percent; + + $this->lines[$i]->vat_src_code = $obj->vat_src_code; $this->lines[$i]->tva_tx = $obj->tva_tx; $this->lines[$i]->info_bits = $obj->info_bits; $this->lines[$i]->total_ht = $obj->total_ht; @@ -3594,7 +3649,7 @@ class PropaleLigne extends CommonObjectLine /** * Insert object line propal in database * - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function insert($notrigger=0) @@ -3624,7 +3679,11 @@ class PropaleLigne extends CommonObjectLine if (empty($this->fk_fournprice)) $this->fk_fournprice=0; if (! is_numeric($this->qty)) $this->qty = 0; if (empty($this->pa_ht)) $this->pa_ht=0; - + if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0; + if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0; + if (empty($this->multicurrency_total_vat)) $this->multicurrency_total_vat=0; + if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0; + // if buy price not defined, define buyprice as configured in margin admin if ($this->pa_ht == 0 && $pa_ht_isemptystring) { @@ -3646,7 +3705,7 @@ class PropaleLigne extends CommonObjectLine // Insert line into database $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'propaldet'; $sql.= ' (fk_propal, fk_parent_line, label, description, fk_product, product_type,'; - $sql.= ' fk_remise_except, qty, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; + $sql.= ' fk_remise_except, qty, vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; $sql.= ' subprice, remise_percent, '; $sql.= ' info_bits, '; $sql.= ' total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, fk_product_fournisseur_price, buy_price_ht, special_code, rang,'; @@ -3661,6 +3720,7 @@ class PropaleLigne extends CommonObjectLine $sql.= " '".$this->product_type."',"; $sql.= " ".($this->fk_remise_except?"'".$this->fk_remise_except."'":"null").","; $sql.= " ".price2num($this->qty).","; + $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->vat_src_code."'").","; $sql.= " ".price2num($this->tva_tx).","; $sql.= " ".price2num($this->localtax1_tx).","; $sql.= " ".price2num($this->localtax2_tx).","; @@ -3731,9 +3791,10 @@ class PropaleLigne extends CommonObjectLine /** * Delete line in database * + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ - function delete() + function delete($notrigger=0) { global $conf,$user; @@ -3757,13 +3818,16 @@ class PropaleLigne extends CommonObjectLine } } - // Call trigger - $result=$this->call_trigger('LINEPROPAL_DELETE',$user); - if ($result < 0) - { - $this->db->rollback(); - return -1; - } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEPROPAL_DELETE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + } // End call triggers $this->db->commit(); @@ -3830,41 +3894,42 @@ class PropaleLigne extends CommonObjectLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."propaldet SET"; $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= " , label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= " , product_type=".$this->product_type; - $sql.= " , tva_tx='".price2num($this->tva_tx)."'"; - $sql.= " , localtax1_tx=".price2num($this->localtax1_tx); - $sql.= " , localtax2_tx=".price2num($this->localtax2_tx); - $sql.= " , localtax1_type='".$this->localtax1_type."'"; - $sql.= " , localtax2_type='".$this->localtax2_type."'"; - $sql.= " , qty='".price2num($this->qty)."'"; - $sql.= " , subprice=".price2num($this->subprice).""; - $sql.= " , remise_percent=".price2num($this->remise_percent).""; - $sql.= " , price=".price2num($this->price).""; // TODO A virer - $sql.= " , remise=".price2num($this->remise).""; // TODO A virer - $sql.= " , info_bits='".$this->info_bits."'"; + $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); + $sql.= ", product_type=".$this->product_type; + $sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'"; + $sql.= ", tva_tx='".price2num($this->tva_tx)."'"; + $sql.= ", localtax1_tx=".price2num($this->localtax1_tx); + $sql.= ", localtax2_tx=".price2num($this->localtax2_tx); + $sql.= ", localtax1_type='".$this->localtax1_type."'"; + $sql.= ", localtax2_type='".$this->localtax2_type."'"; + $sql.= ", qty='".price2num($this->qty)."'"; + $sql.= ", subprice=".price2num($this->subprice).""; + $sql.= ", remise_percent=".price2num($this->remise_percent).""; + $sql.= ", price=".price2num($this->price).""; // TODO A virer + $sql.= ", remise=".price2num($this->remise).""; // TODO A virer + $sql.= ", info_bits='".$this->info_bits."'"; if (empty($this->skip_update_total)) { - $sql.= " , total_ht=".price2num($this->total_ht).""; - $sql.= " , total_tva=".price2num($this->total_tva).""; - $sql.= " , total_ttc=".price2num($this->total_ttc).""; - $sql.= " , total_localtax1=".price2num($this->total_localtax1).""; - $sql.= " , total_localtax2=".price2num($this->total_localtax2).""; + $sql.= ", total_ht=".price2num($this->total_ht).""; + $sql.= ", total_tva=".price2num($this->total_tva).""; + $sql.= ", total_ttc=".price2num($this->total_ttc).""; + $sql.= ", total_localtax1=".price2num($this->total_localtax1).""; + $sql.= ", total_localtax2=".price2num($this->total_localtax2).""; } - $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null"); - $sql.= " , buy_price_ht=".price2num($this->pa_ht); - if (strlen($this->special_code)) $sql.= " , special_code=".$this->special_code; - $sql.= " , fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); + $sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->fk_fournprice."'":"null"); + $sql.= ", buy_price_ht=".price2num($this->pa_ht); + if (strlen($this->special_code)) $sql.= ", special_code=".$this->special_code; + $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); if (! empty($this->rang)) $sql.= ", rang=".$this->rang; - $sql.= " , date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); - $sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= " , fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); + $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); + $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); // Multicurrency - $sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; + $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; $sql.= " WHERE rowid = ".$this->rowid; diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index 33504a1d27b..f82732a49ff 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -1,6 +1,6 @@ - * Copyright (C) 2005-2009 Destailleur Laurent + * Copyright (C) 2005-2016 Destailleur Laurent * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2015 Philippe Grand * @@ -149,66 +149,61 @@ $formother = new FormOther($db); if ($object->id > 0) { - $head = propal_prepare_head($object); + $head = propal_prepare_head($object); dol_fiche_head($head, 'contact', $langs->trans("Proposal"), 0, 'propal'); - /* - * Propal synthese pour rappel - */ - print ''; - $linkback=''.$langs->trans("BackToList").''; - - // Ref - print ''; - - // Ref client - print ''; - print ''; - - // Customer - print ""; - print ''; - - // Delivery address - if (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT)) + // Proposal card + + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
    '; + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) { - print '
    '; + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->propal->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.=''; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } + $morehtmlref.=''; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); - print "
    '.$langs->trans('Ref').''; - print $form->showrefnav($object,'ref',$linkback,1,'ref','ref',''); - print '
    '; - print ''; - print '
    '; - print $langs->trans('RefCustomer').''; - print '
    '; - print '
    '; - print $object->ref_client; - print '
    ".$langs->trans("Company")."'.$object->thirdparty->getNomUrl(1).'
    '; - print ''; - - if ($action != 'editdelivery_address' && ! empty($object->brouillon)) - print ''; - print '
    '; - print $langs->trans('DeliveryAddress'); - print 'socid.'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetDeliveryAddress'),1).'
    '; - print '
    '; - - if ($action == 'editdelivery_address') - { - $formother->form_address($_SERVER['PHP_SELF'].'?id='.$object->id,$object->fk_delivery_address,$object->socid,'fk_address','propal',$object->id); - } - else - { - $formother->form_address($_SERVER['PHP_SELF'].'?id='.$object->id,$object->fk_delivery_address,$object->socid,'none','propal',$object->id); - } - print '
    "; - - print ''; - - print '
    '; - + dol_fiche_end(); + + // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); foreach($dirtpls as $reldir) diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php index 668b093e7db..9b875e434f7 100644 --- a/htdocs/comm/propal/document.php +++ b/htdocs/comm/propal/document.php @@ -100,39 +100,74 @@ if ($object->id > 0) } - print ''; - - $linkback=''.$langs->trans("BackToList").''; - - // Ref - print ''; - - // Ref client - print ''; - print ''; - - // Customer - print ""; - print ''; - - print ''; - print ''; - - print '
    '.$langs->trans('Ref').''; - print $form->showrefnav($object,'ref',$linkback,1,'ref','ref',''); - print '
    '; - print ''; - print '
    '; - print $langs->trans('RefCustomer').''; - print '
    '; - print '
    '; - print $object->ref_client; - print '
    ".$langs->trans("Company")."'.$object->thirdparty->getNomUrl(1).'
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '; - + // Proposal card + + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
    '; + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->propal->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } + } + $morehtmlref.='
    '; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + + print ''; + + // Files infos + print ''; + print ''; + + print "
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    \n"; + print '
    '; + + + dol_fiche_end(); $modulepart = 'propal'; $permission = $user->rights->propal->creer; + $permtoedit = $user->rights->propal->creer; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/comm/propal/info.php b/htdocs/comm/propal/info.php index d3a3899537b..8415cb8618f 100644 --- a/htdocs/comm/propal/info.php +++ b/htdocs/comm/propal/info.php @@ -54,12 +54,66 @@ dol_fiche_head($head, 'info', $langs->trans('Proposal'), 0, 'propal'); $object->info($object->id); -print '
    '; + +// Proposal card + +$linkback = '' . $langs->trans("BackToList") . ''; + + +$morehtmlref='
    '; +// Ref customer +$morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); +$morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); +// Thirdparty +$morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); +// Project +if (! empty($conf->projet->enabled)) +{ + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->propal->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } +} +$morehtmlref.='
    '; + +dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + +print '
    '; +print '
    '; + +print '
    '; + dol_print_object_info($object); -print '
    '; +print ''; print ''; - +dol_fiche_end(); + llxFooter(); $db->close(); diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index 9c0c0c6a6f9..7e759917604 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -10,6 +10,7 @@ * Copyright (C) 2012 Christophe Battarel * Copyright (C) 2013 Cédric Salvador * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2016 Ferran Marcet * * 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 @@ -78,9 +79,10 @@ $object_statut=GETPOST('propal_statut'); $sall=GETPOST("sall"); $mesg=(GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); + $day=GETPOST("day","int"); -$year=GETPOST("year","int"); $month=GETPOST("month","int"); +$year=GETPOST("year","int"); $limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -159,6 +161,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab } } +$object = new Propal($db); // To be passed as parameter of executeHooks that need + /* * Actions @@ -362,6 +366,7 @@ if ($resql) $param='&socid='.$socid.'&viewstatut='.$viewstatut; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($sall) $param.='&sall='.$sall; if ($month) $param.='&month='.$month; if ($year) $param.='&year='.$year; if ($search_ref) $param.='&search_ref=' .$search_ref; @@ -438,10 +443,12 @@ if ($resql) include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); $formmail->withform=-1; - $formmail->fromtype = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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; + + } if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set { $formmail->trackid='ord'.$object->id; @@ -605,11 +612,11 @@ if ($resql) if (! empty($arrayfields['s.nom']['checked'])) { print ''; - print ''; + print ''; print ''; } if (! empty($arrayfields['s.town']['checked'])) print ''; - if (! empty($arrayfields['s.zip']['checked'])) print ''; + if (! empty($arrayfields['s.zip']['checked'])) print ''; // State if (! empty($arrayfields['state.nom']['checked'])) { @@ -1011,11 +1018,7 @@ if ($resql) $genallowed=$user->rights->propal->lire; $delallowed=$user->rights->propal->lire; - print '
    '; - $paramwithoutshowfiles=preg_replace('/show_files=1&?/','',$param); - $title=$langs->trans("MassFilesArea").' ('.$langs->trans("Hide").')'; - - print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); } else { diff --git a/htdocs/comm/propal/note.php b/htdocs/comm/propal/note.php index 91972673201..d161fe03870 100644 --- a/htdocs/comm/propal/note.php +++ b/htdocs/comm/propal/note.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2004 Eric Seigne * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2013 Florian Henry @@ -45,10 +45,9 @@ $result = restrictedArea($user, 'propale', $id, 'propal'); $object = new Propal($db); - -/******************************************************************************/ -/* Actions */ -/******************************************************************************/ +/* + * Actions + */ $permissionnote=$user->rights->propale->creer; // Used by the include of actions_setnotes.inc.php @@ -56,9 +55,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, -/******************************************************************************/ -/* Affichage fiche */ -/******************************************************************************/ +/* + * View + */ llxHeader('',$langs->trans('Proposal'),'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos'); @@ -70,78 +69,74 @@ if ($id > 0 || ! empty($ref)) $now=dol_now(); - if ($object->fetch($id, $ref)) + if ($object->fetch($id, $ref) > 0) { - $societe = new Societe($db); - if ( $societe->fetch($object->socid) ) + if ($object->fetch_thirdparty() > 0) { - $head = propal_prepare_head($object); + $head = propal_prepare_head($object); dol_fiche_head($head, 'note', $langs->trans('Proposal'), 0, 'propal'); - print ''; - - $linkback = ''.$langs->trans('BackToList').''; - - // Ref - print ''; - - // Ref client - print ''; - print ''; - - // Customer - if ( is_null($object->thirdparty) ) - $object->fetch_thirdparty(); - print ""; - print ''; - - // Discounts - print ''; - - // Date - print ''; - print ''; - - // Date fin propal - print ''; - print ''; - print ''; - - print "
    '.$langs->trans('Ref').''; - print $form->showrefnav($object,'ref',$linkback,1,'ref','ref',''); - print '
    '; - print ''; - print '
    '; - print $langs->trans('RefCustomer').''; - print '
    '; - print '
    '; - print $object->ref_client; - print '
    ".$langs->trans("Company")."'.$object->thirdparty->getNomUrl(1).'
    '.$langs->trans('Discounts').''; - if ($societe->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$societe->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - $absolute_discount=$societe->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('Date').''; - print dol_print_date($object->date,'daytext'); - print '
    '.$langs->trans('DateEndPropal').''; - if ($object->fin_validite) + $cssclass='titlefield'; + //if ($action == 'editnote_public') $cssclass='titlefieldcreate'; + //if ($action == 'editnote_private') $cssclass='titlefieldcreate'; + + + // Proposal card + + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
    '; + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + // Project + if (! empty($conf->projet->enabled)) { - print dol_print_date($object->fin_validite,'daytext'); - if ($object->statut == Propal::STATUS_VALIDATED && $object->fin_validite < ($now - $conf->propal->cloture->warning_delay)) print img_warning($langs->trans("Late")); + $langs->load("projects"); + $morehtmlref.='
    '.$langs->trans('Project') . ' '; + if ($user->rights->propal->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ''; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
    '; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
    '; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (! empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref.=''; + $morehtmlref.=$proj->ref; + $morehtmlref.=''; + } else { + $morehtmlref.=''; + } + } } - else - { - print $langs->trans("Unknown"); - } - print '
    "; - - print '
    '; + $morehtmlref.=''; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + print '
    '; + print '
    '; + include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; + print '
    '; + print ''; + dol_fiche_end(); } } diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index aa5a865dbf2..04c1af11e1d 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -37,7 +37,7 @@ $mode=GETPOST("mode")?GETPOST("mode"):'customer'; if ($mode == 'customer' && ! $user->rights->propale->lire) accessforbidden(); if ($mode == 'supplier' && ! $user->rights->supplier_proposal->lire) accessforbidden(); -$object_statut=GETPOST('propal_statut'); +$object_status=GETPOST('object_status'); $userid=GETPOST('userid','int'); $socid=GETPOST('socid','int'); @@ -58,6 +58,7 @@ $langs->load('orders'); $langs->load('companies'); $langs->load('other'); $langs->load('suppliers'); +$langs->load('supplier_proposal'); /* @@ -91,7 +92,7 @@ dol_mkdir($dir); $stats = new PropaleStats($db, $socid, ($userid>0?$userid:0), $mode); -if ($object_statut != '' && $object_statut >= 0) $stats->where .= ' AND p.fk_statut IN ('.$object_statut.')'; +if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND p.fk_statut IN ('.$object_status.')'; // Build graphic number of object $data = $stats->getNbByMonthWithPrevYear($endyear,$startyear); @@ -265,7 +266,7 @@ print '
    '; print ''; // Status print ''.$langs->trans("Status").''; - $formpropal->selectProposalStatus($object_statut,0,1,1,$mode); + $formpropal->selectProposalStatus(($object_status!=''?$object_status:-1),0,0,1,$mode,'object_status'); print ''; // Year print ''.$langs->trans("Year").''; diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 23a4cd67d37..5cc7fcedf4d 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -279,11 +279,13 @@ if ($socid > 0) print '
    '; print load_fiche_titre($langs->trans("NewGlobalDiscount"),'',''); + + print '
    '; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 13fa38969e5..ddf2e75a8bf 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -64,13 +64,13 @@ $langs->load('deliveries'); $langs->load('sendings'); $langs->load('products'); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (! empty($conf->margin->enabled)) - $langs->load('margins'); +if (! empty($conf->margin->enabled)) $langs->load('margins'); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('orderid', 'int')); $ref = GETPOST('ref', 'alpha'); $socid = GETPOST('socid', 'int'); $action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); $lineid = GETPOST('lineid', 'int'); $origin = GETPOST('origin', 'alpha'); @@ -187,7 +187,7 @@ if (empty($reshook)) // Remove a product line else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->commande->creer) { - $result = $object->deleteline($lineid); + $result = $object->deleteline($user, $lineid); if ($result > 0) { // Define output language @@ -478,19 +478,26 @@ if (empty($reshook)) else if ($action == 'classifyunbilled' && $user->rights->commande->creer) { $ret=$object->classifyUnBilled(); - if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } // Positionne ref commande client - else if ($action == 'set_ref_client' && $user->rights->commande->creer) { - $object->set_ref_client($user, GETPOST('ref_client')); + else if ($action == 'setref_client' && $user->rights->commande->creer) { + $result = $object->set_ref_client($user, GETPOST('ref_client')); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'setremise' && $user->rights->commande->creer) { - $object->set_remise($user, GETPOST('remise')); + $result = $object->set_remise($user, GETPOST('remise')); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'setabsolutediscount' && $user->rights->commande->creer) { @@ -1250,7 +1257,7 @@ if (empty($reshook)) if ($action == 'set_thirdparty' && $user->rights->commande->creer) { $object->fetch($id); - $object->setValueFrom('fk_soc', $socid); + $object->setValueFrom('fk_soc', $socid, '', '', 'date', '', $user, 'ORDER_MODIFY'); header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); exit(); @@ -1268,6 +1275,7 @@ if (empty($reshook)) $trigger_name='ORDER_SENTBYMAIL'; $paramname='id'; $mode='emailfromorder'; + $trackid='ord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; @@ -1453,7 +1461,6 @@ if ($action == 'create' && $user->rights->commande->creer) } $absolute_discount=$soc->getAvailableDiscounts(); - $nbrow = 10; print ''; print ''; @@ -1612,7 +1619,14 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; print ''; print ''; } @@ -1721,38 +1735,6 @@ if ($action == 'create' && $user->rights->commande->creer) print '"; } } - else - { - if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) - { - /* - * Services/produits predefinis - */ - $NBLINES = 8; - - print ''; - } - } print '
    '.$langs->trans("AmountHT").'
    '.$langs->trans("AmountHT").''; print ' '.$langs->trans("Currency".$conf->currency).'
    '.$langs->trans("VAT").'
    '.$langs->trans("VAT").''; print $form->load_tva('tva_tx',GETPOST('tva_tx'),$mysoc,$object); print '
    '; - print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:'')); + $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 '
    ' . $langs->trans('MulticurrencyTotalTTC') . '' . price($objectsrc->multicurrency_total_ttc) . "
    '; - - print ''; - print ''; - print ''; - print ''; - print ''; - for($i = 1; $i <= $NBLINES; $i ++) { - print ''; - print ''; - print ''; - } - - print '
    ' . $langs->trans('ProductsAndServices') . '' . $langs->trans('Qty') . '' . $langs->trans('ReductionShort') . '
    '; - // multiprix - if (! empty($conf->global->PRODUIT_MULTIPRICES)) - print $form->select_produits('', 'idprod' . $i, '', $conf->product->limit_size, $soc->price_level); - else - print $form->select_produits('', 'idprod' . $i, '', $conf->product->limit_size); - print '%
    '; - print '
    '; @@ -1802,16 +1784,12 @@ if ($action == 'create' && $user->rights->commande->creer) $formconfirm = ''; - /* - * Confirmation de la suppression de la commande - */ + // Confirmation to delete if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1); } - /* - * Confirmation de la validation - */ + // Confirmation of validation if ($action == 'validate') { // on verifie si l'objet est en numerotation provisoire @@ -1962,74 +1940,68 @@ if ($action == 'create' && $user->rights->commande->creer) // Print form confirm print $formconfirm; - /* - * Commande - */ - $nbrow = 9; - if (! empty($conf->projet->enabled)) - $nbrow ++; - // Local taxes - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) - $nbrow++; - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0 ) - $nbrow++; - - print ''; + // Order card $linkback = '' . $langs->trans("BackToList") . ''; - // Ref - print ''; - print ''; - print ''; - // Ref commande client - print ''; - print ''; + $morehtmlref='
    '; + // 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); + // 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.='
    '; - // Third party - print ''; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + + print '
    ' . $langs->trans('Ref') . ''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref'); - print '
    '; - print ''; - if ($action != 'refcustomer' && $object->brouillon) - print ''; - print '
    '; - print $langs->trans('RefCustomer') . ''; - print '' . img_edit($langs->trans('Modify')) . '
    '; - print '
    '; - if ($user->rights->commande->creer && $action == 'refcustomer') { - print ''; - print ''; - print ''; - print ''; - print ' '; - print ''; - } else { - print $object->ref_client; - } - print '
    '; - print ''; - print ''; - print ''; - print '
    ' . $langs->trans('Company') . ''; - if (! empty($conf->global->COMMANDE_CHANGE_THIRDPARTY) && $action != 'editthirdparty' && $object->brouillon && $user->rights->commande->creer) - print 'id . '">' . img_edit($langs->trans('SetLinkToThirdParty'), 1) . '
    '; - print '
    '; - if ($action == 'editthirdparty') { - $form->form_thirdparty($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, 'socid','client>0'); - } else { - print $soc->getNomUrl(1, 'compta'); - } - print '
    '; if ($soc->outstanding_limit) { // Outstanding Bill - print ''; @@ -2050,7 +2022,7 @@ if ($action == 'create' && $user->rights->commande->creer) $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - print ''; print '
    '; + print '
    '; print $langs->trans('OutstandingBill'); - print ''; + print ''; print price($soc->get_OutstandingBill()) . ' / '; print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency); print '
    ' . $langs->trans('Discounts') . ''; + print '
    ' . $langs->trans('Discounts') . ''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); else @@ -2085,7 +2057,7 @@ if ($action == 'create' && $user->rights->commande->creer) if ($action != 'editdate' && $object->brouillon) print 'id . '">' . img_edit($langs->trans('SetDate'), 1) . '
    '; - print ''; + print ''; if ($action == 'editdate') { print '
    '; print ''; @@ -2103,14 +2075,14 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; // Delivery date planed - print ''; + print ''; print ''; if ($action != 'editdate_livraison') print ''; print '
    '; print $langs->trans('DateDeliveryPlanned'); print 'id . '">' . img_edit($langs->trans('SetDeliveryDate'), 1) . '
    '; - print ''; + print ''; if ($action == 'editdate_livraison') { print ''; print ''; @@ -2136,7 +2108,7 @@ if ($action == 'create' && $user->rights->commande->creer) if ($action != 'editshippingmethod' && $user->rights->commande->creer) print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).''; print ''; - print ''; + print ''; if ($action == 'editshippingmethod') { $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); } else { @@ -2157,7 +2129,7 @@ if ($action == 'create' && $user->rights->commande->creer) if ($action != 'editwarehouse' && $user->rights->commande->creer) print 'id.'">'.img_edit($langs->trans('SetWarehouse'),1).''; print ''; - print ''; + print ''; if ($action == 'editwarehouse') { $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1); } else { @@ -2168,14 +2140,14 @@ if ($action == 'create' && $user->rights->commande->creer) } // Terms of payment - print ''; + print ''; print ''; if ($action != 'editconditions') print ''; print '
    '; print $langs->trans('PaymentConditionsShort'); print 'id . '">' . img_edit($langs->trans('SetConditions'), 1) . '
    '; - print ''; + print ''; if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id', 1); } else { @@ -2186,14 +2158,14 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; // Mode of payment - print ''; + print ''; print ''; if ($action != 'editmode') print ''; print '
    '; print $langs->trans('PaymentMode'); print 'id . '">' . img_edit($langs->trans('SetMode'), 1) . '
    '; - print ''; + print ''; if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id'); } else { @@ -2206,14 +2178,14 @@ if ($action == 'create' && $user->rights->commande->creer) { // Multicurrency code print ''; - print ''; + print ''; print ''; if ($action != 'editmulticurrencycode' && ! empty($object->brouillon)) print ''; print '
    '; print fieldLabel('Currency','multicurrency_code'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
    '; - print ''; + print ''; if ($action == 'editmulticurrencycode') { $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); } else { @@ -2223,14 +2195,14 @@ if ($action == 'create' && $user->rights->commande->creer) // Multicurrency rate print ''; - print ''; + print ''; print ''; if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon)) print ''; print '
    '; print fieldLabel('CurrencyRate','multicurrency_tx'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
    '; - print ''; + print ''; if ($action == 'editmulticurrencyrate') { $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code); } else { @@ -2247,7 +2219,7 @@ if ($action == 'create' && $user->rights->commande->creer) if ($action != 'editavailability') print 'id . '">' . img_edit($langs->trans('SetAvailability'), 1) . ''; print ''; - print ''; + print ''; if ($action == 'editavailability') { $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'availability_id', 1); } else { @@ -2263,7 +2235,7 @@ if ($action == 'create' && $user->rights->commande->creer) if ($action != 'editdemandreason') print 'id . '">' . img_edit($langs->trans('SetDemandReason'), 1) . ''; print ''; - print ''; + print ''; if ($action == 'editdemandreason') { $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'demand_reason_id', 1); } else { @@ -2280,37 +2252,18 @@ if ($action == 'create' && $user->rights->commande->creer) $totalVolume=$tmparray['volume']; if ($totalWeight || $totalVolume) { - print ''.$langs->trans("CalculatedWeight").' / '.$langs->trans("CalculatedVolume").''; - 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 ''; + 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) - // Project - if (! empty($conf->projet->enabled)) - { - $langs->load('projects'); - print ''; - print ''; - if ($action != 'classify') - print ''; - print '
    '; - print $langs->trans('Project'); - print '' . img_edit($langs->trans('SetProject')) . '
    '; - print ''; - // print "$object->id, $object->socid, $object->fk_project"; - if ($action == 'classify') { - $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1); - } else { - $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0); - } - print ''; - } - // Incoterms if (!empty($conf->incoterm->enabled)) { @@ -2334,16 +2287,6 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; } - // Other attributes - $cols = 3; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - - $rowspan = 4; - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) - $rowspan ++; - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) - $rowspan ++; - // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) { @@ -2364,20 +2307,41 @@ if ($action == 'create' && $user->rights->commande->creer) print ''; } + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print ''; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + { + // Multicurrency Amount HT + print ''; + print ''; + print ''; + + // Multicurrency Amount VAT + print ''; + print ''; + print ''; + + // Multicurrency Amount TTC + print ''; + print ''; + print ''; + } + // Total HT - print ''; + print ''; print ''; - // Margin Infos - if (! empty($conf->margin->enabled)) { - print ''; - } else - print ''; - - print ''; - // Total VAT print ''; @@ -2396,29 +2360,22 @@ if ($action == 'create' && $user->rights->commande->creer) // Total TTC print ''; - if (!empty($conf->multicurrency->enabled)) - { - // Multicurrency Amount HT - print ''; - print ''; - print ''; + // Statut + //print ''; - // Multicurrency Amount VAT - 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('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)) . '
    ' . $langs->trans('AmountHT') . '
    ' . $langs->trans('AmountHT') . '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . ''; - $formmargin->displayMarginInfos($object); - print '
    ' . $langs->trans('AmountVAT') . '' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, 1, '', 1, - 1, - 1, $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)) . '
    ' . $langs->trans('Status') . '' . $object->getLibStatut(4) . '
    ' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '; - // 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 ''; + // Margin Infos + if (! empty($conf->margin->enabled)) { + $formmargin->displayMarginInfos($object); } - // Statut - print '' . $langs->trans('Status') . '' . $object->getLibStatut(4) . ''; - print '
    '; - print "\n"; + print '
    '; + print '
    '; + print '
    '; + + print '

    '; if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; @@ -2625,13 +2582,13 @@ if ($action == 'create' && $user->rights->commande->creer) $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; $genallowed = $user->rights->commande->creer; $delallowed = $user->rights->commande->supprimer; - $somethingshown = $formfile->show_documents('commande', $comref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + print $formfile->showdocuments('commande', $comref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('order')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - + print '
    '; @@ -2691,10 +2648,12 @@ if ($action == 'create' && $user->rights->commande->creer) 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 = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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='ord'.$object->id; if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { diff --git a/htdocs/commande/class/api_deprecated_commande.class.php b/htdocs/commande/class/api_deprecated_commande.class.php index b36ea27f6cc..06da6fa874a 100644 --- a/htdocs/commande/class/api_deprecated_commande.class.php +++ b/htdocs/commande/class/api_deprecated_commande.class.php @@ -23,19 +23,19 @@ * API class for commande object * * @smart-auto-routing false - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} - * + * * @category Api * @package Api - * + * * @deprecated Use Orders instead (defined in api_orders.class.php) */ class CommandeApi 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' @@ -50,7 +50,7 @@ class CommandeApi extends DolibarrApi * Constructor Warning: Deprecated * * @url GET order/ - * + * */ function __construct() { @@ -63,66 +63,66 @@ class CommandeApi extends DolibarrApi * Get properties of a commande object Warning: Deprecated * * Return an array with commande informations - * + * * @param int $id ID of order * @param string $ref Ref of object * @param string $ref_ext External reference of object * @param string $ref_int Internal reference of other object * @return array|mixed data without useless information * - * @url GET order/{id} + * @url GET order/{id} * @throws RestException */ function get($id='',$ref='', $ref_ext='', $ref_int='') - { + { if(! DolibarrApiAccess::$user->rights->commande->lire) { 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); } - + $this->commande->fetchObjectLinked(); return $this->_cleanObjectDatas($this->commande); } /** * List orders Warning: Deprecated - * + * * Get a list of orders - * - * @param int $mode Use this param to filter list + * * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @param string $societe Societe filter field + * @param int $mode Use this param to filter list + * @param string $societe Thirdparty filter field * * @url GET /order/list * @return array Array of order objects */ - function getList($mode=0, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $societe = 0) { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $mode=0, $societe = 0) { global $db, $conf; - + $obj_ret = array(); // case of external user, $societe param is ignored and replaced by user's socid $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe; - + // If the internal user must only see his customers, force searching by him if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; $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."commande 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 - + // Example of use $mode //if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; //if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; @@ -131,13 +131,13 @@ class CommandeApi extends DolibarrApi 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 - + // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - + $nbtotalofrecords = 0; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { @@ -157,12 +157,12 @@ class CommandeApi extends DolibarrApi } $result = $db->query($sql); - + if ($result) { $i=0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $commande_static = new Commande($db); @@ -183,9 +183,9 @@ class CommandeApi extends DolibarrApi /** * List orders for specific thirdparty Warning: Deprecated - * + * * Get a list of orders - * + * * @param int $socid Id of customer * * @url GET /customer/{socid}/order/list @@ -196,14 +196,14 @@ class CommandeApi extends DolibarrApi return getList(0,"s.rowid","ASC",0,0,$socid); } - + /** * Create order object Warning: Deprecated * * @param array $request_data Request datas - * + * * @url POST order/ - * + * * @return int ID of commande */ function post($request_data = NULL) @@ -227,7 +227,7 @@ class CommandeApi extends DolibarrApi if(! $this->commande->create(DolibarrApiAccess::$user) ) { throw new RestException(500, "Error while creating order"); } - + return $this->commande->id; } /** @@ -235,21 +235,21 @@ class CommandeApi extends DolibarrApi * * * @param int $id Id of order - * + * * @url GET order/{id}/line/list - * - * @return int + * + * @return int */ function getLines($id) { if(! DolibarrApiAccess::$user->rights->commande->lire) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -265,22 +265,22 @@ class CommandeApi extends DolibarrApi * * * @param int $id Id of commande to update - * @param array $request_data Orderline data - * + * @param array $request_data Orderline data + * * @url POST order/{id}/line - * - * @return int + * + * @return int */ function postLine($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -325,22 +325,22 @@ class CommandeApi extends DolibarrApi * * @param int $id Id of commande to update * @param int $lineid Id of line to update - * @param array $request_data Orderline data - * + * @param array $request_data Orderline data + * * @url PUT order/{id}/line/{lineid} - * - * @return object + * + * @return object */ function putLine($id, $lineid, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -382,26 +382,26 @@ class CommandeApi extends DolibarrApi * * @param int $id Id of commande to update * @param int $lineid Id of line to delete - * + * * @url DELETE order/{id}/line/{lineid} - * - * @return int + * + * @return int */ function delLine($id, $lineid) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $request_data = (object) $request_data; - $updateRes = $this->commande->deleteline($lineid); + $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user,$lineid); if ($updateRes == 1) { return $this->get($id); } @@ -412,42 +412,42 @@ class CommandeApi extends DolibarrApi * Update order general fields (won't touch lines of order) Warning: Deprecated * * @param int $id Id of commande to update - * @param array $request_data Datas - * + * @param array $request_data Datas + * * @url PUT order/{id} - * - * @return int + * + * @return int */ function put($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach($request_data as $field => $value) { $this->commande->$field = $value; } - + if($this->commande->update($id, DolibarrApiAccess::$user,1,'','','update')) return $this->get($id); - + return false; } - + /** * Delete order Warning: Deprecated * * @param int $id Order ID - * + * * @url DELETE order/{id} - * + * * @return array */ function delete($id) @@ -459,35 +459,35 @@ class CommandeApi extends DolibarrApi 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); } - + if( ! $this->commande->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when delete order : '.$this->commande->error); } - + return array( 'success' => array( 'code' => 200, 'message' => 'Order deleted' ) ); - + } - + /** * Validate an order Warning: Deprecated - * + * * @param int $id Order ID * @param int $idwarehouse Warehouse ID - * + * * @url GET order/{id}/validate * @url POST order/{id}/validate - * + * * @return array - * + * */ function validOrder($id, $idwarehouse=0) { @@ -498,15 +498,15 @@ class CommandeApi extends DolibarrApi 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); } - + if( ! $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse)) { throw new RestException(500, 'Error when validate order'); } - + return array( 'success' => array( 'code' => 200, @@ -514,12 +514,12 @@ class CommandeApi extends DolibarrApi ) ); } - + /** * Validate fields before create or update object - * + * * @param array $data Array with data to verify - * @return array + * @return array * @throws RestException */ function _validate($data) @@ -529,7 +529,7 @@ class CommandeApi extends DolibarrApi if (!isset($data[$field])) throw new RestException(400, "$field field missing"); $commande[$field] = $data[$field]; - + } return $commande; } diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index b4c540d6c57..f000e4ce201 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -1,5 +1,6 @@ + * 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 @@ -22,14 +23,14 @@ /** * API class for orders * - * @access protected + * @access protected * @class DolibarrApiAccess {@requires user,external} */ class Orders 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' @@ -54,78 +55,82 @@ class Orders extends DolibarrApi * Get properties of a commande object * * Return an array with commande informations - * + * * @param int $id ID of order * @return array|mixed data without useless information * * @throws RestException */ function get($id) - { + { if(! DolibarrApiAccess::$user->rights->commande->lire) { 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); } - + $this->commande->fetchObjectLinked(); return $this->_cleanObjectDatas($this->commande); } + + /** * List orders - * - * Get a list of orders - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $societe Societe filter field * - * @return array Array of order objects + * Get a list of orders + * + * @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 orders 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 order objects */ - function index($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $societe = 0) { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { global $db, $conf; - + $obj_ret = array(); - // case of external user, $societe param is ignored and replaced by user's socid - $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe; - + // case of external user, $thirdpartyid 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 - if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; + if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; - $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."commande 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 = "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."commande as t"; - $sql.= ' WHERE s.entity IN ('.getEntity('commande', 1).')'; - 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 - + 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('commande', 1).')'; + 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; } - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + // Add sql filters + if ($sqlfilters) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + 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) @@ -137,12 +142,13 @@ class Orders extends DolibarrApi $sql.= $db->plimit($limit + 1, $offset); } + dol_syslog("API Rest request"); $result = $db->query($sql); - + if ($result) { $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $commande_static = new Commande($db); @@ -189,7 +195,7 @@ class Orders extends DolibarrApi $errormsg = $this->commande->error; throw new RestException(500, $errormsg ? $errormsg : "Error while creating order"); } - + return $this->commande->id; } @@ -197,21 +203,21 @@ class Orders extends DolibarrApi * Get lines of an order * * @param int $id Id of order - * + * * @url GET {id}/lines - * - * @return int + * + * @return int */ function getLines($id) { if(! DolibarrApiAccess::$user->rights->commande->lire) { 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); } @@ -227,22 +233,22 @@ 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 array $request_data Orderline data + * * @url POST {id}/lines - * - * @return int + * + * @return int */ function postLine($id, $request_data = NULL) { 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); } @@ -287,22 +293,22 @@ class Orders extends DolibarrApi * * @param int $id Id of commande 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} - * - * @return object + * + * @return object */ function putLine($id, $lineid, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -345,26 +351,26 @@ class Orders extends DolibarrApi * * @param int $id Id of commande to update * @param int $lineid Id of line to delete - * + * * @url DELETE {id}/lines/{lineid} - * - * @return int + * + * @return int */ function delLine($id, $lineid) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $request_data = (object) $request_data; - $updateRes = $this->commande->deleteline($lineid); + $updateRes = $this->commande->deleteline(DolibarrApiAccess::$user,$lineid); if ($updateRes == 1) { return $this->get($id); } @@ -375,38 +381,38 @@ class Orders extends DolibarrApi * Update order general fields (won't touch lines of order) * * @param int $id Id of commande to update - * @param array $request_data Datas - * - * @return int + * @param array $request_data Datas + * + * @return int */ function put($id, $request_data = NULL) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - + $result = $this->commande->fetch($id); if( ! $result ) { throw new RestException(404, 'Commande not found'); } - + if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach($request_data as $field => $value) { $this->commande->$field = $value; } - - if($this->commande->update($id, DolibarrApiAccess::$user,1,'','','update')) + + if($this->commande->update($id, DolibarrApiAccess::$user, 1, '', '', 'update')) return $this->get($id); - + return false; } - + /** * Delete order * * @param int $id Order ID - * + * * @return array */ function delete($id) @@ -418,41 +424,43 @@ class Orders extends DolibarrApi 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); } - + if( ! $this->commande->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when delete order : '.$this->commande->error); } - + return array( 'success' => array( 'code' => 200, 'message' => 'Order deleted' ) ); - + } - + /** * Validate an order - * + * * @param int $id Order ID * @param int $idwarehouse Warehouse 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 * { - * "idwarehouse": 0 + * "idwarehouse": 0, + * "notrigger": 0 * } */ - function validate($id, $idwarehouse=0) + function validate($id, $idwarehouse=0, $notrigger=0) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); @@ -461,15 +469,19 @@ class Orders extends DolibarrApi 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); } - - if( ! $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse)) { - throw new RestException(500, 'Error when validate order'); - } - + + $result = $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse, $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 Order: '.$this->commande->error); + } + return array( 'success' => array( 'code' => 200, @@ -477,12 +489,12 @@ class Orders extends DolibarrApi ) ); } - + /** * Validate fields before create or update object - * + * * @param array $data Array with data to verify - * @return array + * @return array * @throws RestException */ function _validate($data) @@ -492,7 +504,7 @@ class Orders extends DolibarrApi if (!isset($data[$field])) throw new RestException(400, "$field field missing"); $commande[$field] = $data[$field]; - + } return $commande; } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 22f2c1b7113..0ae5ab4b217 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -47,6 +47,7 @@ class Commande extends CommonOrder 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 $picto = 'order'; /** * {@inheritdoc} @@ -258,8 +259,8 @@ class Commande extends CommonOrder * * @param User $user User making status change * @param int $idwarehouse Id of warehouse to use for stock decrease - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers - * @return int <=0 if OK, >0 if KO + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int <=0 if OK, 0=Nothing done, >0 if KO */ function valid($user, $idwarehouse=0, $notrigger=0) { @@ -271,14 +272,14 @@ class Commande extends CommonOrder // Protection if ($this->statut == self::STATUS_VALIDATED) { - dol_syslog(get_class($this)."::valid action abandonned: no draft status", LOG_WARNING); + dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); return 0; } if (! ((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)))) { - $this->error='ErrorPermissionDenied'; + $this->error='NotEnoughPermissions'; dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -1; } @@ -809,11 +810,11 @@ class Commande extends CommonOrder for ($i=0;$i<$num;$i++) { $line = $this->lines[$i]; - + // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE); // convert recursively array into object. if (! is_object($line)) $line = (object) $line; - + // 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; @@ -905,10 +906,10 @@ class Commande extends CommonOrder } } } - + $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'"; - + $resqlcontact = $this->db->query($sqlcontact); if ($resqlcontact) { @@ -1219,7 +1220,7 @@ class Commande extends CommonOrder */ function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $info_bits=0, $fk_remise_except=0, $price_base_type='HT', $pu_ttc=0, $date_start='', $date_end='', $type=0, $rang=-1, $special_code=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='',$array_options=0, $fk_unit=null, $origin='', $origin_id=0) { - global $mysoc, $conf, $langs; + 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); @@ -1284,7 +1285,14 @@ class Commande extends CommonOrder // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); - $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. + } $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx); @@ -1326,6 +1334,8 @@ class Commande extends CommonOrder $this->line->label=$label; $this->line->desc=$desc; $this->line->qty=$qty; + + $this->line->vat_src_code=$vat_src_code; $this->line->tva_tx=$txtva; $this->line->localtax1_tx=$txlocaltax1; $this->line->localtax2_tx=$txlocaltax2; @@ -1372,7 +1382,7 @@ class Commande extends CommonOrder $this->line->array_options=$array_options; } - $result=$this->line->insert(); + $result=$this->line->insert($user); if ($result > 0) { // Reorder if child line @@ -1726,7 +1736,7 @@ class Commande extends CommonOrder { $this->lines=array(); - $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.tva_tx,'; + $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.product_type, l.fk_commande, l.label as custom_label, l.description, l.price, l.qty, l.vat_src_code, l.tva_tx,'; $sql.= ' l.localtax1_tx, l.localtax2_tx, l.fk_remise_except, l.remise_percent, l.subprice, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht, l.rang, l.info_bits, l.special_code,'; $sql.= ' l.total_ht, l.total_ttc, l.total_tva, l.total_localtax1, l.total_localtax2, l.date_start, l.date_end,'; $sql.= ' l.fk_unit,'; @@ -1761,6 +1771,8 @@ class Commande extends CommonOrder $line->description = $objp->description; // Description line $line->product_type = $objp->product_type; $line->qty = $objp->qty; + + $line->vat_src_code = $objp->vat_src_code; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; $line->localtax2_tx = $objp->localtax2_tx; @@ -1971,10 +1983,11 @@ class Commande extends CommonOrder /** * Delete an order line * + * @param User $user User object * @param int $lineid Id of line to delete * @return int >0 if OK, 0 if nothing to do, <0 if KO */ - function deleteline($lineid) + function deleteline($user=null, $lineid=0) { if ($this->statut == self::STATUS_DRAFT) @@ -2001,7 +2014,7 @@ class Commande extends CommonOrder // For triggers $line->fetch($lineid); - if ($line->delete() > 0) + if ($line->delete($user) > 0) { $result=$this->update_price(1); @@ -2048,7 +2061,7 @@ class Commande extends CommonOrder * * @param User $user User qui positionne la remise * @param float $remise Discount (percent) - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_remise($user, $remise, $notrigger=0) @@ -2114,7 +2127,7 @@ class Commande extends CommonOrder * * @param User $user User qui positionne la remise * @param float $remise Discount - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_remise_absolue($user, $remise, $notrigger=0) @@ -2180,7 +2193,7 @@ class Commande extends CommonOrder * * @param User $user Object user making change * @param int $date Date - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_date($user, $date, $notrigger=0) @@ -2244,7 +2257,7 @@ class Commande extends CommonOrder * * @param User $user Objet utilisateur qui modifie * @param int $date_livraison Date de livraison - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 si ko, >0 si ok */ function set_date_livraison($user, $date_livraison, $notrigger=0) @@ -2380,13 +2393,13 @@ class Commande extends CommonOrder * Update delivery delay * * @param int $availability_id Id du nouveau mode - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int >0 if OK, <0 if KO */ function availability($availability_id, $notrigger=0) { global $user; - + dol_syslog('Commande::availability('.$availability_id.')'); if ($this->statut >= self::STATUS_DRAFT) { @@ -2450,13 +2463,13 @@ class Commande extends CommonOrder * Update order demand_reason * * @param int $demand_reason_id Id of new demand - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int >0 if ok, <0 if ko */ function demand_reason($demand_reason_id, $notrigger=0) { global $user; - + dol_syslog('Commande::demand_reason('.$demand_reason_id.')'); if ($this->statut >= self::STATUS_DRAFT) { @@ -2521,7 +2534,7 @@ class Commande extends CommonOrder * * @param User $user User that make change * @param string $ref_client Customer ref - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_ref_client($user, $ref_client, $notrigger=0) @@ -2557,7 +2570,6 @@ class Commande extends CommonOrder if ($result < 0) $error++; // End call triggers } - if (! $error) { $this->db->commit(); @@ -2584,7 +2596,7 @@ class Commande extends CommonOrder * Classify the order as invoiced * * @param User $user Object user making the change - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function classifyBilled(User $user, $notrigger=0) @@ -2740,7 +2752,7 @@ class Commande extends CommonOrder */ function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0.0,$txlocaltax2=0.0, $price_base_type='HT', $info_bits=0, $date_start='', $date_end='', $type=0, $fk_parent_line=0, $skip_update_total=0, $fk_fournprice=null, $pa_ht=0, $label='', $special_code=0, $array_options=0, $fk_unit=null) { - global $conf, $mysoc, $langs; + global $conf, $mysoc, $langs, $user; dol_syslog(get_class($this)."::updateline id=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, date_start=$date_start, date_end=$date_end, type=$type, fk_parent_line=$fk_parent_line, pa_ht=$pa_ht, special_code=$special_code"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -2773,7 +2785,14 @@ class Commande extends CommonOrder // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc); - $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. + } $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx); @@ -2847,26 +2866,28 @@ class Commande extends CommonOrder $this->line->label=$label; $this->line->desc=$desc; $this->line->qty=$qty; - $this->line->tva_tx=$txtva; - $this->line->localtax1_tx=$txlocaltax1; - $this->line->localtax2_tx=$txlocaltax2; + + $this->line->vat_src_code = $vat_src_code; + $this->line->tva_tx = $txtva; + $this->line->localtax1_tx = $txlocaltax1; + $this->line->localtax2_tx = $txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; - $this->line->remise_percent=$remise_percent; - $this->line->subprice=$subprice; - $this->line->info_bits=$info_bits; - $this->line->special_code=$special_code; - $this->line->total_ht=$total_ht; - $this->line->total_tva=$total_tva; - $this->line->total_localtax1=$total_localtax1; - $this->line->total_localtax2=$total_localtax2; - $this->line->total_ttc=$total_ttc; - $this->line->date_start=$date_start; - $this->line->date_end=$date_end; - $this->line->product_type=$type; - $this->line->fk_parent_line=$fk_parent_line; + $this->line->remise_percent = $remise_percent; + $this->line->subprice = $subprice; + $this->line->info_bits = $info_bits; + $this->line->special_code = $special_code; + $this->line->total_ht = $total_ht; + $this->line->total_tva = $total_tva; + $this->line->total_localtax1= $total_localtax1; + $this->line->total_localtax2= $total_localtax2; + $this->line->total_ttc = $total_ttc; + $this->line->date_start = $date_start; + $this->line->date_end = $date_end; + $this->line->product_type = $type; + $this->line->fk_parent_line = $fk_parent_line; $this->line->skip_update_total=$skip_update_total; - $this->line->fk_unit=$fk_unit; + $this->line->fk_unit = $fk_unit; $this->line->fk_fournprice = $fk_fournprice; $this->line->pa_ht = $pa_ht; @@ -2885,7 +2906,7 @@ class Commande extends CommonOrder $this->line->array_options=$array_options; } - $result=$this->line->update(); + $result=$this->line->update($user); if ($result > 0) { // Reorder if child line @@ -3045,7 +3066,7 @@ class Commande extends CommonOrder * Delete the customer order * * @param User $user User object - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <=0 if KO, >0 if OK */ function delete($user, $notrigger=0) @@ -3281,7 +3302,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraftShort'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated'),'statut1').' '.$langs->trans('StatusOrderValidatedShort').$billedtext; if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSent'),'statut3').' '.$langs->trans('StatusOrderSentShort').$billedtext; - if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut7').' '.$langs->trans('StatusOrderToBillShort'); + if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBillShort'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDeliveredShort'); } @@ -3291,7 +3312,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1'); if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3'); - if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut7'); + if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6'); if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6'); } @@ -3301,7 +3322,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_DRAFT) return img_picto($langs->trans('StatusOrderDraft'),'statut0').' '.$langs->trans('StatusOrderDraft'); if ($statut==self::STATUS_VALIDATED) return img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1').' '.$langs->trans('StatusOrderValidated').$billedtext; if ($statut==self::STATUS_ACCEPTED) return img_picto($langs->trans('StatusOrderSentShort').$billedtext,'statut3').' '.$langs->trans('StatusOrderSent').$billedtext; - if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut7').' '.$langs->trans('StatusOrderToBill'); + if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderToBill'),'statut4').' '.$langs->trans('StatusOrderToBill'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderProcessedShort').$billedtext,'statut6').' '.$langs->trans('StatusOrderProcessed').$billedtext; if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return img_picto($langs->trans('StatusOrderDelivered'),'statut6').' '.$langs->trans('StatusOrderDelivered'); } @@ -3311,7 +3332,7 @@ class Commande extends CommonOrder if ($statut==self::STATUS_DRAFT) return ''.$langs->trans('StatusOrderDraftShort').' '.img_picto($langs->trans('StatusOrderDraft'),'statut0'); if ($statut==self::STATUS_VALIDATED) return ''.$langs->trans('StatusOrderValidatedShort').$billedtext.' '.img_picto($langs->trans('StatusOrderValidated').$billedtext,'statut1'); if ($statut==self::STATUS_ACCEPTED) return ''.$langs->trans('StatusOrderSentShort').$billedtext.' '.img_picto($langs->trans('StatusOrderSent').$billedtext,'statut3'); - if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderToBillShort').' '.img_picto($langs->trans('StatusOrderToBill'),'statut7'); + if ($statut==self::STATUS_CLOSED && (! $billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderToBillShort').' '.img_picto($langs->trans('StatusOrderToBill'),'statut4'); if ($statut==self::STATUS_CLOSED && ($billed && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderProcessedShort').$billedtext.' '.img_picto($langs->trans('StatusOrderProcessed').$billedtext,'statut6'); if ($statut==self::STATUS_CLOSED && (! empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT))) return ''.$langs->trans('StatusOrderDeliveredShort').' '.img_picto($langs->trans('StatusOrderDelivered'),'statut6'); } @@ -3324,13 +3345,16 @@ class Commande extends CommonOrder * @param int $withpicto Add picto into link * @param int $option Where point the link (0=> main card, 1,2 => shipment) * @param int $max Max length to show - * @param int $short Use short labels + * @param int $short ??? + * @param int $notooltip 1=Disable tooltip * @return string String with URL */ - function getNomUrl($withpicto=0,$option=0,$max=0,$short=0) + function getNomUrl($withpicto=0,$option=0,$max=0,$short=0,$notooltip=0) { global $conf, $langs, $user; + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + $result=''; if (! empty($conf->expedition->enabled) && ($option == 1 || $option == 2)) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id; @@ -3343,30 +3367,36 @@ class Commande extends CommonOrder if ($user->rights->commande->lire) { $label = ''.$langs->trans("ShowOrder").''; - if (!empty($this->ref)) { - $label .= '
    '.$langs->trans('Ref').': '.$this->ref; - } - if (!empty($this->ref_client)) { - $label .= '
    '.$langs->trans('RefCustomer').': '.$this->ref_client; - } + $label .= '
    '.$langs->trans('Ref').': '.$this->ref; + $label .= '
    '.$langs->trans('RefCustomer').': '.($this->ref_customer ? $this->ref_customer : $this->ref_client); if (!empty($this->total_ht)) { - $label .= '
    '.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, - $conf->currency); + $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); + $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); } if (!empty($this->total_ttc)) { - $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, - $conf->currency); + $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); } } - $linkstart = ''; + $linkclose=''; + if (empty($notooltip) && $user->rights->commande->lire) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowOrder"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } + + $linkstart = ''; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object($label, $picto, 'class="classfortooltip"').$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; @@ -3571,9 +3601,9 @@ class Commande extends CommonOrder } /** - * Create a document onto disk accordign to template module. + * Create a document onto disk according to template module. * - * @param string $modele Force le mnodele a utiliser ('' to not force) + * @param string $modele Force template to use ('' to not force) * @param Translate $outputlangs objet lang a utiliser pour traduction * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description @@ -3805,9 +3835,11 @@ class OrderLine extends CommonOrderLine /** * Delete line in database * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 si ko, >0 si ok */ - function delete() + function delete($user=null, $notrigger=0) { global $conf, $user, $langs; @@ -3833,10 +3865,13 @@ class OrderLine extends CommonOrderLine } } - // Call trigger - $result=$this->call_trigger('LINEORDER_DELETE',$user); - if ($result < 0) $error++; - // End call triggers + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINEORDER_DELETE',$user); + if ($result < 0) $error++; + // End call triggers + } if (!$error) { $this->db->commit(); @@ -3861,12 +3896,13 @@ class OrderLine extends CommonOrderLine /** * Insert line into database * + * @param User $user User that modify * @param int $notrigger 1 = disable triggers * @return int <0 if KO, >0 if OK */ - function insert($notrigger=0) + function insert($user=null, $notrigger=0) { - global $langs, $conf, $user; + global $langs, $conf; $error=0; @@ -3911,7 +3947,7 @@ class OrderLine extends CommonOrderLine // Insertion dans base de la ligne $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'commandedet'; $sql.= ' (fk_commande, fk_parent_line, label, description, qty, '; - $sql.= ' tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; + $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; $sql.= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,'; $sql.= ' special_code, rang, fk_product_fournisseur_price, buy_price_ht,'; $sql.= ' info_bits, total_ht, total_tva, total_localtax1, total_localtax2, total_ttc, date_start, date_end,'; @@ -3923,6 +3959,7 @@ class OrderLine extends CommonOrderLine $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; $sql.= " '".$this->db->escape($this->desc)."',"; $sql.= " '".price2num($this->qty)."',"; + $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->vat_src_code."'").","; $sql.= " '".price2num($this->tva_tx)."',"; $sql.= " '".price2num($this->localtax1_tx)."',"; $sql.= " '".price2num($this->localtax2_tx)."',"; @@ -4004,12 +4041,13 @@ class OrderLine extends CommonOrderLine /** * Update the line object into db * + * @param User $user User that modify * @param int $notrigger 1 = disable triggers * @return int <0 si ko, >0 si ok */ - function update($notrigger=0) + function update($user=null, $notrigger=0) { - global $conf,$langs,$user; + global $conf,$langs; $error=0; diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index 6b96940df98..a05a6e0061d 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -121,6 +121,7 @@ if ($id > 0 || ! empty($ref)) $modulepart = 'commande'; $permission = $user->rights->commande->creer; + $permtoedit = $user->rights->commande->creer; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 5625b153ab1..87a95062323 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -35,10 +35,12 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/discount.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/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $langs->load('orders'); @@ -76,6 +78,7 @@ $search_sale=GETPOST('search_sale','int'); $search_total_ht=GETPOST('search_total_ht','alpha'); $optioncss = GETPOST('optioncss','alpha'); $billed = GETPOST('billed','int'); +$viewstatut=GETPOST('viewstatut'); // Security check $id = (GETPOST('orderid')?GETPOST('orderid','int'):GETPOST('id','int')); @@ -95,13 +98,11 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield='c.ref'; if (! $sortorder) $sortorder='DESC'; -$viewstatut=GETPOST('viewstatut'); - -// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +// Initialize technical object to manage context to save list fields $contextpage='orderlist'; // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('orderlist')); +$hookmanager->initHooks(array($contextpage)); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -154,47 +155,49 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab */ if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - -// Purge search criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers -{ - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_product_category=''; - $search_ref=''; - $search_ref_customer=''; - $search_company=''; - $search_town=''; - $search_zip=""; - $search_state=""; - $search_type=''; - $search_country=''; - $search_type_thirdparty=''; - $search_total_ht=''; - $search_total_vat=''; - $search_total_ttc=''; - $orderyear=''; - $ordermonth=''; - $orderday=''; - $deliveryday=''; - $deliverymonth=''; - $deliveryyear=''; - $viewstatut=''; - $billed=''; - $toselect=''; - $search_array_options=array(); -} - if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers + { + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_product_category=''; + $search_ref=''; + $search_ref_customer=''; + $search_company=''; + $search_town=''; + $search_zip=""; + $search_state=""; + $search_type=''; + $search_country=''; + $search_type_thirdparty=''; + $search_total_ht=''; + $search_total_vat=''; + $search_total_ttc=''; + $orderyear=''; + $ordermonth=''; + $orderday=''; + $deliveryday=''; + $deliverymonth=''; + $deliveryyear=''; + $viewstatut=''; + $billed=''; + $toselect=''; + $search_array_options=array(); + } + + // Mass actions $objectclass='Commande'; $objectlabel='Orders'; $permtoread = $user->rights->commande->lire; @@ -204,6 +207,225 @@ if (empty($reshook)) } +if ($massaction == 'confirm_createbills') { + + $orders = GETPOST('toselect'); + $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); + $validate_invoices = GETPOST('valdate_invoices', 'int'); + + $TFact = array(); + $TFactThird = array(); + + $nb_bills_created = 0; + + $db->begin(); + + foreach($orders as $id_order) { + + $cmd = new Commande($db); + if($cmd->fetch($id_order) <= 0) continue; + + $object = new Facture($db); + if(!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $object = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + else { + + $object->socid = $cmd->socid; + $object->type = Facture::TYPE_STANDARD; + $object->cond_reglement_id = $cmd->cond_reglement_id; + $object->mode_reglement_id = $cmd->mode_reglement_id; + $object->fk_project = $cmd->fk_project; + + $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + if (empty($datefacture)) + { + $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); + } + + $object->date = $datefacture; + $object->origin = 'commande'; + $object->origin_id = $id_order; + + $res = $object->create($user); + + if($res > 0) $nb_bills_created++; + + } + + if($object->id > 0) { + + $db->begin(); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql.= "fk_source"; + $sql.= ", sourcetype"; + $sql.= ", fk_target"; + $sql.= ", targettype"; + $sql.= ") VALUES ("; + $sql.= $id_order; + $sql.= ", '".$object->origin."'"; + $sql.= ", ".$object->id; + $sql.= ", '".$object->element."'"; + $sql.= ")"; + + if ($db->query($sql)) + { + $db->commit(); + } + else + { + $db->rollback(); + } + + $lines = $cmd->lines; + if (empty($lines) && method_exists($cmd, 'fetch_lines')) + { + $cmd->fetch_lines(); + $lines = $cmd->lines; + } + + $fk_parent_line=0; + $num=count($lines); + + for ($i=0;$i<$num;$i++) + { + $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle); + if ($lines[$i]->subprice < 0) + { + // Negative line, we create a discount line + $discount = new DiscountAbsolute($db); + $discount->fk_soc=$object->socid; + $discount->amount_ht=abs($lines[$i]->total_ht); + $discount->amount_tva=abs($lines[$i]->total_tva); + $discount->amount_ttc=abs($lines[$i]->total_ttc); + $discount->tva_tx=$lines[$i]->tva_tx; + $discount->fk_user=$user->id; + $discount->description=$desc; + $discountid=$discount->create($user); + if ($discountid > 0) + { + $result=$object->insert_discount($discountid); + //$result=$discount->link_to_invoice($lineid,$id); + } + else + { + setEventMessages($discount->error, $discount->errors, 'errors'); + $error++; + break; + } + } + else + { + // Positive line + $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); + // Date start + $date_start=false; + if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start; + //Date end + $date_end=false; + if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end; + // Reset fk_parent_line for no child products and special product + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) + { + $fk_parent_line = 0; + } + $result = $object->addline( + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $lines[$i]->tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $date_start, + $date_end, + 0, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $product_type, + $ii, + $lines[$i]->special_code, + $object->origin, + $lines[$i]->rowid, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $lines[$i]->label + ); + if ($result > 0) + { + $lineid=$result; + } + else + { + $lineid=0; + $error++; + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $lines[$i]->product_type == 9) + { + $fk_parent_line = $result; + } + } + } + + } + + $cmd->classifyBilled($user); + + if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $object; + else $TFact[$object->id] = $object; + } + + // Build doc with all invoices + $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; + $toselect = array(); + + if(!empty($validate_invoices)) { + + $massaction = $action = 'builddoc'; + + foreach($TAllFact as &$object) { + $object->validate($user); + $toselect[] = $object->id; // For builddoc action + + // Fac builddoc + $upload_dir = $conf->facture->dir_output; + $permissioncreate=$user->rights->facture->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + } + + $objectclass='Facture'; + $objectlabel='Invoice'; + $permtoread = $user->rights->facture->lire; + $permtodelete = $user->rights->facture->supprimer; + $uploaddir = $conf->facture->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + + } + + if (! $error) + { + $db->commit(); + setEventMessage($langs->trans('BillCreated', $nb_bills_created)); + } + else + { + $db->rollback(); + $action='create'; + $_GET["origin"]=$_POST["origin"]; + $_GET["originid"]=$_POST["originid"]; + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } + +} /* @@ -317,7 +539,6 @@ if ($search_company) $sql .= natural_search('s.nom', $search_company); if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; if ($search_total_ht != '') $sql.= natural_search('c.total_ht', $search_total_ht, 1); - // Add where from extra fields foreach ($search_array_options as $key => $val) { @@ -386,6 +607,7 @@ if ($resql) $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($sall) $param.='&sall='.$sall; if ($socid > 0) $param.='&socid='.$socid; if ($viewstatut != '') $param.='&viewstatut='.$viewstatut; if ($orderday) $param.='&orderday='.$orderday; @@ -404,6 +626,7 @@ if ($resql) if ($search_total_ttc != '') $param.='&search_total_ttc='.$search_total_ttc; if ($show_files) $param.='&show_files=' .$show_files; if ($optioncss != '') $param.='&optioncss='.$optioncss; + if ($billed != '') $param.='&billed='.$billed; // Add $param from extra fields foreach ($search_array_options as $key => $val) { @@ -417,11 +640,12 @@ if ($resql) 'presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"), ); + if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->commande->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); - if ($massaction == 'presend') $arrayofmassactions=array(); + if ($massaction == 'presend' || $massaction == 'createbills') $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - // Lignes des champs de filtre + // Lines of title fields print ''; if ($optioncss != '') print ''; print ''; @@ -470,10 +694,12 @@ if ($resql) include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); $formmail->withform=-1; - $formmail->fromtype = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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; + + } if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set { $formmail->trackid='ord'.$object->id; @@ -528,6 +754,46 @@ if ($resql) dol_fiche_end(); } + elseif ($massaction == 'createbills') + { + //var_dump($_REQUEST); + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + print $langs->trans('DateInvoice'); + print ''; + print $form->select_date('', '', '', '', '', '', 1, 1); + print '
    '; + print $langs->trans('CreateOneBillByThird'); + print ''; + print $form->selectyesno('createbills_onebythird', '', 1); + print '
    '; + print $langs->trans('ValidateInvoices'); + print ''; + print $form->selectyesno('valdate_invoices', 1, 1); + print '
    '; + + print '
    '; + print '
    '; + print ' '; + print ''; + print '
    '; + print '
    '; + + } if ($sall) { @@ -642,9 +908,9 @@ if ($resql) print ''; } // Town - if (! empty($arrayfields['s.town']['checked'])) print ''; + if (! empty($arrayfields['s.town']['checked'])) print ''; // Zip - if (! empty($arrayfields['s.zip']['checked'])) print ''; + if (! empty($arrayfields['s.zip']['checked'])) print ''; // State if (! empty($arrayfields['state.nom']['checked'])) { @@ -687,14 +953,14 @@ if ($resql) { // Amount print ''; - print ''; + print ''; print ''; } if (! empty($arrayfields['c.total_vat']['checked'])) { // Amount print ''; - print ''; + print ''; print ''; } if (! empty($arrayfields['c.total_ttc']['checked'])) @@ -748,11 +1014,11 @@ if ($resql) { print ''; $liststatus=array( - '0'=>$langs->trans("StatusOrderDraftShort"), - '1'=>$langs->trans("StatusOrderValidated"), - '2'=>$langs->trans("StatusOrderSentShort"), - '3'=>$langs->trans("StatusOrderDelivered"), - '-1'=>$langs->trans("StatusOrderCanceledShort") + Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraftShort"), + Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), + Commande::STATUS_ACCEPTED=>$langs->trans("StatusOrderSentShort"), + Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), + Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceledShort") ); print $form->selectarray('viewstatut', $liststatus, $viewstatut, -4); print ''; @@ -1156,9 +1422,11 @@ if ($resql) print ''."\n"; + print '
    '; + print ''."\n"; - print '
    '.img_help(1,'').' '.$langs->trans("ToBillSeveralOrderSelectCustomer", $langs->transnoentitiesnoconv("CreateInvoiceForThisCustomer")).'
    '; + //print '
    '.img_help(1,'').' '.$langs->trans("ToBillSeveralOrderSelectCustomer", $langs->transnoentitiesnoconv("CreateInvoiceForThisCustomer")).'
    '; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { @@ -1172,10 +1440,6 @@ if ($resql) $genallowed=$user->rights->commande->lire; $delallowed=$user->rights->commande->lire; - print '
    '; - $paramwithoutshowfiles=preg_replace('/show_files=1&?/','',$param); - $title=$langs->trans("MassFilesArea").' ('.$langs->trans("Hide").')'; - print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index 1f0f763bfd1..55b82d1063c 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -28,6 +28,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commandestats.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formorder.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $WIDTH=DolGraph::getDefaultGraphSizeForStats('width'); @@ -37,6 +38,8 @@ $mode=GETPOST("mode")?GETPOST("mode"):'customer'; if ($mode == 'customer' && ! $user->rights->commande->lire) accessforbidden(); if ($mode == 'supplier' && ! $user->rights->fournisseur->commande->lire) accessforbidden(); +$object_status=GETPOST('object_status'); + $userid=GETPOST('userid','int'); $socid=GETPOST('socid','int'); // Security check @@ -63,6 +66,7 @@ $langs->load('suppliers'); */ $form=new Form($db); +$formorder=new FormOrder($db); if ($mode == 'customer') { @@ -82,9 +86,19 @@ print load_fiche_titre($title,'','title_commercial.png'); dol_mkdir($dir); $stats = new CommandeStats($db, $socid, $mode, ($userid>0?$userid:0)); +if ($mode == 'customer') +{ + if ($object_status != '' && $object_status >= -1) $stats->where .= ' AND c.fk_statut IN ('.$object_status.')'; +} +if ($mode == 'supplier') +{ + if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND c.fk_statut IN ('.$object_status.')'; +} + // Build graphic number of object $data = $stats->getNbByMonthWithPrevYear($endyear,$startyear); + //var_dump($data); // $data = array(array('Lib',val1,val2,val3),...) @@ -261,6 +275,24 @@ print '
    '; // User print ''.$langs->trans("CreatedBy").''; print $form->select_dolusers($userid, 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + // Status + print ''.$langs->trans("Status").''; + if ($mode == 'customer') + { + $liststatus=array( + Commande::STATUS_DRAFT=>$langs->trans("StatusOrderDraft"), + Commande::STATUS_VALIDATED=>$langs->trans("StatusOrderValidated"), + Commande::STATUS_ACCEPTED=>$langs->trans("StatusOrderSent"), + Commande::STATUS_CLOSED=>$langs->trans("StatusOrderDelivered"), + Commande::STATUS_CANCELED=>$langs->trans("StatusOrderCanceled") + ); + print $form->selectarray('object_status', $liststatus, GETPOST('object_status'), -4); + } + if ($mode == 'supplier') + { + $formorder->selectSupplierOrderStatus((strstr($object_status, ',')?-1:$object_status), 0, 'object_status'); + } + print ''; // Year print ''.$langs->trans("Year").''; if (! in_array($year,$arrayyears)) $arrayyears[$year]=$year; diff --git a/htdocs/compta/bank/account.php b/htdocs/compta/bank/account.php deleted file mode 100644 index 8adbfb1fcb5..00000000000 --- a/htdocs/compta/bank/account.php +++ /dev/null @@ -1,971 +0,0 @@ - - * Copyright (C) 2003 Jean-Louis Bergamo - * Copyright (C) 2004-2011 Laurent Destailleur - * Copyright (C) 2004 Christophe Combelles - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010-2011 Juanjo Menent - * Copyright (C) 2012-2016 Marcos García - * Copyright (C) 2011-2015 Alexandre Spangaro - * Copyright (C) 2015 Florian Henry - * - * 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/compta/bank/account.php - * \ingroup banque - * \brief List of details of bank transactions for an account - */ - -require('../../main.inc.php'); -require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; -require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; -require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; -require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; -require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; -require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - -$langs->load("banks"); -$langs->load("categories"); -$langs->load("bills"); -$langs->load("companies"); -$langs->load("salaries"); -$langs->load("loan"); -$langs->load("donations"); -$langs->load("trips"); -$langs->load("members"); - -$id = (GETPOST('id','int') ? GETPOST('id','int') : GETPOST('account','int')); -$ref = GETPOST('ref','alpha'); -$action=GETPOST('action','alpha'); -$confirm=GETPOST('confirm','alpha'); - -// Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref :'')); -$fieldtype = (! empty($ref) ? 'ref' :'rowid'); -if ($user->societe_id) $socid=$user->societe_id; -$result=restrictedArea($user,'banque',$fieldvalue,'bank_account&bank_account','','',$fieldtype); - -$paiementtype=GETPOST('paiementtype','alpha',3); -$req_nb=GETPOST("req_nb",'',3); -$thirdparty=GETPOST("thirdparty",'',3); -$req_desc=GETPOST("req_desc",'',3); -$req_debit=GETPOST("req_debit",'',3); -$req_credit=GETPOST("req_credit",'',3); - -$req_stdtmonth=GETPOST('req_stdtmonth', 'int'); -$req_stdtday=GETPOST('req_stdtday', 'int'); -$req_stdtyear=GETPOST('req_stdtyear', 'int'); -$req_stdt = dol_mktime(0, 0, 0, $req_stdtmonth, $req_stdtday, $req_stdtyear); -$req_enddtmonth=GETPOST('req_enddtmonth', 'int'); -$req_enddtday=GETPOST('req_enddtday', 'int'); -$req_enddtyear=GETPOST('req_enddtyear', 'int'); -$req_enddt = dol_mktime(23, 59, 59, $req_enddtmonth, $req_enddtday, $req_enddtyear); - -$vline=GETPOST("vline"); -$page=GETPOST('page','int'); -$negpage=GETPOST('negpage','int'); -if ($negpage) -{ - $page=GETPOST("nbpage") - $negpage; - if ($page > GETPOST("nbpage")) $page = GETPOST("nbpage"); -} - -$object = new Account($db); - -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers -{ - $paiementtype=""; - $req_nb=""; - $thirdparty=""; - $req_desc=""; - $req_debit=""; - $req_credit=""; - $req_stdtmonth=""; - $req_stdtday=""; - $req_stdtyear=""; - $req_stdt = ""; - $req_enddtmonth=""; - $req_enddtday=""; - $req_enddtyear=""; - $req_enddt = ""; -} - -/* - * Action - */ -$dateop=-1; - -if ($action == 'add' && $id && ! isset($_POST["cancel"]) && $user->rights->banque->modifier) -{ - $error = 0; - - if (price2num($_POST["credit"]) > 0) - { - $amount = price2num($_POST["credit"]); - } - else - { - $amount = - price2num($_POST["debit"]); - } - - $dateop = dol_mktime(12,0,0,$_POST["opmonth"],$_POST["opday"],$_POST["opyear"]); - $operation=$_POST["operation"]; - $num_chq=$_POST["num_chq"]; - $label=$_POST["label"]; - $cat1=$_POST["cat1"]; - - if (! $dateop) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Date")), null, 'errors'); - } - if (! $operation) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Type")), null, 'errors'); - } - if (! $amount) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Amount")), null, 'errors'); - } - - if (! $error) - { - $object->fetch($id); - $insertid = $object->addline($dateop, $operation, $label, $amount, $num_chq, $cat1, $user); - if ($insertid > 0) - { - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - header("Location: ".$_SERVER['PHP_SELF']."?id=".$id."&action=addline"); - exit; - } - else - { - setEventMessages($object->error, $object->errors, 'errors'); - } - } - else - { - $action='addline'; - } -} -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->banque->modifier) -{ - $accline=new AccountLine($db); - $result=$accline->fetch(GETPOST("rowid")); - $result=$accline->delete(); -} - - -/* - * View - */ -$title = $langs->trans("FinancialAccount").' - '.$langs->trans("Transactions"); -$helpurl = ""; -llxHeader('',$title,$helpurl); - -$societestatic=new Societe($db); -$userstatic=new User($db); -$chargestatic=new ChargeSociales($db); -$loanstatic=new Loan($db); -$memberstatic=new Adherent($db); -$paymentstatic=new Paiement($db); -$paymentsupplierstatic=new PaiementFourn($db); -$paymentvatstatic=new TVA($db); -$paymentsalstatic=new PaymentSalary($db); -$donstatic=new Don($db); -$expensereportstatic=new ExpenseReport($db); -$bankstatic=new Account($db); -$banklinestatic=new AccountLine($db); - -$form = new Form($db); - -if ($id > 0 || ! empty($ref)) -{ - if ($vline) - { - $viewline = $vline; - } - else - { - $viewline = empty($conf->global->MAIN_SIZE_LISTE_LIMIT)?20:$conf->global->MAIN_SIZE_LISTE_LIMIT; - } - - $result=$object->fetch($id, $ref); - - // Load bank groups - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; - $bankcateg = new BankCateg($db); - $options = array(); - - foreach ($bankcateg->fetchAll() as $bankcategory) { - $options[$bankcategory->id] = $bankcategory->label; - } - - // Definition de sql_rech et param - $param=''; - $sql_rech=''; - $mode_search = 0; - if ($req_nb) - { - $sql_rech.= " AND b.num_chq LIKE '%".$db->escape($req_nb)."%'"; - $param.='&req_nb='.urlencode($req_nb); - $mode_search = 1; - } - if ($req_desc) - { - $sql_rech.= " AND b.label LIKE '%".$db->escape($req_desc)."%'"; - $param.='&req_desc='.urlencode($req_desc); - $mode_search = 1; - } - if ($req_debit != '') - { - $sql_rech.=" AND b.amount = -".price2num($req_debit); - $param.='&req_debit='.urlencode($req_debit); - $mode_search = 1; - } - if ($req_credit != '') - { - $sql_rech.=" AND b.amount = ".price2num($req_credit); - $param.='&req_credit='.urlencode($req_credit); - $mode_search = 1; - } - if ($thirdparty) - { - $sql_rech.=" AND s.nom LIKE '%".$db->escape($thirdparty)."%'"; - $param.='&thirdparty='.urlencode($thirdparty); - $mode_search = 1; - } - if ($paiementtype) - { - $sql_rech.=" AND b.fk_type = '".$db->escape($paiementtype)."'"; - $param.='&paiementtype='.urlencode($paiementtype); - $mode_search = 1; - } - - if ($req_stdt && $req_enddt) - { - $sql_rech.=" AND (b.datev BETWEEN '".$db->escape($db->idate($req_stdt))."' AND '".$db->escape($db->idate($req_enddt))."')"; - $param.='&req_stdtmonth='.$req_stdtmonth.'&req_stdtyear='.$req_stdtyear.'&req_stdtday='.$req_stdtday; - $param.='&req_enddtmonth='.$req_enddtmonth.'&req_enddtday='.$req_enddtday.'&req_enddtyear='.$req_enddtyear; - $mode_search = 1; - } - elseif ($req_stdt) - { - $sql_rech.=" AND b.datev >= '".$db->escape($db->idate($req_stdt))."'"; - $param.='&req_stdtmonth='.$req_stdtmonth.'&req_stdtyear='.$req_stdtyear.'&req_stdtday='.$req_stdtday; - $mode_search = 1; - } - elseif ($req_enddt) - { - $sql_rech.=" AND b.datev <= '".$db->escape($db->idate($req_enddt))."'"; - $param.='&req_enddtmonth='.$req_enddtmonth.'&req_enddtday='.$req_enddtday.'&req_enddtyear='.$req_enddtyear; - $mode_search = 1; - } - - - $sql = "SELECT count(*) as total"; - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ", ".MAIN_DB_PREFIX."bank as b"; - if ($mode_search) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = b.rowid AND bu.type='company'"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu.url_id = s.rowid"; - } - $sql.= " WHERE b.fk_account = ".$object->id; - $sql.= " AND b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account', 1).")"; - $sql.= $sql_rech; - - dol_syslog("account.php count transactions -", LOG_DEBUG); - $result=$db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $nbline = $obj->total; - $total_lines = $nbline; - - $db->free($result); - } - else - { - dol_print_error($db); - } - - //Total pages - $totalPages = ceil($total_lines/$viewline); - - if ($totalPages == 0) { - $page = 0; - } else { - - if ($page > 0) { - $limitsql = ($totalPages - $page) * $viewline; - if ($limitsql < $viewline) { - $limitsql = $viewline; - } - $nbline = $limitsql; - } else { - $page = 0; - $limitsql = $nbline; - } - } - - //print $limitsql.'-'.$page.'-'.$viewline; - - // Onglets - $head=bank_prepare_head($object); - dol_fiche_head($head,'journal',$langs->trans("FinancialAccount"),0,'account'); - - - print ''; - - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - print ''; - - // Label - print ''; - print ''; - - print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref'); - print '
    '.$langs->trans("Label").''.$object->label.'
    '; - - dol_fiche_end(); - - - - /* - * Buttons actions - */ - - if ($action != 'delete') - { - print '
    '; - - if ($action != 'addline') - { - if (empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) - { - if ($user->rights->banque->modifier) { - print 'id.'&page='.$page.($vline?'&vline='.$vline:'').'">'.$langs->trans("AddBankRecord").''; - } else { - print ''.$langs->trans("AddBankRecord").''; - } - } else { - print ''.$langs->trans("AddBankRecord").''; - } - } - - if ($object->canBeConciliated() > 0) { - // If not cash account and can be reconciliate - if ($user->rights->banque->consolidate) { - print ''.$langs->trans("Conciliate").''; - } else { - print ''.$langs->trans("Conciliate").''; - } - } - - print '
    '; - } - - print '
    '; - - /** - * Search form - */ - $param.='&account='.$object->id.'&vline='.$vline; - - // Confirmation delete - if ($action == 'delete') - { - $text=$langs->trans('ConfirmDeleteTransaction'); - print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&rowid='.GETPOST("rowid"),$langs->trans('DeleteTransaction'),$text,'confirm_delete'); - - } - - // Define transaction list navigation string - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $navig ='
    '; - if ($limitsql > $viewline) $navig.=''.img_previous().''; - $navig.= ' "; // ' Page '; - $navig.=''; - $navig.='/'.$totalPages.' '; - if ($total_lines > $limitsql ) - { - $navig.= ''.img_next().''; - } - $navig.='
    '; - - - //var_dump($navig); - - if ($action != 'addline' && $action != 'delete') - { - print '
    '.$navig.'
    '; - } - - // Form to add a transaction with no invoice - if ($user->rights->banque->modifier && $action == 'addline') - { - print load_fiche_titre($langs->trans("AddBankRecordLong"),'',''); - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
    '.$langs->trans("Date").' '.$langs->trans("Type").''.$langs->trans("Numero").''.$langs->trans("Description").''.$langs->trans("Debit").''.$langs->trans("Credit").' 
    '; - $form->select_date($dateop,'op',0,0,0,'transaction'); - print ''; - $form->select_types_paiements((GETPOST('operation')?GETPOST('operation'):($object->courant == Account::TYPE_CASH ? 'LIQ' : '')),'operation','1,2',2,1); - print ''; - print ''; - print ''; - if ($options) { - print '
    '.$langs->trans("Rubrique").': '; - print Form::selectarray('cat1', $options, GETPOST('cat1'), 1); - } - print '
    '; - print '
    '; - print ''; - print '
    '; - print '
    '; - print '
    '; - } - - - /* - * Show list of bank transactions - */ - - print ''; - - // Ligne de titre tableau des ecritures - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - print ''; - print ''; - print ''; - - $period_filter .= $langs->trans('From').' '.$form->select_date($req_stdt,'req_stdt',0,0,1,null,1,0,1); - $period_filter .= ' '; - $period_filter .= $langs->trans('to').' '.$form->select_date($req_enddt,'req_enddt',0,0,1,null,1,0,1); - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - - /* - * Another solution - * create temporary table solde type=heap select amount from llx_bank limit 100 ; - * select sum(amount) from solde ; - */ - - $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,"; - $sql.= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, b.fk_bordereau,"; - $sql.= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel"; - if ($mode_search) - { - $sql.= ", s.rowid as socid, s.nom as thirdparty"; - } - /* - if ($mode_search && ! empty($conf->adherent->enabled)) - { - - } - if ($mode_search && ! empty($conf->tax->enabled)) - { - - } - */ - $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; - $sql.= ", ".MAIN_DB_PREFIX."bank as b"; - if ($mode_search) - { - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu1 ON bu1.fk_bank = b.rowid AND bu1.type='company'"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu1.url_id = s.rowid"; - } - if ($mode_search && ! empty($conf->tax->enabled)) - { - // VAT - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON bu2.fk_bank = b.rowid AND bu2.type='payment_vat'"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."tva as t ON bu2.url_id = t.rowid"; - - // Salary payment - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu3 ON bu3.fk_bank = b.rowid AND bu3.type='payment_salary'"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."payment_salary as sal ON bu3.url_id = sal.rowid"; - } - if ($mode_search && ! empty($conf->adherent->enabled)) - { - // TODO Mettre jointure sur adherent pour recherche sur un adherent - //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu3 ON bu3.fk_bank = b.rowid AND bu3.type='company'"; - //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu3.url_id = s.rowid"; - } - $sql.= " WHERE b.fk_account=".$object->id; - $sql.= " AND b.fk_account = ba.rowid"; - $sql.= " AND ba.entity IN (".getEntity('bank_account', 1).")"; - $sql.= $sql_rech; - $sql.= $db->order("b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day - $sql.= $db->plimit($limitsql, 0); - - dol_syslog("account.php get transactions -", LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $now=dol_now(); - $nows=dol_print_date($now,'%Y%m%d'); - - //$form->load_cache_types_paiements(); - //$form->cache_types_paiements - - $var=true; - - $num = $db->num_rows($result); - $i = 0; $total = 0; $sep = -1; $total_deb=0; $total_cred=0; - - while ($i < $num) - { - $objp = $db->fetch_object($result); - $total = price2num($total + $objp->amount,'MT'); - if ($i >= ($viewline * (($totalPages-$page)-1))) - { - $var=!$var; - - // Is it a transaction in future ? - $dos=dol_print_date($db->jdate($objp->do),'%Y%m%d'); - //print "dos=".$dos." nows=".$nows; - if ($dos < $nows) $sep=0; // 0 means there was at least one line before current date - if ($dos > $nows && ! $sep) // We have found a line in future and we already found on line before current date - { - $sep = 1 ; - print ''; - print ''; - print ""; - print ''; - } - - print ''; - - print '\n"; - - print '\n"; - - // Payment type - print '\n"; - - // Num - print '\n"; - - // Description - print ''; - - // Add third party column - print ''; - - // Amount - if ($objp->amount < 0) - { - print ''."\n"; - $total_deb +=$objp->amount; - } - else - { - print ''."\n"; - $total_cred +=$objp->amount; - } - - // Balance - if (! $mode_search) - { - if ($total >= 0) - { - print ''; - } - else - { - print ''; - } - } - else - { - print ''; - } - - // Transaction reconciliated or edit link - if ($objp->rappro && $object->canBeConciliated() > 0) // If line not conciliated and account can be conciliated - { - print '"; - } - else - { - print ''; - } - - print ""; - } - - $i++; - } - - // Show total - if ($page == 0 && ! $mode_search) - { - //Real account situation - print ''; - print ''; - print ''; - print ''; - } else { - // Only total according row displays - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - $db->free($result); - } - else - { - dol_print_error($db); - } - - print "
    '.$langs->trans("Date").''.$langs->trans("Value").''.$langs->trans("Type").''.$langs->trans("Numero").''.$langs->trans("Description").''.$langs->trans("ThirdParty").''.$langs->trans("Debit").''.$langs->trans("Credit").''.$langs->trans("BankBalance").''; - if ($object->canBeConciliated() > 0) { - print $langs->trans("AccountStatementShort"); - } else { - print ' '; - } - print '
    '.$period_filter.''; - //$filtertype=array('TIP'=>'TIP','PRE'=>'PRE',...) - $filtertype=''; - $form->select_types_paiements($paiementtype,'paiementtype',$filtertype,2,1,1,8); - print ' '; - $searchpitco=$form->showFilterAndCheckAddButtons(0); - print $searchpitco; - print '
    '; - print $langs->trans("CurrentBalance"); - print ''.price($total - $objp->amount).' 
    '.dol_print_date($db->jdate($objp->do),"day")."'.dol_print_date($db->jdate($objp->dv),"day"); - print "'; - $label=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$objp->fk_type; - - if ($objp->fk_type == 'SOLD') $label=' '; - if ($objp->fk_type == 'CHQ' && $objp->fk_bordereau > 0) - { - dol_include_once('/compta/paiement/cheque/class/remisecheque.class.php'); - $bordereaustatic = new RemiseCheque($db); - $bordereaustatic->id = $objp->fk_bordereau; - $label .= ' '.$bordereaustatic->getNomUrl(2); - } - print $label; - print "'.($objp->num_chq?$objp->num_chq:"")."'; - // Show generic description - if (preg_match('/^\((.*)\)$/i',$objp->label,$reg)) - { - // Generic description because between (). We show it after translating. - print $langs->trans($reg[1]); - } - else - { - print dol_trunc($objp->label,60); - } - - // Add links after description - $links = $object->get_url($objp->rowid); - foreach($links as $key=>$val) - { - if ($links[$key]['type']=='payment') - { - $paymentstatic->id=$links[$key]['url_id']; - $paymentstatic->ref=$links[$key]['url_id']; - print ' '.$paymentstatic->getNomUrl(2); - } - elseif ($links[$key]['type']=='payment_supplier') - { - $paymentsupplierstatic->id=$links[$key]['url_id']; - $paymentsupplierstatic->ref=$links[$key]['url_id']; - print ' '.$paymentsupplierstatic->getNomUrl(2); - } - elseif ($links[$key]['type']=='payment_sc') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; - //print $langs->trans("SocialContributionPayment"); - print ''; - } - elseif ($links[$key]['type']=='payment_vat') - { - $paymentvatstatic->id=$links[$key]['url_id']; - $paymentvatstatic->ref=$links[$key]['url_id']; - print ' '.$paymentvatstatic->getNomUrl(2); - } - elseif ($links[$key]['type']=='payment_salary') - { - $paymentsalstatic->id=$links[$key]['url_id']; - $paymentsalstatic->ref=$links[$key]['url_id']; - print ' '.$paymentsalstatic->getNomUrl(2); - } - elseif ($links[$key]['type']=='payment_loan') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; - print ''; - } - elseif ($links[$key]['type']=='payment_donation') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; - print ''; - } - elseif ($links[$key]['type']=='payment_expensereport') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; - print ''; - } - elseif ($links[$key]['type']=='banktransfert') - { - // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. - if ($objp->amount > 0) - { - $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id=$banklinestatic->fk_account; - $bankstatic->label=$banklinestatic->bank_account_ref; - print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1,'transactions'); - print ' '.$langs->trans("toward").' '; - $bankstatic->id=$objp->bankid; - $bankstatic->label=$objp->bankref; - print $bankstatic->getNomUrl(1,''); - print ')'; - } - else - { - $bankstatic->id=$objp->bankid; - $bankstatic->label=$objp->bankref; - print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1,''); - print ' '.$langs->trans("toward").' '; - $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id=$banklinestatic->fk_account; - $bankstatic->label=$banklinestatic->bank_account_ref; - print $bankstatic->getNomUrl(1,'transactions'); - print ')'; - } - //var_dump($links); - } - elseif ($links[$key]['type']=='company') - { - - } - elseif ($links[$key]['type']=='user') - { - - } - elseif ($links[$key]['type']=='member') - { - - } - elseif ($links[$key]['type']=='sc') - { - - } - else - { - // Show link with label $links[$key]['label'] - if (! empty($objp->label) && ! empty($links[$key]['label'])) print ' - '; - print ''; - if (preg_match('/^\((.*)\)$/i',$links[$key]['label'],$reg)) - { - // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1]=='paiement') $reg[1]='Payment'; - print ' '.$langs->trans($reg[1]); - } - else - { - print ' '.$links[$key]['label']; - } - print ''; - } - } - print ''; - foreach($links as $key=>$val) - { - if ($links[$key]['type']=='company') - { - $societestatic->id=$links[$key]['url_id']; - $societestatic->name=$links[$key]['label']; - print $societestatic->getNomUrl(1,'',16); - } - else if ($links[$key]['type']=='user') - { - $userstatic->id=$links[$key]['url_id']; - $userstatic->lastname=$links[$key]['label']; - print $userstatic->getNomUrl(1,''); - } - else if ($links[$key]['type']=='sc') - { - // sc=old value - $chargestatic->id=$links[$key]['url_id']; - if (preg_match('/^\((.*)\)$/i',$links[$key]['label'],$reg)) - { - if ($reg[1]=='socialcontribution') $reg[1]='SocialContribution'; - $chargestatic->lib=$langs->trans($reg[1]); - } - else - { - $chargestatic->lib=$links[$key]['label']; - } - $chargestatic->ref=$chargestatic->lib; - print $chargestatic->getNomUrl(1,16); - } - else if ($links[$key]['type']=='loan') - { - $loanstatic->id=$links[$key]['url_id']; - if (preg_match('/^\((.*)\)$/i',$links[$key]['label'],$reg)) - { - if ($reg[1]=='loan') $reg[1]='Loan'; - $loanstatic->label=$langs->trans($reg[1]); - } - else - { - $loanstatic->label=$links[$key]['label']; - } - $loanstatic->ref=$loanstatic->label; - print $loanstatic->getLinkUrl(1,16); - } - else if ($links[$key]['type']=='member') - { - $memberstatic->id=$links[$key]['url_id']; - $memberstatic->ref=$links[$key]['label']; - print $memberstatic->getNomUrl(1,16,'card'); - } - } - print ''.price($objp->amount * -1).'   '.price($objp->amount).' '.price($total).' '.price($total).'-'; - print ''; - print img_edit(); - print ''; - print "  "; - print ''.$objp->num_releve.''; - print "'; - if ($user->rights->banque->modifier || $user->rights->banque->consolidate) - { - print ''; - print img_edit(); - print ''; - } - else - { - print ''; - print img_view(); - print ''; - } - if ($object->canBeConciliated() > 0 && empty($objp->rappro)) - { - if ($db->jdate($objp->dv) < ($now - $conf->bank->rappro->warning_delay)) - { - print ' '.img_warning($langs->trans("Late")); - } - } - print ' '; - if ($user->rights->banque->modifier) - { - print 'rowid.'&id='.$object->id.'&page='.$page.'">'; - print img_delete(); - print ''; - } - print '
    '; - if ($sep > 0) print ' '; // If we had at least one line in future - else print $langs->trans("CurrentBalance"); - print ' '.$object->currency_code.''.price($total).' 
    '; - if ($sep > 0) print ' '; // If we had at least one line in future - else print $langs->trans("Total"); - print ' '.$object->currency_code.''.price($total_deb*-1).''.price($total_cred).''.price($total_cred-($total_deb*-1)).' 
    "; - - print "\n"; - - print '
    '; -} -else -{ - print $langs->trans("ErrorBankAccountNotFound"); -} - -llxFooter(); - -$db->close(); diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index 5f0dbfd10ac..9acf83db399 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -32,7 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $langs->load("banks"); $langs->load("categories"); -$id=GETPOST('account'); +$id=GETPOST('account')?GETPOST('account','alpha'):GETPOST('id'); $ref=GETPOST('ref'); // Security check @@ -60,16 +60,16 @@ llxHeader('',$title,$helpurl); $form = new Form($db); // Get account informations -$acct = new Account($db); +$object = new Account($db); if ($id > 0 && ! preg_match('/,/', $id)) // if for a particular account and not a list { - $result=$acct->fetch($id); - $id=$acct->id; + $result=$object->fetch($id); + $id=$object->id; } if (! empty($ref)) { - $result=$acct->fetch(0, $ref); - $id=$acct->id; + $result=$object->fetch(0, $ref); + $id=$object->id; } @@ -134,58 +134,38 @@ else // Onglets -$head=bank_prepare_head($acct); +$head=bank_prepare_head($object); dol_fiche_head($head,'annual',$langs->trans("FinancialAccount"),0,'account'); -$title=$langs->trans("FinancialAccount")." : ".$acct->label; -$link=($year_start?"".img_previous()." ".$langs->trans("Year")." ".img_next()."":""); - -print ''; +$title=$langs->trans("FinancialAccount")." : ".$object->label; +$link=($year_start?"".img_previous()." ".$langs->trans("Year")." ".img_next()."":""); $linkback = ''.$langs->trans("BackToList").''; -// Ref -print ''; -print ''; - -// Label -print ''; -print ''; - -print '
    '.$langs->trans("Ref").''; + if (!empty($id)) { - if (! preg_match('/,/', $id)) - { - print $form->showrefnav($acct, 'ref', $linkback, 1, 'ref'); - } - else - { - $bankaccount=new Account($db); - $listid=explode(',', $id); - foreach($listid as $key => $aId) - { - $bankaccount->fetch($aId); - $bankaccount->label=$bankaccount->ref; - print $bankaccount->getNomUrl(1); - if ($key < (count($listid)-1)) print ', '; - } - } -} -else -{ - print $langs->trans("ALL"); -} -print '
    '.$langs->trans("Label").''; -if (! empty($id)) -{ - print $acct->label; + if (! preg_match('/,/', $id)) + { + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + } + else + { + $bankaccount=new Account($db); + $listid=explode(',', $id); + foreach($listid as $key => $aId) + { + $bankaccount->fetch($aId); + $bankaccount->label=$bankaccount->ref; + print $bankaccount->getNomUrl(1); + if ($key < (count($listid)-1)) print ', '; + } + } } else { print $langs->trans("AllAccounts"); } -print '
    '; dol_fiche_end(); @@ -287,7 +267,7 @@ print ""; $year = $year_end; -$result=dol_mkdir($conf->banque->dir_temp); +$result=dol_mkdir($conf->bank->dir_temp); if ($result < 0) { $langs->load("errors"); @@ -378,7 +358,7 @@ else } // Fabrication tableau 4b - $file= $conf->banque->dir_temp."/credmovement".$id."-".$year.".png"; + $file= $conf->bank->dir_temp."/credmovement".$id."-".$year.".png"; $fileurl=DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/credmovement".$id."-".$year.".png"; $title=$langs->transnoentities("Credit").' - '.$langs->transnoentities("Year").': '.($year-2).' - '.($year-1)." - ".$year; $graph_datas=array(); @@ -465,7 +445,7 @@ else $datamin[$i] = 0; } - $file= $conf->banque->dir_temp."/debmovement".$id."-".$year.".png"; + $file= $conf->bank->dir_temp."/debmovement".$id."-".$year.".png"; $fileurl= DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/debmovement".$id."-".$year.".png"; $title=$langs->transnoentities("Debit").' - '.$langs->transnoentities("Year").': '.($year-2).' - '.($year-1)." - ".$year; $graph_datas=array(); diff --git a/htdocs/compta/bank/bankentries.php b/htdocs/compta/bank/bankentries.php new file mode 100644 index 00000000000..477c65a66b3 --- /dev/null +++ b/htdocs/compta/bank/bankentries.php @@ -0,0 +1,1305 @@ + + * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2005-2010 Regis Houssin + * Copyright (C) 2012 Vinícius Nogueira + * Copyright (C) 2014 Florian Henry + * Copyright (C) 2015 Jean-François Ferry + * + * 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/compta/bank/bankentries.php + * \ingroup banque + * \brief List of bank transactions + */ + +require('../../main.inc.php'); +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + +require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; + +$langs->load("banks"); +$langs->load("bills"); +$langs->load("categories"); +$langs->load("companies"); +$langs->load("margins"); +$langs->load("salaries"); +$langs->load("loan"); +$langs->load("donations"); +$langs->load("trips"); +$langs->load("members"); + +$id = GETPOST('id','int'); +$ref = GETPOST('ref','alpha'); +$action=GETPOST('action','alpha'); +$cancel=GETPOST('cancel','alpha'); +$confirm=GETPOST('confirm','alpha'); + +// Security check +$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref :'')); +$fieldtype = (! empty($ref) ? 'ref' :'rowid'); +if ($fielvalue) +{ + if ($user->societe_id) $socid=$user->societe_id; + $result=restrictedArea($user,'banque',$fieldvalue,'bank_account&bank_account','','',$fieldtype); +} +else +{ + if ($user->societe_id) $socid=$user->societe_id; + $result=restrictedArea($user,'banque'); +} + +$search_ref=GETPOST('search_ref','alpha'); +$description=GETPOST("description",'alpha'); +$debit=GETPOST("debit",'alpha'); +$credit=GETPOST("credit",'alpha'); +$type=GETPOST("type",'alpha'); +$account=GETPOST("account",'int'); +$bid=GETPOST("bid","int"); +$search_dt_start = dol_mktime(0, 0, 0, GETPOST('search_start_dtmonth', 'int'), GETPOST('search_start_dtday', 'int'), GETPOST('search_start_dtyear', 'int')); +$search_dt_end = dol_mktime(0, 0, 0, GETPOST('search_end_dtmonth', 'int'), GETPOST('search_end_dtday', 'int'), GETPOST('search_end_dtyear', 'int')); +$search_dv_start = dol_mktime(0, 0, 0, GETPOST('search_start_dvmonth', 'int'), GETPOST('search_start_dvday', 'int'), GETPOST('search_start_dvyear', 'int')); +$search_dv_end = dol_mktime(0, 0, 0, GETPOST('search_end_dvmonth', 'int'), GETPOST('search_end_dvday', 'int'), GETPOST('search_end_dvyear', 'int')); +$search_thirdparty=GETPOST("thirdparty",'alpha'); +$search_req_nb=GETPOST("req_nb",'alpha'); +$search_num_releve=GETPOST("search_num_releve",'alpha'); +$num_releve=GETPOST("num_releve"); +$cat=GETPOST("cat"); + + +$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +$pageplusone = GETPOST("pageplusone",'int'); +if ($pageplusone) $page = $pageplusone - 1; +if ($page == -1) { $page = 0; } +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortorder) $sortorder='ASC'; +if (! $sortfield) $sortfield='b.datev'; + +$mode_balance_ok=false; +//if (($sortfield == 'b.datev' || $sortfield == 'b.datev, b.dateo, b.rowid')) // TODO Manage balance when account not selected +if (($sortfield == 'b.datev' || $sortfield == 'b.datev, b.dateo, b.rowid')) +{ + $sortfield = 'b.datev, b.dateo, b.rowid'; + if ($id > 0 || ! empty($ref) || $account > 0) $mode_balance_ok = true; +} +if (strtolower($sortorder) == 'desc') $mode_balance_ok = false; + +$object = new Account($db); +if ($id > 0 || ! empty($ref)) +{ + $result=$object->fetch($id, $ref); + $account = $object->id; // Force the search field on id of account +} + + +// Initialize technical object to manage context to save list fields +$contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id); +//var_dump($contextpage); + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('banktransactionlist', $contextpage)); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('banktransaction'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +$arrayfields=array( + 'b.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'description'=>array('label'=>$langs->trans("Description"), 'checked'=>1), + 'b.dateo'=>array('label'=>$langs->trans("DateOperationShort"), 'checked'=>1), + 'b.datev'=>array('label'=>$langs->trans("DateValueShort"), 'checked'=>1), + 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), + 'b.num_chq'=>array('label'=>$langs->trans("Numero"), 'checked'=>1), + 'bu.label'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>500), + 'ba.ref'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>(($id > 0 || ! empty($ref))?0:1), 'position'=>1000), + 'b.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1, 'position'=>600), + 'b.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1, 'position'=>605), + 'balance'=>array('label'=>$langs->trans("Balance"), 'checked'=>1, 'position'=>1000), + 'b.num_releve'=>array('label'=>$langs->trans("AccountStatement"), 'checked'=>1, 'position'=>1010), +); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } +} + + + +/* + * Actions + */ + +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_dt_start=''; + $search_dt_end=''; + $search_dv_start=''; + $search_dv_end=''; + $description=""; + $type=""; + $debit=""; + $credit=""; + $bid=""; + $search_ref=""; + $search_req_nb=''; + $search_thirdparty=''; + $search_num_releve=''; + $thirdparty=''; + + $account=""; + if ($id > 0 || ! empty($ref)) $account=$object->id; +} + +if (empty($reshook)) +{ + $objectclass='Account'; + $objectlabel='BankTransaction'; + $permtoread = $user->rights->banque->lire; + $permtodelete = $user->rights->banque->supprimer; + $uploaddir = $conf->bank->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + +// Conciliation +if (GETPOST('confirm_reconcile') && $user->rights->banque->consolidate) +{ + $error=0; + + // Definition, nettoyage parametres + $num_releve=trim(GETPOST("num_releve")); + + if ($num_releve) + { + $bankline=new AccountLine($db); + if (isset($_POST['rowid']) && is_array($_POST['rowid'])) + { + foreach($_POST['rowid'] as $row) + { + if ($row > 0) + { + $result=$bankline->fetch($row); + $bankline->num_releve=$num_releve; //$_POST["num_releve"]; + $result=$bankline->update_conciliation($user, GETPOST("cat")); + if ($result < 0) + { + setEventMessages($bankline->error, $bankline->errors, 'errors'); + $error++; + break; + } + } + } + } + else + { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("NoRecordSelected"), null, 'errors'); + } + } + else + { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); + } + + if (! $error) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); // To avoid to submit twice and allow back + exit; + } +} + + +$dateop=-1; + +if (GETPOST('save') && $id && ! $cancel && $user->rights->banque->modifier) +{ + $error = 0; + + if (price2num($_POST["addcredit"]) > 0) + { + $amount = price2num($_POST["addcredit"]); + } + else + { + $amount = - price2num($_POST["adddebit"]); + } + + $dateop = dol_mktime(12,0,0,$_POST["opmonth"],$_POST["opday"],$_POST["opyear"]); + $operation=$_POST["operation"]; + $num_chq=$_POST["num_chq"]; + $label=$_POST["label"]; + $cat1=$_POST["cat1"]; + + if (! $dateop) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Date")), null, 'errors'); + } + if (! $operation) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Type")), null, 'errors'); + } + if (! $amount) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("Amount")), null, 'errors'); + } + + if (! $error) + { + $object->fetch($id); + $insertid = $object->addline($dateop, $operation, $label, $amount, $num_chq, $cat1, $user); + if ($insertid > 0) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + else + { + $action='addline'; + } +} + +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->banque->modifier) +{ + $accline=new AccountLine($db); + $result=$accline->fetch(GETPOST("rowid")); + $result=$accline->delete($user); +} + + + +/* + * View + */ + +$form = new Form($db); +$formother = new FormOther($db); + +$companystatic=new Societe($db); +$bankaccountstatic=new Account($db); + +$societestatic=new Societe($db); +$userstatic=new User($db); +$chargestatic=new ChargeSociales($db); +$loanstatic=new Loan($db); +$memberstatic=new Adherent($db); +$paymentstatic=new Paiement($db); +$paymentsupplierstatic=new PaiementFourn($db); +$paymentvatstatic=new TVA($db); +$paymentsalstatic=new PaymentSalary($db); +$donstatic=new Don($db); +$expensereportstatic=new ExpenseReport($db); +$bankstatic=new Account($db); +$banklinestatic=new AccountLine($db); + +$now = dol_now(); + + +// Must be before button action +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($id > 0) $param.='&id='.urlencode($id); +if (!empty($ref)) $param.='&ref='.urlencode($ref); +if (!empty($search_ref)) $param.='&search_ref='.urlencode($search_ref); +if (!empty($description)) $param.='&description='.urlencode($description); +if (!empty($type)) $param.='&type='.urlencode($type); +if (!empty($debit)) $param.='&debit='.$debit; +if (!empty($credit)) $param.='&credit='.$credit; +if (!empty($account)) $param.='&account='.$account; +if (!empty($search_num_releve)) $param.='&search_num_releve='.urlencode($search_num_releve); +if (!empty($bid)) $param.='&bid='.$bid; +if (dol_strlen($search_dt_start) > 0) $param .= '&search_start_dtmonth=' . GETPOST('search_start_dtmonth', 'int') . '&search_start_dtday=' . GETPOST('search_start_dtday', 'int') . '&search_start_dtyear=' . GETPOST('search_start_dtyear', 'int'); +if (dol_strlen($search_dt_end) > 0) $param .= '&search_end_dtmonth=' . GETPOST('search_end_dtmonth', 'int') . '&search_end_dtday=' . GETPOST('search_end_dtday', 'int') . '&search_end_dtyear=' . GETPOST('search_end_dtyear', 'int'); +if (dol_strlen($search_dv_start) > 0) $param .= '&search_start_dvmonth=' . GETPOST('search_start_dvmonth', 'int') . '&search_start_dvday=' . GETPOST('search_start_dvday', 'int') . '&search_start_dvyear=' . GETPOST('search_start_dvyear', 'int'); +if (dol_strlen($search_dv_end) > 0) $param .= '&search_end_dvmonth=' . GETPOST('search_end_dvmonth', 'int') . '&search_end_dvday=' . GETPOST('search_end_dvday', 'int') . '&search_end_dvyear=' . GETPOST('search_end_dvyear', 'int'); +if ($search_req_nb) $param.='&req_nb='.urlencode($search_req_nb); +if (GETPOST("thirdparty")) $param.='&thirdparty='.urlencode(GETPOST("thirdparty")); +if ($optioncss != '') $param.='&optioncss='.$optioncss; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + + + +if ($id > 0 || ! empty($ref)) +{ + $title = $langs->trans("FinancialAccount").' - '.$langs->trans("Transactions"); + $helpurl = ""; + llxHeader('',$title,$helpurl); + + // Load bank groups + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; + $bankcateg = new BankCateg($db); + $options = array(); + + foreach ($bankcateg->fetchAll() as $bankcategory) { + $options[$bankcategory->id] = $bankcategory->label; + } + + // Bank card + + $head=bank_prepare_head($object); + dol_fiche_head($head,'journal',$langs->trans("FinancialAccount"),0,'account'); + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + + dol_fiche_end(); + + + + /* + * Buttons actions + */ + if ($action != 'addline' && $action != 'reconcile') + { + print '
    '; + + if ($action != 'addline') + { + if (empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) + { + if ($user->rights->banque->modifier) { + print ''.$langs->trans("AddBankRecord").''; + } else { + print ''.$langs->trans("AddBankRecord").''; + } + } else { + print ''.$langs->trans("AddBankRecord").''; + } + } + if ($object->canBeConciliated() > 0) { + // If not cash account and can be reconciliate + if ($user->rights->banque->consolidate) { + print ''.$langs->trans("Conciliate").''; + } else { + print ''.$langs->trans("Conciliate").''; + } + } + + print '
    '; + } +} +else +{ + llxHeader('', $langs->trans("BankTransactions"), '', '', 0, 0, array(), array(), $param); +} + +$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq,"; +$sql.= " b.fk_account, b.fk_type,"; +$sql.= " ba.rowid as bankid, ba.ref as bankref,"; +$sql.= " bu.url_id,"; +$sql.= " s.nom, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur"; +// 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 +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql.= " FROM "; +if ($bid) $sql.= MAIN_DB_PREFIX."bank_class as l,"; +$sql.= " ".MAIN_DB_PREFIX."bank_account as ba,"; +$sql.= " ".MAIN_DB_PREFIX."bank as b"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_extrafields as ef on (b.rowid = ef.fk_object)"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = b.rowid AND type = 'company'"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu.url_id = s.rowid"; +$sql.= " WHERE b.fk_account = ba.rowid"; +$sql.= " AND ba.entity IN (".getEntity('bank_account', 1).")"; +if ($account > 0) $sql.=" AND b.fk_account = ".$account; +// Search period criteria +if (dol_strlen($search_dt_start)>0) $sql .= " AND b.dateo >= '" . $db->idate($search_dt_start) . "'"; +if (dol_strlen($search_dt_end)>0) $sql .= " AND b.dateo <= '" . $db->idate($search_dt_end) . "'"; +// Search period criteria +if (dol_strlen($search_dv_start)>0) $sql .= " AND b.datev >= '" . $db->idate($search_dv_start) . "'"; +if (dol_strlen($search_dv_end)>0) $sql .= " AND b.datev <= '" . $db->idate($search_dv_end) . "'"; +if ($search_ref) $sql.=natural_search("b.rowid", $search_ref); +if ($search_req_nb) $sql.= natural_search("b.num_chq", $search_req_nb); +if ($search_num_releve) $sql.= natural_search("b.num_releve", $search_num_releve); +if ($search_thirdparty) $sql.= natural_search("s.nom", $search_thirdparty); +if ($description) $sql.= natural_search("b.label", $description); // Warning some text are just translation keys, not translated strings +if ($bid) $sql.= " AND b.rowid=l.lineid AND l.fk_categ=".$bid; +if (! empty($type)) $sql.= " AND b.fk_type = '".$db->escape($type)."' "; +// Search criteria amount +$debit = price2num(str_replace('-','',$debit)); +$credit = price2num(str_replace('-','',$credit)); +if ($debit) $sql.= natural_search('- b.amount', $debit, 1); +if ($credit) $sql.= natural_search('b.amount', $credit, 1); +// Add where from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double'))) $mode=1; // Search on a numeric + if ($val && ( ($crit != '' && ! in_array($typ, array('select'))) || ! empty($crit))) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } +} +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +$sql.= $db->order($sortfield,$sortorder); + +$nbtotalofrecords = 0; +$nbtotalofpages = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + $nbtotalofpages = ceil($nbtotalofrecords/$limit); +} + +if (($id > 0 || ! empty($ref)) && ((string) $page == '')) +{ + // We open a list of transaction of a dedicated account and no page was set by defaut + // We force on last page. + $page = ($nbtotalofpages - 1); + $offset = $limit * $page; + if ($page < 0) $page = 0; +} +if ($page >= $nbtotalofpages) +{ + // If we made a search and result has low page than the page number we were on + $page = ($nbtotalofpages -1); + $offset = $limit * $page; + if ($page < 0) $page = 0; +} + +if (! empty($search_ref)) $mode_balance_ok=false; +if (! empty($req_nb)) $mode_balance_ok=false; +if (! empty($type)) $mode_balance_ok=false; +if (! empty($debit)) $mode_balance_ok=false; +if (! empty($credit)) $mode_balance_ok=false; +if (! empty($thirdparty)) $mode_balance_ok=false; + +$sql.= $db->plimit($limit+1,$offset); + +dol_syslog('compta/bank/bankentries.php', LOG_DEBUG); +$resql = $db->query($sql); +if ($resql) +{ + $var=True; + $num = $db->num_rows($resql); + + $arrayofselected=is_array($toselect)?$toselect:array(); + + // List of mass actions available + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + //if ($user->rights->bank->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + + + // Confirmation delete + if ($action == 'delete') + { + $text=$langs->trans('ConfirmDeleteTransaction'); + print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&rowid='.GETPOST("rowid"), $langs->trans('DeleteTransaction'), $text, 'confirm_delete', null, '', 1); + } + + + // Lines of title fields + print '
    '."\n"; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (! empty($_REQUEST['bid'])) print ''; + + // Form to reconcile + if ($user->rights->banque->consolidate && $action == 'reconcile') + { +// print ''; +// print ''; +// print '
    '; + print '
    '; + print ''.$langs->trans("InputReceiptNumber").': '; + print ''; // The only default value is value we just entered + print '
    '; + if ($options) { + print $langs->trans("EventualyAddCategory").': '; + print Form::selectarray('cat', $options, GETPOST('cat'), 1); + } + print '
    '.$langs->trans("ThenCheckLinesAndConciliate").' '; + print ''; + print ' '.$langs->trans("or").' '; + print ''; + + // Show last bank statements + $nbmax=15; // We accept to show last 15 receipts (so we can have more than one year) + $liste=""; + $sql = "SELECT DISTINCT num_releve FROM ".MAIN_DB_PREFIX."bank"; + $sql.= " WHERE fk_account=".$id." AND num_releve IS NOT NULL"; + $sql.= $db->order("num_releve","DESC"); + $sql.= $db->plimit($nbmax+1); + print '

    '; + print $langs->trans("LastAccountStatements").' : '; + $resqlr=$db->query($sql); + if ($resqlr) + { + $numr=$db->num_rows($resqlr); + $i=0; + $last_ok=0; + while (($i < $numr) && ($i < $nbmax)) + { + $objr = $db->fetch_object($resqlr); + if (! $last_ok) { + $last_releve = $objr->num_releve; + $last_ok=1; + } + $i++; + $liste=''.$objr->num_releve.'   '.$liste; + } + if ($numr >= $nbmax) $liste="...   ".$liste; + print $liste; + if ($numr <= 0) print ''.$langs->trans("None").''; + } + else + { + dol_print_error($db); + } + print '

    '; +// print '
    '; + } + + // Form to add a transaction with no invoice + if ($user->rights->banque->modifier && $action == 'addline') + { + print load_fiche_titre($langs->trans("AddBankRecordLong"),'',''); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '.$langs->trans("Date").' '.$langs->trans("Type").''.$langs->trans("Numero").''.$langs->trans("Description").''.$langs->trans("Debit").''.$langs->trans("Credit").' 
    '; + $form->select_date(empty($dateop)?-1:$dateop,'op',0,0,0,'transaction'); + print ''; + $form->select_types_paiements((GETPOST('operation')?GETPOST('operation'):($object->courant == Account::TYPE_CASH ? 'LIQ' : '')),'operation','1,2',2,1); + print ''; + print ''; + print ''; + if ($options) { + print '
    '.$langs->trans("Rubrique").': '; + print Form::selectarray('cat1', $options, GETPOST('cat1'), 1); + } + print '
    '; + print '
    '; + print ''; + print '
    '; + print '
    '; + } + + + /// ajax adjust value date + print ' + + + '; + + $i = 0; + + // Title + $bankcateg=new BankCateg($db); + $morehtml='
    '; + $morehtml.= ' "; // ' Page '; + $morehtml.=''; + $morehtml.='/'.$nbtotalofpages.' '; + $morehtml.='
    '; + + $picto='title_bank'; + if ($id > 0 || ! empty($ref)) $picto=''; + if (GETPOST("bid")) + { + $result=$bankcateg->fetch(GETPOST("bid")); + print_barre_liste($langs->trans("BankTransactionForCategory",$bankcateg->label).' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $morehtml, '', $limit); + } + else + { + print_barre_liste($langs->trans("BankTransactions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $morehtml, '', $limit); + } + + // We can add page now to param + if ($page != '') $param.='&page='.urlencode($page); + + + $moreforfilter = ''; + + $moreforfilter.='
    '; + $moreforfilter .= $langs->trans('DateOperationShort').' : '; + $moreforfilter .= '
    '.$langs->trans('From') . ' '; + $moreforfilter .= $form->select_date($search_dt_start, 'search_start_dt', 0, 0, 1, "search_form", 1, 0, 1).'
    '; + $moreforfilter .= ' - '; + $moreforfilter .= '
    '.$langs->trans('to') . ' ' . $form->select_date($search_dt_end, 'search_end_dt', 0, 0, 1, "search_form", 1, 0, 1).'
    '; + $moreforfilter .= '
    '; + + $moreforfilter.='
    '; + $moreforfilter .= $langs->trans('DateValueShort').' : '; + $moreforfilter .= '
    '.$langs->trans('From') . ' '; + $moreforfilter .= $form->select_date($search_dv_start, 'search_start_dv', 0, 0, 1, "search_form", 1, 0, 1).'
    '; + $moreforfilter .= ' - '; + $moreforfilter .= '
    '.$langs->trans('to') . ' ' . $form->select_date($search_dv_end, 'search_end_dv', 0, 0, 1, "search_form", 1, 0, 1).'
    '; + $moreforfilter .= '
    '; + + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; + + if ($moreforfilter) + { + print '
    '; + print $moreforfilter; + print '
    '."\n"; + } + + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + + print ''."\n"; + + // Fields title + print ''; + if (! empty($arrayfields['b.rowid']['checked'])) print_liste_field_titre($arrayfields['b.rowid']['label'],$_SERVER['PHP_SELF'],'b.rowid','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['description']['checked'])) print_liste_field_titre($arrayfields['description']['label'],$_SERVER['PHP_SELF'],'','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['b.dateo']['checked'])) print_liste_field_titre($arrayfields['b.dateo']['label'],$_SERVER['PHP_SELF'],'b.dateo','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['b.datev']['checked'])) print_liste_field_titre($arrayfields['b.datev']['label'],$_SERVER['PHP_SELF'],'b.datev, b.dateo, b.rowid','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['type']['checked'])) print_liste_field_titre($arrayfields['type']['label'],$_SERVER['PHP_SELF'],'','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['b.num_chq']['checked'])) print_liste_field_titre($arrayfields['b.num_chq']['label'],$_SERVER['PHP_SELF'],'b.num_chq','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['bu.label']['checked'])) print_liste_field_titre($arrayfields['bu.label']['label'],$_SERVER['PHP_SELF'],'bu.label','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['ba.ref']['checked'])) print_liste_field_titre($arrayfields['ba.ref']['label'],$_SERVER['PHP_SELF'],'ba.ref','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['b.debit']['checked'])) print_liste_field_titre($arrayfields['b.debit']['label'],$_SERVER['PHP_SELF'],'b.amount','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['b.credit']['checked'])) print_liste_field_titre($arrayfields['b.credit']['label'],$_SERVER['PHP_SELF'],'b.amount','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['balance']['checked'])) print_liste_field_titre($arrayfields['balance']['label'],$_SERVER['PHP_SELF'],'balance','',$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['b.num_releve']['checked'])) print_liste_field_titre($arrayfields['b.num_releve']['label'],$_SERVER['PHP_SELF'],'b.num_releve','',$param,'align="center"',$sortfield,$sortorder); + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print_liste_field_titre('', $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); + print "\n"; + + print ''; + if (! empty($arrayfields['b.rowid']['checked'])) + { + print ''; + } + if (! empty($arrayfields['description']['checked'])) + { + print ''; + } + if (! empty($arrayfields['b.dateo']['checked'])) + { + print ''; + } + if (! empty($arrayfields['b.datev']['checked'])) + { + print ''; + } + if (! empty($arrayfields['type']['checked'])) + { + print ''; + } + if (! empty($arrayfields['b.num_chq']['checked'])) + { + // Numero + print ''; + } + if (! empty($arrayfields['bu.label']['checked'])) + { + print ''; + } + if (! empty($arrayfields['ba.ref']['checked'])) + { + print ''; + } + if (! empty($arrayfields['b.debit']['checked'])) + { + print ''; + } + if (! empty($arrayfields['b.credit']['checked'])) + { + print ''; + } + if (! empty($arrayfields['balance']['checked'])) + { + print ''; + } + if (! empty($arrayfields['b.num_releve']['checked'])) + { + // Numero statement + print ''; + } + print ''; + print ''; + print "\n"; + + $balance = 0; // For balance + $balancecalculated = false; + + // Loop on each record + $sign = 1; + + $totalarray=array(); + while ($i < min($num,$limit)) + { + $objp = $db->fetch_object($resql); + + // If we are in a situation where we need/can show balance, we calculate the start of balance + if (! $balancecalculated && ! empty($arrayfields['balance']['checked']) && $mode_balance_ok) + { + //Loop on each record + $sign = 1; + $i = 0; + $sqlforbalance='SELECT SUM(b.amount) as balance'; + $sqlforbalance.= " FROM "; + $sqlforbalance.= " ".MAIN_DB_PREFIX."bank_account as ba,"; + $sqlforbalance.= " ".MAIN_DB_PREFIX."bank as b"; + $sqlforbalance.= " WHERE b.fk_account = ba.rowid"; + $sqlforbalance.= " AND ba.entity IN (".getEntity('bank_account', 1).")"; + $sqlforbalance.= " AND b.fk_account = ".$account; + $sqlforbalance.= " AND b.datev < '" . $db->idate($db->jdate($objp->dv)) . "'"; + $resqlforbalance = $db->query($sqlforbalance); + //print $sqlforbalance; + if ($resqlforbalance) + { + $objforbalance = $db->fetch_object($resqlforbalance); + if ($objforbalance) + { + $balance = $objforbalance->balance; + } + } + else dol_print_error($db); + + $balancecalculated=true; + } + + $balance = price2num($balance + ($sign * $objp->amount),'MT'); + + if (empty($cachebankaccount[$objp->bankid])) + { + $bankaccounttmp = new Account($db); + $bankaccounttmp->fetch($objp->bankid); + $cachebankaccount[$objp->bankid]=$bankaccounttmp; + $bankaccount = $bankaccounttmp; + } + else + { + $bankaccount = $cachebankaccount[$objp->bankid]; + } + + $var=!$var; + + print ""; + + // Ref + if (! empty($arrayfields['b.rowid']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Description + if (! empty($arrayfields['description']['checked'])) + { + print "'; + if (! $i) $totalarray['nbfield']++; + } + + // Date ope + if (! empty($arrayfields['b.dateo']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Date value + if (! empty($arrayfields['b.datev']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Payment type + if (! empty($arrayfields['type']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Num cheque + if (! empty($arrayfields['b.num_chq']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Third party + if (! empty($arrayfields['bu.label']['checked'])) + { + print "'; + if (! $i) $totalarray['nbfield']++; + } + + // Bank account + if (! empty($arrayfields['ba.ref']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + } + + // Debit + if (! empty($arrayfields['b.debit']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totaldebfield']=$totalarray['nbfield']; + } + // Credit + if (! empty($arrayfields['b.credit']['checked'])) + { + print '\n"; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalcredfield']=$totalarray['nbfield']; + } + + // Balance + if (! empty($arrayfields['balance']['checked'])) + { + if ($mode_balance_ok) + { + if ($balance >= 0) + { + print ''; + } + else + { + print ''; + } + } + else + { + print ''; + } + } + + if (! empty($arrayfields['b.num_releve']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Action edit/delete + print ''; + if (! $i) $totalarray['nbfield']++; + + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print ""; + + $i++; + } + + // Show total line + if (isset($totalarray['totaldebfield']) || isset($totalarray['totalcredfield'])) + { + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + elseif ($totalarray['totaldebfield'] == $i) print ''; + elseif ($totalarray['totalcredfield'] == $i) print ''; + else print ''; + } + print ''; + } + + print "
    '; + print ''; + print ''; + //print ''; + print '  '; + $form->select_types_paiements(empty($type)?'':$type, 'type', '', 2, 0, 1, 0, 1, 'maxwidth100'); + print ''; + $form->select_comptes($account,'account',0,'',1, ($id > 0 || ! empty($ref)?' disabled="disabled"':'')); + print ''; + print ''; + print ''; + print ''; + print ''; + $htmltext=$langs->trans("BalanceVisibilityDependsOnSortAndFilters", $langs->transnoentitiesnoconv("DateValue")); + print $form->textwithpicto('', $htmltext, 1); + print ''; + print ''; + $searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + print $searchpitco; + print '
    '; + print "rowid.'">'.img_object($langs->trans("ShowPayment").': '.$objp->rowid, 'account', 'class="classfortooltip"').' '.$objp->rowid."   "; + print '"; + + //print "rowid."&account=".$objp->fk_account."\">"; + $reg=array(); + preg_match('/\((.+)\)/i',$objp->label,$reg); // Si texte entoure de parenthee on tente recherche de traduction + if ($reg[1] && $langs->trans($reg[1])!=$reg[1]) print $langs->trans($reg[1]); + else print dol_trunc($objp->label,40); + //print " "; + + // Add links after description + $links = $bankaccountstatic->get_url($objp->rowid); + $cachebankaccount=array(); + foreach($links as $key=>$val) + { + if ($links[$key]['type']=='payment') + { + $paymentstatic->id=$links[$key]['url_id']; + $paymentstatic->ref=$links[$key]['url_id']; + print ' '.$paymentstatic->getNomUrl(2); + } + elseif ($links[$key]['type']=='payment_supplier') + { + $paymentsupplierstatic->id=$links[$key]['url_id']; + $paymentsupplierstatic->ref=$links[$key]['url_id']; + print ' '.$paymentsupplierstatic->getNomUrl(2); + } + elseif ($links[$key]['type']=='payment_sc') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; + //print $langs->trans("SocialContributionPayment"); + print ''; + } + elseif ($links[$key]['type']=='payment_vat') + { + $paymentvatstatic->id=$links[$key]['url_id']; + $paymentvatstatic->ref=$links[$key]['url_id']; + print ' '.$paymentvatstatic->getNomUrl(2); + } + elseif ($links[$key]['type']=='payment_salary') + { + $paymentsalstatic->id=$links[$key]['url_id']; + $paymentsalstatic->ref=$links[$key]['url_id']; + print ' '.$paymentsalstatic->getNomUrl(2); + } + elseif ($links[$key]['type']=='payment_loan') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; + print ''; + } + elseif ($links[$key]['type']=='payment_donation') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; + print ''; + } + elseif ($links[$key]['type']=='payment_expensereport') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; + print ''; + } + elseif ($links[$key]['type']=='banktransfert') + { + // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. + if ($objp->amount > 0) + { + $banklinestatic->fetch($links[$key]['url_id']); + $bankstatic->id=$banklinestatic->fk_account; + $bankstatic->label=$banklinestatic->bank_account_ref; + print ' ('.$langs->trans("TransferFrom").' '; + print $bankstatic->getNomUrl(1,'transactions'); + print ' '.$langs->trans("toward").' '; + $bankstatic->id=$objp->bankid; + $bankstatic->label=$objp->bankref; + print $bankstatic->getNomUrl(1,''); + print ')'; + } + else + { + $bankstatic->id=$objp->bankid; + $bankstatic->label=$objp->bankref; + print ' ('.$langs->trans("TransferFrom").' '; + print $bankstatic->getNomUrl(1,''); + print ' '.$langs->trans("toward").' '; + $banklinestatic->fetch($links[$key]['url_id']); + $bankstatic->id=$banklinestatic->fk_account; + $bankstatic->label=$banklinestatic->bank_account_ref; + print $bankstatic->getNomUrl(1,'transactions'); + print ')'; + } + //var_dump($links); + } + elseif ($links[$key]['type']=='company') + { + + } + elseif ($links[$key]['type']=='user') + { + + } + elseif ($links[$key]['type']=='member') + { + + } + elseif ($links[$key]['type']=='sc') + { + + } + else + { + // Show link with label $links[$key]['label'] + if (! empty($objp->label) && ! empty($links[$key]['label'])) print ' - '; + print ''; + if (preg_match('/^\((.*)\)$/i',$links[$key]['label'],$reg)) + { + // Label generique car entre parentheses. On l'affiche en le traduisant + if ($reg[1]=='paiement') $reg[1]='Payment'; + print ' '.$langs->trans($reg[1]); + } + else + { + print ' '.$links[$key]['label']; + } + print ''; + } + } + + print ''.dol_print_date($db->jdate($objp->do),"day")."'; + print ''.dol_print_date($db->jdate($objp->dv),"day").""; + print ' '; + print ''; + print ''; + print img_edit_remove() . " "; + print ''; + print img_edit_add() .""; + print ''; + print "'; + $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db,$objp->fk_type,'c_paiement','code','libelle'); + if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); + else print $labeltype; + print "'.($objp->num_chq?$objp->num_chq:"").""; + if ($objp->url_id) + { + $companystatic->id=$objp->url_id; + $companystatic->name=$objp->nom; + $companystatic->name_alias=$objp->name_alias; + $companystatic->client=$objp->client; + $companystatic->fournisseur=$objp->fournisseur; + $companystatic->code_client=$objp->code_client; + $companystatic->code_fournisseur=$objp->code_fournisseur; + $companystatic->code_compta=$objp->code_compta; + $companystatic->code_compta_fournisseur=$objp->code_compta_fournisseur; + print $companystatic->getNomUrl(1); + } + else + { + print ' '; + } + print ''; + print $bankaccount->getNomUrl(1); + print "'; + if ($objp->amount < 0) + { + print price($objp->amount * -1); + $totalarray['totaldeb'] += $objp->amount; + } + print "'; + if ($objp->amount > 0) + { + print price($objp->amount); + $totalarray['totalcred'] += $objp->amount; + } + print " '.price($balance).' '.price($balance).'-'; + // Transaction reconciliated or edit link + if ($bankaccount->canBeConciliated() > 0) + { + if ($objp->rappro) // If line not conciliated and account can be conciliated + { + print ''.$objp->num_releve.''; + } + else if ($action == 'reconcile') + { + print 'rowid])?' checked':'').'>'; + } + } + print ''; + // Transaction reconciliated or edit link + if ($objp->rappro && $bankaccount->canBeConciliated() > 0) // If line not conciliated and account can be conciliated + { + print ''; + print img_edit(); + print ''; + } + else + { + if ($user->rights->banque->modifier || $user->rights->banque->consolidate) + { + print ''; + print img_edit(); + print ''; + } + else + { + print ''; + print img_view(); + print ''; + } + if ($bankaccount->canBeConciliated() > 0 && empty($objp->rappro)) + { + if ($db->jdate($objp->dv) < ($now - $conf->bank->rappro->warning_delay)) + { + print ' '.img_warning($langs->trans("ReconciliationLate")); + } + } + print ' '; + if ($user->rights->banque->modifier) + { + print 'rowid.'&id='.$object->id.'&page='.$page.'">'; + print img_delete(); + print ''; + } + } + print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price(-1 * $totalarray['totaldeb']).''.price($totalarray['totalcred']).'
    "; + print '
    '; + $db->free($resql); +} +else +{ + dol_print_error($db); +} + +// If no data to display after a search +if ($_POST["action"] == "search" && ! $num) +{ + print '
    '.$langs->trans("NoRecordFound").'
    '; +} + +llxFooter(); + +$db->close(); diff --git a/htdocs/compta/bank/budget.php b/htdocs/compta/bank/budget.php index 666ad0085e1..cd6d2adb796 100644 --- a/htdocs/compta/bank/budget.php +++ b/htdocs/compta/bank/budget.php @@ -76,7 +76,7 @@ if ($result) $objp = $db->fetch_object($result); $var=!$var; print ""; - print "rowid\">$objp->label"; + print "rowid\">$objp->label"; print ''.$objp->nombre.''; print ''.price(abs($objp->somme)).""; print ''.price(abs(price2num($objp->somme / $objp->nombre,'MT'))).""; diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php index 5f075ebf821..a608a71bf7d 100644 --- a/htdocs/compta/bank/card.php +++ b/htdocs/compta/bank/card.php @@ -45,6 +45,7 @@ $langs->load("companies"); $langs->load("compta"); $action=GETPOST("action"); +$cancel = GETPOST('cancel', 'alpha'); // Security check if (isset($_GET["id"]) || isset($_GET["ref"])) @@ -55,69 +56,77 @@ $fieldid = isset($_GET["ref"])?'ref':'rowid'; if ($user->societe_id) $socid=$user->societe_id; $result=restrictedArea($user,'banque',$id,'bank_account&bank_account','','',$fieldid); -$account = new Account($db); +$object = new Account($db); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels -$extralabels=$extrafields->fetch_name_optionals_label($account->table_element); +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + /* * Actions */ -if ($_POST["action"] == 'add') + +if ($cancel) $action=''; + +if ($action == 'add') { $error=0; + $db->begin(); + // Create account - $account = new Account($db); + $object = new Account($db); - $account->ref = dol_sanitizeFileName(trim($_POST["ref"])); - $account->label = trim($_POST["label"]); - $account->courant = $_POST["type"]; - $account->clos = $_POST["clos"]; - $account->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; - $account->url = $_POST["url"]; + $object->ref = dol_sanitizeFileName(trim($_POST["ref"])); + $object->label = trim($_POST["label"]); + $object->courant = $_POST["type"]; + $object->clos = $_POST["clos"]; + $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; + $object->url = $_POST["url"]; - $account->bank = trim($_POST["bank"]); - $account->code_banque = trim($_POST["code_banque"]); - $account->code_guichet = trim($_POST["code_guichet"]); - $account->number = trim($_POST["number"]); - $account->cle_rib = trim($_POST["cle_rib"]); - $account->bic = trim($_POST["bic"]); - $account->iban = trim($_POST["iban"]); - $account->domiciliation = trim($_POST["domiciliation"]); + $object->bank = trim($_POST["bank"]); + $object->code_banque = trim($_POST["code_banque"]); + $object->code_guichet = trim($_POST["code_guichet"]); + $object->number = trim($_POST["number"]); + $object->cle_rib = trim($_POST["cle_rib"]); + $object->bic = trim($_POST["bic"]); + $object->iban = trim($_POST["iban"]); + $object->domiciliation = trim($_POST["domiciliation"]); - $account->proprio = trim($_POST["proprio"]); - $account->owner_address = trim($_POST["owner_address"]); + $object->proprio = trim($_POST["proprio"]); + $object->owner_address = trim($_POST["owner_address"]); $account_number = GETPOST('account_number','alpha'); - if ($account_number <= 0) { $account->account_number = ''; } else { $account->account_number = $account_number; } - $account->accountancy_journal = trim($_POST["accountancy_journal"]); + if ($account_number <= 0) { $object->account_number = ''; } else { $object->account_number = $account_number; } + $object->accountancy_journal = trim($_POST["accountancy_journal"]); - $account->solde = $_POST["solde"]; - $account->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); + $object->solde = $_POST["solde"]; + $object->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); - $account->currency_code = trim($_POST["account_currency_code"]); + $object->currency_code = trim($_POST["account_currency_code"]); - $account->state_id = $_POST["account_state_id"]; - $account->country_id = $_POST["account_country_id"]; + $object->state_id = $_POST["account_state_id"]; + $object->country_id = $_POST["account_country_id"]; - $account->min_allowed = GETPOST("account_min_allowed",'int'); - $account->min_desired = GETPOST("account_min_desired",'int'); - $account->comment = trim($_POST["account_comment"]); + $object->min_allowed = GETPOST("account_min_allowed",'int'); + $object->min_desired = GETPOST("account_min_desired",'int'); + $object->comment = trim($_POST["account_comment"]); - if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($account->account_number)) + $object->fk_user_author = $user->id; + + if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'error'); $action='create'; // Force chargement page en mode creation $error++; } - if (empty($account->ref)) + if (empty($object->ref)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); $action='create'; // Force chargement page en mode creation $error++; } - if (empty($account->label)) + if (empty($object->label)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); $action='create'; // Force chargement page en mode creation @@ -125,79 +134,91 @@ if ($_POST["action"] == 'add') } // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$account); + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); if (! $error) { - $id = $account->create($user); + $id = $object->create($user); if ($id > 0) { // Category association $categories = GETPOST('categories'); - $account->setCategories($categories); + $object->setCategories($categories); $_GET["id"]=$id; // Force chargement page en mode visu + + $action=''; } else { - setEventMessages($account->error, $account->errors, 'errors'); + $error++; + setEventMessages($object->error, $object->errors, 'errors'); $action='create'; // Force chargement page en mode creation } } + + if (! $error) + { + $db->commit(); + } + else + { + $db->rollback(); + } } -if ($_POST["action"] == 'update' && ! $_POST["cancel"]) +if ($action == 'update') { $error=0; // Update account - $account = new Account($db); - $account->fetch($_POST["id"]); + $object = new Account($db); + $object->fetch($_POST["id"]); - $account->ref = dol_string_nospecial(trim($_POST["ref"])); - $account->label = trim($_POST["label"]); - $account->courant = $_POST["type"]; - $account->clos = $_POST["clos"]; - $account->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; - $account->url = trim($_POST["url"]); + $object->ref = dol_string_nospecial(trim($_POST["ref"])); + $object->label = trim($_POST["label"]); + $object->courant = $_POST["type"]; + $object->clos = $_POST["clos"]; + $object->rappro = (isset($_POST["norappro"]) && $_POST["norappro"])?0:1; + $object->url = trim($_POST["url"]); - $account->bank = trim($_POST["bank"]); - $account->code_banque = trim($_POST["code_banque"]); - $account->code_guichet = trim($_POST["code_guichet"]); - $account->number = trim($_POST["number"]); - $account->cle_rib = trim($_POST["cle_rib"]); - $account->bic = trim($_POST["bic"]); - $account->iban = trim($_POST["iban"]); - $account->domiciliation = trim($_POST["domiciliation"]); + $object->bank = trim($_POST["bank"]); + $object->code_banque = trim($_POST["code_banque"]); + $object->code_guichet = trim($_POST["code_guichet"]); + $object->number = trim($_POST["number"]); + $object->cle_rib = trim($_POST["cle_rib"]); + $object->bic = trim($_POST["bic"]); + $object->iban = trim($_POST["iban"]); + $object->domiciliation = trim($_POST["domiciliation"]); - $account->proprio = trim($_POST["proprio"]); - $account->owner_address = trim($_POST["owner_address"]); + $object->proprio = trim($_POST["proprio"]); + $object->owner_address = trim($_POST["owner_address"]); $account_number = GETPOST('account_number', 'int'); - if ($account_number <= 0) { $account->account_number = ''; } else { $account->account_number = $account_number; } - $account->accountancy_journal = trim($_POST["accountancy_journal"]); + if ($account_number <= 0) { $object->account_number = ''; } else { $object->account_number = $account_number; } + $object->accountancy_journal = trim($_POST["accountancy_journal"]); - $account->currency_code = trim($_POST["account_currency_code"]); + $object->currency_code = trim($_POST["account_currency_code"]); - $account->state_id = $_POST["account_state_id"]; - $account->country_id = $_POST["account_country_id"]; + $object->state_id = $_POST["account_state_id"]; + $object->country_id = $_POST["account_country_id"]; - $account->min_allowed = GETPOST("account_min_allowed",'int'); - $account->min_desired = GETPOST("account_min_desired",'int'); - $account->comment = trim($_POST["account_comment"]); + $object->min_allowed = GETPOST("account_min_allowed",'int'); + $object->min_desired = GETPOST("account_min_desired",'int'); + $object->comment = trim($_POST["account_comment"]); - if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($account->account_number)) + if ($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED && empty($object->account_number)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("AccountancyCode")), null, 'error'); $action='edit'; // Force chargement page en mode creation $error++; } - if (empty($account->ref)) + if (empty($object->ref)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")), null, 'errors'); $action='edit'; // Force chargement page en mode creation $error++; } - if (empty($account->label)) + if (empty($object->label)) { setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("LabelBankCashAccount")), null, 'errors'); $action='edit'; // Force chargement page en mode creation @@ -205,22 +226,22 @@ if ($_POST["action"] == 'update' && ! $_POST["cancel"]) } // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$account); + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); if (! $error) { - $result = $account->update($user); + $result = $object->update($user); if ($result >= 0) { // Category association $categories = GETPOST('categories'); - $account->setCategories($categories); + $object->setCategories($categories); $_GET["id"]=$_POST["id"]; // Force chargement page en mode visu } else { - setEventMessages($account->error, $account->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $action='edit'; // Force chargement page edition } } @@ -229,9 +250,9 @@ if ($_POST["action"] == 'update' && ! $_POST["cancel"]) if ($_POST["action"] == 'confirm_delete' && $_POST["confirm"] == "yes" && $user->rights->banque->configurer) { // Delete - $account = new Account($db); - $account->fetch($_GET["id"]); - $account->delete(); + $object = new Account($db); + $object->fetch($_GET["id"]); + $object->delete(); header("Location: ".DOL_URL_ROOT."/compta/bank/index.php"); exit; @@ -258,7 +279,7 @@ llxHeader("",$title,$helpurl); if ($action == 'create') { - $account=new Account($db); + $object=new Account($db); print load_fiche_titre($langs->trans("NewFinancialAccount"), '', 'title_bank.png'); @@ -289,7 +310,7 @@ if ($action == 'create') // Ref print ''.$langs->trans("Ref").''; - print 'ref).'" maxlength="12">'; + print 'ref).'" maxlength="12">'; // Label print ''.$langs->trans("LabelBankCashAccount").''; @@ -304,7 +325,7 @@ if ($action == 'create') // Currency print ''.$langs->trans("Currency").''; print ''; - $selectedcode=$account->currency_code; + $selectedcode=$object->currency_code; if (! $selectedcode) $selectedcode=$conf->currency; print $form->selectCurrency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code'); //print $langs->trans("Currency".$conf->currency); @@ -314,17 +335,17 @@ if ($action == 'create') // Status print ''.$langs->trans("Status").''; print ''; - print $form->selectarray("clos", $account->status,(isset($_POST["clos"])?$_POST["clos"]:$account->clos)); + print $form->selectarray("clos", $object->status,(isset($_POST["clos"])?$_POST["clos"]:$object->clos)); print ''; // Country $selectedcode=''; if (isset($_POST["account_country_id"])) { - $selectedcode=$_POST["account_country_id"]?$_POST["account_country_id"]:$account->country_code; + $selectedcode=$_POST["account_country_id"]?$_POST["account_country_id"]:$object->country_code; } else if (empty($selectedcode)) $selectedcode=$mysoc->country_code; - $account->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules + $object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules print ''.$langs->trans("BankAccountCountry").''; print ''; @@ -354,7 +375,7 @@ if ($action == 'create') print ''.$langs->trans("Categories").''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); $c = new Categorie($db); - $cats = $c->containing($account->id,Categorie::TYPE_ACCOUNT); + $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); foreach($cats as $cat) { $arrayselected[] = $cat->id; } @@ -367,16 +388,16 @@ if ($action == 'create') print ''; // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$account->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,4,70); + $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$object->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,4,70); $doleditor->Create(); print ''; // Other attributes $parameters=array('colspan' => 3); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$account,$action); // Note that $action and $object may have been modified by hook + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook if (empty($reshook) && ! empty($extrafields->attribute_label)) { - print $account->showOptionals($extrafields,'edit',$parameters); + print $object->showOptionals($extrafields,'edit',$parameters); } print ''; @@ -387,7 +408,7 @@ if ($action == 'create') // Sold print ''.$langs->trans("InitialBankBalance").''; - print 'solde)).'">'; + print 'solde)).'">'; print ''.$langs->trans("Date").''; print ''; @@ -395,10 +416,10 @@ if ($action == 'create') print ''; print ''.$langs->trans("BalanceMinimalAllowed").''; - print 'min_allowed).'">'; + print 'min_allowed).'">'; print ''.$langs->trans("BalanceMinimalDesired").''; - print 'min_desired).'">'; + print 'min_desired).'">'; print ''; print '
    '; @@ -409,56 +430,56 @@ if ($action == 'create') // If bank account print ''.$langs->trans("BankName").''; - print ''; + print ''; print ''; // Show fields of bank account - foreach ($account->getFieldsToShow() as $val) { + foreach ($object->getFieldsToShow() as $val) { if ($val == 'BankCode') { $name = 'code_banque'; $size = 8; - $content = $account->code_banque; + $content = $object->code_banque; } elseif ($val == 'DeskCode') { $name = 'code_guichet'; $size = 8; - $content = $account->code_guichet; + $content = $object->code_guichet; } elseif ($val == 'BankAccountNumber') { $name = 'number'; $size = 18; - $content = $account->number; + $content = $object->number; } elseif ($val == 'BankAccountNumberKey') { $name = 'cle_rib'; $size = 3; - $content = $account->cle_rib; + $content = $object->cle_rib; } print ''.$langs->trans($val).''; print ''; print ''; } - $ibankey = FormBank::getIBANLabel($account); + $ibankey = FormBank::getIBANLabel($object); $bickey="BICNumber"; - if ($account->getCountryCode() == 'IN') $bickey="SWIFT"; + if ($object->getCountryCode() == 'IN') $bickey="SWIFT"; // IBAN print ''.$langs->trans($ibankey).''; - print ''; + print ''; print ''.$langs->trans($bickey).''; - print ''; + print ''; print ''.$langs->trans("BankAccountDomiciliation").''; print ""; print ''.$langs->trans("BankAccountOwner").''; - print ''; + print ''; print ''; print ''.$langs->trans("BankAccountOwnerAddress").''; print ""; print ''; @@ -473,13 +494,13 @@ if ($action == 'create') { print ''.$langs->trans("AccountancyCode").''; print ''; - print $formaccountancy->select_account($account->account_number, 'account_number', 1, '', 1, 1); + print $formaccountancy->select_account($object->account_number, 'account_number', 1, '', 1, 1); print ''; } else { print ''.$langs->trans("AccountancyCode").''; - print 'account_number).'">'; + print 'account_number).'">'; } } else @@ -488,13 +509,13 @@ if ($action == 'create') { print ''.$langs->trans("AccountancyCode").''; print ''; - print $formaccountancy->select_account($account->account_number, 'account_number', 1, '', 1, 1); + print $formaccountancy->select_account($object->account_number, 'account_number', 1, '', 1, 1); print ''; } else { print ''.$langs->trans("AccountancyCode").''; - print 'account_number).'">'; + print 'account_number).'">'; } } @@ -502,7 +523,7 @@ if ($action == 'create') if (! empty($conf->accounting->enabled)) { print ''.$langs->trans("AccountancyJournal").''; - print 'accountancy_journal).'">'; + print 'accountancy_journal).'">'; } print ''; @@ -526,15 +547,15 @@ else { if (($_GET["id"] || $_GET["ref"]) && $action != 'edit') { - $account = new Account($db); + $object = new Account($db); if ($_GET["id"]) { - $account->fetch($_GET["id"]); + $object->fetch($_GET["id"]); } if ($_GET["ref"]) { - $account->fetch(0,$_GET["ref"]); - $_GET["id"]=$account->id; + $object->fetch(0,$_GET["ref"]); + $_GET["id"]=$object->id; } /* @@ -542,123 +563,158 @@ else */ // Onglets - $head=bank_prepare_head($account); + $head=bank_prepare_head($object); dol_fiche_head($head, 'bankname', $langs->trans("FinancialAccount"),0,'account'); - /* - * Confirmation to delete - */ + $formconfirm = ''; + + // Confirmation to delete if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$account->id,$langs->trans("DeleteAccount"),$langs->trans("ConfirmDeleteAccount"),"confirm_delete"); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans("DeleteAccount"),$langs->trans("ConfirmDeleteAccount"),"confirm_delete"); } + // Print form confirm + print $formconfirm; + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref=''; + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + print ''; - $linkback = ''.$langs->trans("BackToList").''; // Ref + /* print ''; print ''; + print $form->showrefnav($object, 'ref', $linkback, 1, 'ref'); + print '';*/ // Label - print ''; - print ''; + /*print ''; + print '';*/ // Type print ''; - print ''; + print ''; // Currency print ''; - print ''; // Status - print ''; - print ''; + /*print ''; + print '';*/ // Country + /* print ''; // State print ''; + if ($object->state_id > 0) print getState($object->state_id); + print '';*/ // Conciliate print ''; - print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; - print '\n"; + // Accountancy code + print ''; + print ''; + } else { + print $object->account_number; + } + print ''; + + // Accountancy journal + if (! empty($conf->accounting->enabled)) + { + print ''; + print ''; + } + + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($account, 'ref', $linkback, 1, 'ref'); - print '
    '.$langs->trans("Label").''.$account->label.'
    '.$langs->trans("Label").''.$object->label.'
    '.$langs->trans("AccountType").''.$account->type_lib[$account->type].'
    '.$object->type_lib[$object->type].'
    '.$langs->trans("Currency").''; - $selectedcode=$account->currency_code; + print ''; + $selectedcode=$object->currency_code; if (! $selectedcode) $selectedcode=$conf->currency; print $langs->trans("Currency".$selectedcode); print '
    '.$langs->trans("Status").''.$account->getLibStatut(4).'
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("BankAccountCountry").''; - if ($account->country_id > 0) + if ($object->country_id > 0) { - $img=picto_from_langcode($account->country_code); + $img=picto_from_langcode($object->country_code); print $img?$img.' ':''; - print getCountry($account->getCountryCode(),0,$db); + print getCountry($object->getCountryCode(),0,$db); } print '
    '.$langs->trans('State').''; - if ($account->state_id > 0) print getState($account->state_id); - print '
    '.$langs->trans("Conciliable").''; - $conciliate=$account->canBeConciliated(); + print ''; + $conciliate=$object->canBeConciliated(); if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; - else print ($account->rappro==1 ? $langs->trans("Yes") : ($langs->trans("No").' ('.$langs->trans("ConciliationDisabled").')')); + else print ($object->rappro==1 ? $langs->trans("Yes") : ($langs->trans("No").' ('.$langs->trans("ConciliationDisabled").')')); print '
    '.$langs->trans("BalanceMinimalAllowed").''.$account->min_allowed.'
    '.$object->min_allowed.'
    '.$langs->trans("BalanceMinimalDesired").''.$account->min_desired.'
    '.$object->min_desired.'
    '.$langs->trans("Web").''; - if ($account->url) print ''; - print $account->url; - if ($account->url) print ''; - print "
    '.$langs->trans("AccountancyCode").''; + if (! empty($conf->accounting->enabled)) { + print length_accountg($object->account_number).'
    '.$langs->trans("AccountancyJournal").''.$object->accountancy_journal.'
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + + print ''; + // Categories - if($conf->categorie->enabled) { - print '"; } print ''; - print ''; - - // Other attributes - $parameters=array('colspan' => 3); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$account,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && ! empty($extrafields->attribute_label)) - { - print $account->showOptionals($extrafields); - } + print ''; print '
    '.$langs->trans("Categories").''; - print $form->showCategories($account->id,'account',1); + if ($conf->categorie->enabled) { + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'account',1); print "
    '.$langs->trans("Comment").''.dol_htmlentitiesbr($account->comment).'
    '.dol_htmlentitiesbr($object->comment).'
    '; - - print '
    '; - - if ($account->type == Account::TYPE_SAVINGS || $account->type == Account::TYPE_CURRENT) + + + if ($object->type == Account::TYPE_SAVINGS || $object->type == Account::TYPE_CURRENT) { - print ''; + print '
    '; + + print '
    '; + + print '
    '; - print ''; - print ''; + print ''; + print ''; // Show fields of bank account - foreach ($account->getFieldsToShow() as $val) { + foreach ($object->getFieldsToShow() as $val) { if ($val == 'BankCode') { - $content = $account->code_banque; + $content = $object->code_banque; } elseif ($val == 'DeskCode') { - $content = $account->code_guichet; + $content = $object->code_guichet; } elseif ($val == 'BankAccountNumber') { - $content = $account->number; + $content = $object->number; } elseif ($val == 'BankAccountNumberKey') { - $content = $account->cle_rib; + $content = $object->cle_rib; } print ''; @@ -666,14 +722,14 @@ else print ''; } - $ibankey = FormBank::getIBANLabel($account); + $ibankey = FormBank::getIBANLabel($object); $bickey="BICNumber"; - if ($account->getCountryCode() == 'IN') $bickey="SWIFT"; + if ($object->getCountryCode() == 'IN') $bickey="SWIFT"; print ''; - print ''; print ''; - print ''; - print '\n"; - print '\n"; - print '\n"; print '
    '.$langs->trans("BankName").''.$account->bank.'
    '.$langs->trans("BankName").''.$object->bank.'
    '.$langs->trans($val).'
    '.$langs->trans($ibankey).''.$account->iban.' '; - if (! empty($account->iban)) { - if (! checkIbanForAccount($account)) { + print ''.$object->iban.' '; + if (! empty($object->iban)) { + if (! checkIbanForAccount($object)) { print img_picto($langs->trans("IbanNotValid"),'warning'); } else { print img_picto($langs->trans("IbanValid"),'info'); @@ -682,9 +738,9 @@ else print '
    '.$langs->trans($bickey).''.$account->bic.' '; - if (! empty($account->bic)) { - if (! checkSwiftForAccount($account)) { + print ''.$object->bic.' '; + if (! empty($object->bic)) { + if (! checkSwiftForAccount($object)) { print img_picto($langs->trans("SwiftNotValid"),'warning'); } else { print img_picto($langs->trans("SwiftValid"),'info'); @@ -692,44 +748,28 @@ else } print '
    '.$langs->trans("BankAccountDomiciliation").''; - print nl2br($account->domiciliation); + print '
    '.$langs->trans("BankAccountDomiciliation").''; + print nl2br($object->domiciliation); print "
    '.$langs->trans("BankAccountOwner").''; - print $account->proprio; + print '
    '.$langs->trans("BankAccountOwner").''; + print $object->proprio; print "
    '.$langs->trans("BankAccountOwnerAddress").''; - print nl2br($account->owner_address); + print '
    '.$langs->trans("BankAccountOwnerAddress").''; + print nl2br($object->owner_address); print "
    '; - print '
    '; } - print ''; - // Accountancy code - print ''; - print ''; - } else { - print $account->account_number; - } - print ''; - - // Accountancy journal - if (! empty($conf->accounting->enabled)) - { - print ''; - print ''; - } - - print '
    '.$langs->trans("AccountancyCode").''; - if (! empty($conf->accounting->enabled)) { - print length_accountg($account->account_number).'
    '.$langs->trans("AccountancyJournal").''.$account->accountancy_journal.'
    '; - + print '
    '; + print '
    '; print '
    '; + print '
    '; + + dol_fiche_end(); /* * Barre d'actions @@ -738,13 +778,13 @@ else if ($user->rights->banque->configurer) { - print 'id.'">'.$langs->trans("Modify").''; + print 'id.'">'.$langs->trans("Modify").''; } - $canbedeleted=$account->can_be_deleted(); // Renvoi vrai si compte sans mouvements + $canbedeleted=$object->can_be_deleted(); // Renvoi vrai si compte sans mouvements if ($user->rights->banque->configurer && $canbedeleted) { - print 'id.'">'.$langs->trans("Delete").''; + print 'id.'">'.$langs->trans("Delete").''; } print '
    '; @@ -759,8 +799,8 @@ else if (GETPOST('id','int') && $action == 'edit' && $user->rights->banque->configurer) { - $account = new Account($db); - $account->fetch(GETPOST('id','int')); + $object = new Account($db); + $object->fetch(GETPOST('id','int')); print load_fiche_titre($langs->trans("EditFinancialAccount"), '', 'title_bank.png'); @@ -783,35 +823,37 @@ else print ''."\n"; } - print '
    '; + print ''; print ''; print ''; print ''."\n\n"; dol_fiche_head(''); + print '
    '; + print ''; // Ref print ''; - print ''; + print ''; // Label print ''; - print ''; + print ''; // Type print ''; - print ''; // Currency print ''; - print ''; - print ''; // Country - $account->country_id=$account->country_id?$account->country_id:$mysoc->country_id; - $selectedcode=$account->country_code; + $object->country_id=$object->country_id?$object->country_id:$mysoc->country_id; + $selectedcode=$object->country_code; if (isset($_POST["account_country_id"])) $selectedcode=$_POST["account_country_id"]; else if (empty($selectedcode)) $selectedcode=$mysoc->country_code; - $account->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules + $object->country_code = getCountry($selectedcode, 2); // Force country code on account to have following field on bank fields matching country rules print ''; - print ''; // State - print ''; - print ''; - print ''; + print ''; print ''; - print ''; + print ''; // Web print ''; - print ''; // Tags-Categories if ($conf->categorie->enabled) { - print ''; - print ''; // Other attributes $parameters=array('colspan' => 3); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$account,$action); // Note that $action and $object may have been modified by hook + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook if (empty($reshook) && ! empty($extrafields->attribute_label)) { - print $account->showOptionals($extrafields,'edit'); + print $object->showOptionals($extrafields,'edit'); } print '
    '.$langs->trans("Ref").'ref).'">
    ref).'">
    '.$langs->trans("Label").'label).'">
    label).'">
    '.$langs->trans("AccountType").''; - $formbank->selectTypeOfBankAccount((isset($_POST["type"])?$_POST["type"]:$account->type),"type"); + print ''; + $formbank->selectTypeOfBankAccount((isset($_POST["type"])?$_POST["type"]:$object->type),"type"); print '
    '.$langs->trans("Currency"); - print ''; + print ''; print ''; - $selectedcode=$account->currency_code; + print ''; + $selectedcode=$object->currency_code; if (! $selectedcode) $selectedcode=$conf->currency; print $form->selectCurrency((isset($_POST["account_currency_code"])?$_POST["account_currency_code"]:$selectedcode), 'account_currency_code'); //print $langs->trans("Currency".$conf->currency); @@ -820,28 +862,28 @@ else // Status print '
    '.$langs->trans("Status").''; - print $form->selectarray("clos", $account->status,(isset($_POST["clos"])?$_POST["clos"]:$account->clos)); + print ''; + print $form->selectarray("clos", $object->status,(isset($_POST["clos"])?$_POST["clos"]:$object->clos)); print '
    '.$langs->trans("Country").''; + print ''; print $form->select_country($selectedcode,'account_country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); print '
    '.$langs->trans('State').''; + print '
    '.$langs->trans('State').''; if ($selectedcode) { - print $formcompany->select_state(isset($_POST["account_state_id"])?$_POST["account_state_id"]:$account->state_id,$selectedcode,'account_state_id'); + print $formcompany->select_state(isset($_POST["account_state_id"])?$_POST["account_state_id"]:$object->state_id,$selectedcode,'account_state_id'); } else { @@ -851,8 +893,8 @@ else // Conciliable print '
    '.$langs->trans("Conciliable").''; - $conciliate=$account->canBeConciliated(); + print ''; + $conciliate=$object->canBeConciliated(); if ($conciliate == -2) print $langs->trans("No").' ('.$langs->trans("CashAccount").')'; else if ($conciliate == -3) print $langs->trans("No").' ('.$langs->trans("Closed").')'; else print ' 0)?'':' checked="checked"').'"> '.$langs->trans("DisableConciliation"); @@ -860,20 +902,20 @@ else // Balance print '
    '.$langs->trans("BalanceMinimalAllowed").'min_allowed).'">
    min_allowed).'">
    '.$langs->trans("BalanceMinimalDesired").'min_desired).'">
    min_desired).'">
    '.$langs->trans("Web").'url).'">'; + print 'url).'">'; print '
    '.$langs->trans("Categories").''; + print '
    '.$langs->trans("Categories").''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_ACCOUNT, '', 'parent', 64, 0, 1); $c = new Categorie($db); $cats = $c->containing($object->id,Categorie::TYPE_ACCOUNT); @@ -886,50 +928,85 @@ else // Comment print '
    '.$langs->trans("Comment").''; + print ''; // Editor wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$account->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,4,70); + $doleditor=new DolEditor('account_comment',(GETPOST("account_comment")?GETPOST("account_comment"):$object->comment),'',90,'dolibarr_notes','',false,true,$conf->global->FCKEDITOR_ENABLE_SOCIETE,4,70); $doleditor->Create(); print '
    '; print '
    '; + + print '
    '; + + print ''; + + // Accountancy code + $tdextra = ' class="titlefieldcreate"'; + + if (!empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) { + $tdextra = ' class="fieldrequired titlefieldcreate"'; + } + + print ''.$langs->trans("AccountancyCode").''; + print ''; + + // Accountancy journal + if (! empty($conf->accounting->enabled)) + { + print ''; + print ''; + } + + print '
    '; + if (!empty($conf->accounting->enabled)) { + print $formaccountancy->select_account($object->account_number, 'account_number', 1, '', 1, 1); + } else { + print 'account_number).'">'; + } + print '
    '.$langs->trans("AccountancyJournal").'accountancy_journal).'">
    '; + + if ($_POST["type"] == Account::TYPE_SAVINGS || $_POST["type"] == Account::TYPE_CURRENT) { + print '
    '; + + print '
    '; + print ''; // If bank account - print ''; - print ''; + print ''; + print ''; print ''; // Show fields of bank account - foreach ($account->getFieldsToShow() as $val) { + foreach ($object->getFieldsToShow() as $val) { if ($val == 'BankCode') { $name = 'code_banque'; $size = 8; - $content = $account->code_banque; + $content = $object->code_banque; } elseif ($val == 'DeskCode') { $name = 'code_guichet'; $size = 8; - $content = $account->code_guichet; + $content = $object->code_guichet; } elseif ($val == 'BankAccountNumber') { $name = 'number'; $size = 18; - $content = $account->number; + $content = $object->number; } elseif ($val == 'BankAccountNumberKey') { $name = 'cle_rib'; $size = 3; - $content = $account->cle_rib; + $content = $object->cle_rib; } print ''; @@ -937,62 +1014,34 @@ else print ''; } - $ibankey = FormBank::getIBANLabel($account); + $ibankey = FormBank::getIBANLabel($object); $bickey="BICNumber"; - if ($account->getCountryCode() == 'IN') $bickey="SWIFT"; + if ($object->getCountryCode() == 'IN') $bickey="SWIFT"; // IBAN print ''; - print ''; + print ''; print ''; - print ''; + print ''; - print '"; print ''; - print ''; + print ''; + print ''; - print '"; print '
    '.$langs->trans("BankName").'
    '.$langs->trans("BankName").'
    '.$langs->trans($val).'
    '.$langs->trans($ibankey).'
    '.$langs->trans($bickey).'
    '.$langs->trans("BankAccountDomiciliation").''; + print '
    '.$langs->trans("BankAccountDomiciliation").''; print "
    '.$langs->trans("BankAccountOwner").''; - print '
    '.$langs->trans("BankAccountOwnerAddress").''; + print '
    '.$langs->trans("BankAccountOwnerAddress").''; print "
    '; - print '
    '; } - print ''; - - // Accountancy code - $tdextra = ' class="titlefieldcreate"'; - - if (!empty($conf->global->MAIN_BANK_ACCOUNTANCY_CODE_ALWAYS_REQUIRED)) { - $tdextra = ' class="fieldrequired titlefieldcreate"'; - } - - print ''.$langs->trans("AccountancyCode").''; - print ''; - - // Accountancy journal - if (! empty($conf->accounting->enabled)) - { - print ''; - print ''; - } - - print '
    '; - if (!empty($conf->accounting->enabled)) { - print $formaccountancy->select_account($account->account_number, 'account_number', 1, '', 1, 1); - } else { - print 'account_number).'">'; - } - print '
    '.$langs->trans("AccountancyJournal").'accountancy_journal).'">
    '; - dol_fiche_end(); print '
    '; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 7d34c637265..29f04d8f82d 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -38,7 +38,8 @@ class Account extends CommonObject { public $element = 'bank_account'; public $table_element = 'bank_account'; - + public $picto = 'account'; + /** * @var int Use id instead of rowid * @deprecated @@ -500,9 +501,10 @@ class Account extends CommonObject * Create bank account into database * * @param User $user Object user making creation + * @param int $notrigger 1=Disable triggers * @return int < 0 if KO, > 0 if OK */ - function create(User $user = null) + function create(User $user = null, $notrigger=0) { global $langs,$conf, $hookmanager; @@ -537,6 +539,8 @@ class Account extends CommonObject $now=dol_now(); + $this->db->begin(); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account ("; $sql.= "datec"; $sql.= ", ref"; @@ -593,7 +597,7 @@ class Account extends CommonObject { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account"); - $result=$this->update($user); + $result=$this->update($user, 1); if ($result > 0) { $accline = new AccountLine($this->db); @@ -606,52 +610,68 @@ class Account extends CommonObject $accline->fk_type = 'SOLD'; if ($accline->insert() < 0) { - return -3; + $error++; } - // Actions on extra fields (by external module or standard code) - $hookmanager->initHooks(array('bankdao')); - $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 (! $error) + { + $result=$this->insertExtraFields(); + if ($result < 0) $error++; + } + + if (! $error && ! $notrigger) { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - return -4; - } - } - } - else if ($reshook < 0) return -5; + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + else + { + $error++; } - return $this->id; } else { if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error=$langs->trans("ErrorBankLabelAlreadyExists"); - return -1; + $error++; } else { $this->error=$this->db->error()." sql=".$sql; - return -2; + $error++; } } + + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1*$error; + } } /** * Update bank account card * * @param User $user Object user making action + * @param int $notrigger 1=Disable triggers * @return int <0 si ko, >0 si ok */ - function update(User $user = null) + function update(User $user = null, $notrigger = 0) { global $langs,$conf, $hookmanager; + $error=0; + + $this->db->begin(); + // Clean parameters $this->state_id = ($this->state_id?$this->state_id:$this->state_id); $this->country_id = ($this->country_id?$this->country_id:$this->country_id); @@ -710,33 +730,41 @@ class Account extends CommonObject $result = $this->db->query($sql); if ($result) { - // Actions on extra fields (by external module or standard code) - $hookmanager->initHooks(array('bankdao')); - $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) - { - return -1; - } - } - } - else if ($reshook < 0) return -1; - - - return 1; + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + if (! $error) + { + $result=$this->insertExtraFields(); + if ($result < 0) $error++; + } + } + + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user); + if ($result < 0) $error++; + // End call triggers + } } else { + $error++; $this->error=$this->db->lasterror(); dol_print_error($this->db); - return -1; } + + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->db->rollback(); + return -1*$error; + } } @@ -980,10 +1008,10 @@ class Account extends CommonObject /** - * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * Return label of object status * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long - * @return string Libelle + * @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 */ function getLibStatut($mode=0) { @@ -991,11 +1019,11 @@ class Account extends CommonObject } /** - * Renvoi le libelle d'un statut donne + * Return label of given object status * - * @param int $statut Id statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut + * @param int $statut Id statut + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto + * @return string Label */ function LibStatut($statut, $mode = 0) { @@ -1018,6 +1046,8 @@ class Account extends CommonObject return $picto.' '.$label; } elseif ($mode == 5) { return $label.' '.$picto; + } elseif ($mode == 6) { + return $label.' '.$picto; } //There is no short mode for this label @@ -1183,14 +1213,18 @@ class Account extends CommonObject */ function getNomUrl($withpicto=0, $mode='') { - global $langs; + global $conf, $langs; $result=''; $label = '' . $langs->trans("ShowAccount") . ''; - if (! empty($this->label)) - $label .= '
    ' . $langs->trans('Account') . ': ' . $this->label; - if (! empty($this->number)) - $label .= '
    ' . $langs->trans('AccountNumber') . ': ' . $this->number; + $label .= '
    ' . $langs->trans('BankAccount') . ': ' . $this->label; + $label .= '
    ' . $langs->trans('AccountNumber') . ': ' . $this->number; + if (! empty($conf->accounting->enabled)) + { + $langs->load("accountancy"); + $label .= '
    ' . $langs->trans('AccountAccounting') . ': ' . $this->account_number; + $label .= '
    ' . $langs->trans('AccountancyJournal') . ': ' . $this->accountancy_journal; + } $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; if (empty($mode)) @@ -1200,7 +1234,7 @@ class Account extends CommonObject } else if ($mode == 'transactions') { - $link = ''; } else if ($mode == 'receipts') @@ -1210,7 +1244,7 @@ class Account extends CommonObject } if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' '); - $result.=$link.$this->label.$linkend; + $result.=$link.$this->ref.$linkend; return $result; } @@ -1259,8 +1293,6 @@ class Account extends CommonObject // For backward compatibility, we try to guess country from other information if (! empty($this->iban)) { - if ($mysoc->country_code === 'IN') return $mysoc->country_code; // Test to know if we can trust IBAN - // If IBAN defined, we can know country of account from it if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1]; } @@ -1366,11 +1398,12 @@ class Account extends CommonObject * - DeskCode * * Some countries show less or more bank account properties to the user - * + * + * @param int $includeibanbic 1=Return also key for IBAN and BIC * @return array * @see useDetailedBBAN */ - public function getFieldsToShow() + public function getFieldsToShow($includeibanbic=0) { //Get the required properties depending on the country $detailedBBAN = $this->useDetailedBBAN(); @@ -1389,8 +1422,11 @@ class Account extends CommonObject } //if ($this->needIBAN()) { // return always IBAN and BIC (this was old behaviour) + if ($includeibanbic) + { $fieldarray[]='IBAN'; $fieldarray[]='BIC'; + } //} //Get the order the properties are shown @@ -1452,8 +1488,9 @@ class Account extends CommonObject */ function initAsSpecimen() { + $this->specimen = 1; $this->ref = 'MBA'; - $this->label = 'My Bank account'; + $this->label = 'My Big Company Bank account'; $this->bank = 'MyBank'; $this->courant = Account::TYPE_CURRENT; $this->clos = Account::STATUS_OPEN; @@ -1463,7 +1500,7 @@ class Account extends CommonObject $this->cle_rib = 50; $this->bic = 'AA12'; $this->iban = 'FR999999999'; - $this->domiciliation = 'The bank addresse'; + $this->domiciliation = 'My bank address'; $this->proprio = 'Owner'; $this->owner_address = 'Owner address'; $this->country_id = 1; @@ -1498,7 +1535,7 @@ class AccountLine extends CommonObject var $fk_user_rappro; var $fk_type; var $rappro; // Is it conciliated - var $num_releve; // If conciliated, what is bank receipt + var $num_releve; // If conciliated, what is bank statement var $num_chq; // Num of cheque var $bank_chq; // Bank of cheque var $fk_bordereau; // Id of cheque receipt @@ -1618,7 +1655,7 @@ class AccountLine extends CommonObject $sql .= ", '".$this->db->idate($this->datev)."'"; $sql .= ", '".$this->db->escape($this->label)."'"; $sql .= ", ".price2num($this->amount); - $sql .= ", '".$this->fk_user_author."'"; + $sql .= ", ".($this->fk_user_author > 0 ? "'".$this->fk_user_author."'":"null"); $sql .= ", ".($this->num_chq ? "'".$this->num_chq."'" : "null"); $sql .= ", '".$this->fk_account."'"; $sql .= ", '".$this->db->escape($this->fk_type)."'"; @@ -1768,8 +1805,20 @@ class AccountLine extends CommonObject */ function update_conciliation(User $user, $cat) { + global $conf; + $this->db->begin(); + // Check statement field + if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE)) + { + if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve)) + { + $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE); + return -1; + } + } + $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET"; $sql.= " rappro = 1"; $sql.= ", num_releve = '".$this->num_releve."'"; diff --git a/htdocs/compta/bank/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php new file mode 100644 index 00000000000..7de67119d2b --- /dev/null +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -0,0 +1,379 @@ + + * + * 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.'/compta/bank/class/account.class.php'; + +/** + * API class for accounts + * + * @access protected + * @class DolibarrApiAccess {@requires user,external} + */ +class BankAccounts extends DolibarrApi +{ + + /** + * array $FIELDS Mandatory fields, checked when creating an object + */ + static $FIELDS = array( + 'ref', + 'label', + 'type', + 'currency_code', + 'country_id' + ); + + /** + * Constructor + */ + function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of accounts. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.import_key:<:'20160101')" + * @return array List of account objects + * + * @throws RestException + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') + { + $list = array(); + + if(! DolibarrApiAccess::$user->rights->banque->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank_account as t"; + $sql.= ' WHERE t.entity IN ('.getEntity('banque', 1).')'; + // 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.= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $this->db->plimit($limit + 1, $offset); + } + + dol_syslog("API Rest request"); + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + for ($i = 0; $i < min($num, ($limit <= 0 ? $num : $limit)); $i++) { + $obj = $this->db->fetch_object($result); + $account = new Account($this->db); + if ($account->fetch($obj->rowid) > 0) { + $list[] = $this->_cleanObjectDatas($account); + } + } + } else { + throw new RestException(503, 'Error when retrieving list of accounts: ' . $this->db->lasterror()); + } + + return $list; + } + + /** + * Get account by ID. + * + * @param int $id ID of account + * @return array Account object + * + * @throws RestException + */ + function get($id) + { + if (! DolibarrApiAccess::$user->rights->banque->lire) { + throw new RestException(401); + } + + $account = new Account($this->db); + $result = $account->fetch($id); + if (! $result) { + throw new RestException(404, 'account not found'); + } + + return $this->_cleanObjectDatas($account); + } + + /** + * Create account object + * + * @param array $request_data Request data + * @return int ID of account + */ + function post($request_data = null) + { + if (! DolibarrApiAccess::$user->rights->banque->configurer) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); + + $account = new Account($this->db); + foreach ($request_data as $field => $value) { + $account->$field = $value; + } + // Date of the initial balance (required to create an account). + $account->date_solde = time(); + // courant and type are the same thing but the one used when + // creating an account is courant + $account->courant = $account->type; + + if ($account->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(503, 'Error when creating account: ' . $account->error); + } + return $account->id; + } + + /** + * Update account + * + * @param int $id ID of account + * @param array $request_data data + * @return int + */ + function put($id, $request_data = null) + { + if (! DolibarrApiAccess::$user->rights->banque->configurer) { + throw new RestException(401); + } + + $account = new Account($this->db); + $result = $account->fetch($id); + if (! $result) { + throw new RestException(404, 'account not found'); + } + + foreach ($request_data as $field => $value) { + $account->$field = $value; + } + + if ($account->update(DolibarrApiAccess::$user) > 0) + return $this->get($id); + + return false; + } + + /** + * Delete account + * + * @param int $id ID of account + * @return array + */ + function delete($id) + { + if (! DolibarrApiAccess::$user->rights->banque->configurer) { + throw new RestException(401); + } + $account = new Account($this->db); + $result = $account->fetch($id); + if (! $result) { + throw new RestException(404, 'account not found'); + } + + if ($account->delete(DolibarrApiAccess::$user) < 0) { + throw new RestException(401, 'error when deleting account'); + } + + return array( + 'success' => array( + 'code' => 200, + 'message' => 'account deleted' + ) + ); + } + + /** + * Validate fields before creating an object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + function _validate($data) + { + $account = array(); + foreach (Accounts::$FIELDS as $field) { + if (! isset($data[$field])) + throw new RestException(400, "$field field missing"); + $account[$field] = $data[$field]; + } + return $account; + } + + /** + * 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->rowid); + + return $object; + } + + /** + * Get the list of lines of the account. + * + * @param int $id ID of account + * @return array Array of AccountLine objects + * + * @throws RestException + * + * @url GET {id}/lines + */ + function getLines($id) + { + $list = array(); + + if (! DolibarrApiAccess::$user->rights->banque->lire) { + throw new RestException(401); + } + + $account = new Account($this->db); + $result = $account->fetch($id); + if (! $result) { + throw new RestException(404, 'account not found'); + } + + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank "; + $sql .= " WHERE fk_account = ".$id; + $sql .= " ORDER BY rowid"; + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + for ($i = 0; $i < $num; $i++) { + $obj = $this->db->fetch_object($result); + $accountLine = new AccountLine($this->db); + if ($accountLine->fetch($obj->rowid) > 0) { + $list[] = $this->_cleanObjectDatas($accountLine); + } + } + } else { + throw new RestException(503, 'Error when retrieving list of account lines: ' . $accountLine->error); + } + + return $list; + } + + /** + * Add a line to an account + * + * @param int $id ID of account + * @param int $date Payment date (timestamp) {@from body} {@type timestamp} + * @param string $type Payment mode (TYP,VIR,PRE,LIQ,VAD,CB,CHQ...) {@from body} + * @param string $label Label {@from body} + * @param float $amount Amount (may be 0) {@from body} + * @param int $category Category + * @param string $cheque_number Cheque numberl {@from body} + * @param string $cheque_writer Name of cheque writer {@from body} + * @param string $cheque_bank Bank of cheque writer {@from body} + * @return int ID of line + * + * @url POST {id}/lines + */ + function addLine($id, $date, $type, $label, $amount, $category=0, $cheque_number='', $cheque_writer='', $cheque_bank='') + { + if (! DolibarrApiAccess::$user->rights->banque->modifier) { + throw new RestException(401); + } + + $account = new Account($this->db); + $result = $account->fetch($id); + if (! $result) { + throw new RestException(404, 'account not found'); + } + + $result = $account->addline($date, $type, $label, $amount, $cheque_number, $category, + DolibarrApiAccess::$user, $cheque_writer, $cheque_bank); + if ($result < 0) { + throw new RestException(503, 'Error when adding line to account: ' . $account->error); + } + return $result; + } + + /** + * Add a link to an account line + * + * @param int $account_id ID of account + * @param int $line_id ID of account line + * @param int $url_id ID to set in the URL {@from body} + * @param string $url URL of the link {@from body} + * @param string $label Label {@from body} + * @param string $type Type of link ('payment', 'company', 'member', ...) {@from body} + * @return int ID of link + * + * @url POST {account_id}/lines/{line_id}/links + */ + function addLink($account_id, $line_id, $url_id, $url, $label, $type) + { + if (! DolibarrApiAccess::$user->rights->banque->modifier) { + throw new RestException(401); + } + + $account = new Account($this->db); + $result = $account->fetch($account_id); + if (! $result) { + throw new RestException(404, 'account not found'); + } + + $accountLine = new AccountLine($this->db); + $result = $accountLine->fetch($line_id); + if (! $result) { + throw new RestException(404, 'account line not found'); + } + + $result = $account->add_url_line($line_id, $url_id, $url, $label, $type); + if ($result < 0) { + throw new RestException(503, 'Error when adding link to account line: ' . $account->error); + } + return $result; + } +} diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php index a014bdc5d60..0878474dcb5 100644 --- a/htdocs/compta/bank/document.php +++ b/htdocs/compta/bank/document.php @@ -139,6 +139,7 @@ else if ($action == 'confirm_deletefile' && $confirm == 'yes') { /* * View */ + $title = $langs->trans("FinancialAccount").' - '.$langs->trans("Documents"); $helpurl = ""; llxHeader('',$title,$helpurl); @@ -152,8 +153,7 @@ if ($id > 0 || !empty($ref)) { // Onglets $head = bank_prepare_head($object); - dol_fiche_head($head, 'document', $langs->trans("FinancialAccount"), 0, - 'account'); + dol_fiche_head($head, 'document', $langs->trans("FinancialAccount"), 0, 'account'); // Construit liste des fichiers @@ -166,29 +166,25 @@ if ($id > 0 || !empty($ref)) { } $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print ''; - - // Ref - print ''; - print ''; - - // Label - print ''; - print ''; - - // Status - print ''; - print ''; - print ''; + + print '
    '; + print '
    '; + + print '
    ' . $langs->trans("Ref") . ''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref'); - print '
    ' . $langs->trans("Label") . '' . $object->label . '
    ' . $langs->trans("Status") . '' . $object->getLibStatut(4) . '
    ' . $langs->trans("NbOfAttachedFiles") . '' . count($filearray) . '
    '; + print ''; print ''; print "
    ' . $langs->trans("NbOfAttachedFiles") . '' . count($filearray) . '
    ' . $langs->trans("TotalSizeOfAttachedFiles") . '' . $totalsize . ' ' . $langs->trans("bytes") . '
    \n"; - print "
    \n"; + + print '
    '; + + dol_fiche_end(); dol_htmloutput_mesg($mesg, $mesgs); + /* * Confirmation suppression fichier */ @@ -217,6 +213,7 @@ if ($id > 0 || !empty($ref)) { } else { Header('Location: index.php'); + exit; } diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index 6f9de0a5aac..bf69fe98a3b 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -67,18 +67,18 @@ if (! empty($_GET["year"])) $year=sprintf("%04d",$_GET["year"]); if (! empty($_GET["month"])) $month=sprintf("%02d",$_GET["month"]); -$acct = new Account($db); +$object = new Account($db); if ($_GET["account"] && ! preg_match('/,/',$_GET["account"])) // if for a particular account and not a list { - $result=$acct->fetch($_GET["account"]); + $result=$object->fetch($_GET["account"]); } if ($_GET["ref"]) { - $result=$acct->fetch(0,$_GET["ref"]); - $account=$acct->id; + $result=$object->fetch(0,$_GET["ref"]); + $account=$object->id; } -$result=dol_mkdir($conf->banque->dir_temp); +$result=dol_mkdir($conf->bank->dir_temp); if ($result < 0) { $langs->load("errors"); @@ -107,6 +107,8 @@ else { dol_print_error($db); } + if (empty($min)) $min = dol_now - 3600 * 24; + $log="graph.php: min=".$min." max=".$max; dol_syslog($log); @@ -202,8 +204,8 @@ else { $datas[$i] = $solde + $subtotal; } - $datamin[$i] = $acct->min_desired; - $dataall[$i] = $acct->min_allowed; + $datamin[$i] = $object->min_desired; + $dataall[$i] = $object->min_allowed; //$labels[$i] = strftime("%d",$day); $labels[$i] = $xday; @@ -223,22 +225,22 @@ else //exit; // Fabrication tableau 1 - $file= $conf->banque->dir_temp."/balance".$account."-".$year.$month.".png"; + $file= $conf->bank->dir_temp."/balance".$account."-".$year.$month.".png"; $fileurl=DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/balance".$account."-".$year.$month.".png"; $title=$langs->transnoentities("Balance").' - '.$langs->transnoentities("Month").': '.$month.' '.$langs->transnoentities("Year").': '.$year; $graph_datas=array(); foreach($datas as $i => $val) { $graph_datas[$i]=array(isset($labels[$i])?$labels[$i]:'',$datas[$i]); - if ($acct->min_desired) array_push($graph_datas[$i],$datamin[$i]); - if ($acct->min_allowed) array_push($graph_datas[$i],$dataall[$i]); + if ($object->min_desired) array_push($graph_datas[$i],$datamin[$i]); + if ($object->min_allowed) array_push($graph_datas[$i],$dataall[$i]); } $px1 = new DolGraph(); $px1->SetData($graph_datas); $arraylegends=array($langs->transnoentities("Balance")); - if ($acct->min_desired) array_push($arraylegends,$langs->transnoentities("BalanceMinimalDesired")); - if ($acct->min_allowed) array_push($arraylegends,$langs->transnoentities("BalanceMinimalAllowed")); + if ($object->min_desired) array_push($arraylegends,$langs->transnoentities("BalanceMinimalDesired")); + if ($object->min_allowed) array_push($arraylegends,$langs->transnoentities("BalanceMinimalAllowed")); $px1->SetLegend($arraylegends); $px1->SetLegendWidthMin(180); $px1->SetMaxValue($px1->GetCeilMaxValue()<0?0:$px1->GetCeilMaxValue()); @@ -346,8 +348,8 @@ else { $datas[$i] = $solde + $subtotal; } - $datamin[$i] = $acct->min_desired; - $dataall[$i] = $acct->min_allowed; + $datamin[$i] = $object->min_desired; + $dataall[$i] = $object->min_allowed; if ($xday == '15') { $labels[$i] = dol_print_date($day,"%b"); @@ -360,21 +362,21 @@ else } // Fabrication tableau 2 - $file= $conf->banque->dir_temp."/balance".$account."-".$year.".png"; + $file= $conf->bank->dir_temp."/balance".$account."-".$year.".png"; $fileurl=DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/balance".$account."-".$year.".png"; $title=$langs->transnoentities("Balance").' - '.$langs->transnoentities("Year").': '.$year; $graph_datas=array(); foreach($datas as $i => $val) { $graph_datas[$i]=array(isset($labels[$i])?$labels[$i]:'',$datas[$i]); - if ($acct->min_desired) array_push($graph_datas[$i],$datamin[$i]); - if ($acct->min_allowed) array_push($graph_datas[$i],$dataall[$i]); + if ($object->min_desired) array_push($graph_datas[$i],$datamin[$i]); + if ($object->min_allowed) array_push($graph_datas[$i],$dataall[$i]); } $px2 = new DolGraph(); $px2->SetData($graph_datas); $arraylegends=array($langs->transnoentities("Balance")); - if ($acct->min_desired) array_push($arraylegends,$langs->transnoentities("BalanceMinimalDesired")); - if ($acct->min_allowed) array_push($arraylegends,$langs->transnoentities("BalanceMinimalAllowed")); + if ($object->min_desired) array_push($arraylegends,$langs->transnoentities("BalanceMinimalDesired")); + if ($object->min_allowed) array_push($arraylegends,$langs->transnoentities("BalanceMinimalAllowed")); $px2->SetLegend($arraylegends); $px2->SetLegendWidthMin(180); $px2->SetMaxValue($px2->GetCeilMaxValue()<0?0:$px2->GetCeilMaxValue()); @@ -462,8 +464,8 @@ else { $datas[$i] = '' + $solde + $subtotal; } - $datamin[$i] = $acct->min_desired; - $dataall[$i] = $acct->min_allowed; + $datamin[$i] = $object->min_desired; + $dataall[$i] = $object->min_allowed; if (substr($textdate,6,2) == '01' || $i == 0) { $labels[$i] = substr($textdate,4,2); @@ -475,22 +477,22 @@ else } // Fabrication tableau 3 - $file= $conf->banque->dir_temp."/balance".$account.".png"; + $file= $conf->bank->dir_temp."/balance".$account.".png"; $fileurl=DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/balance".$account.".png"; $title=$langs->transnoentities("Balance")." - ".$langs->transnoentities("AllTime"); $graph_datas=array(); foreach($datas as $i => $val) { $graph_datas[$i]=array(isset($labels[$i])?$labels[$i]:'',$datas[$i]); - if ($acct->min_desired) array_push($graph_datas[$i],$datamin[$i]); - if ($acct->min_allowed) array_push($graph_datas[$i],$dataall[$i]); + if ($object->min_desired) array_push($graph_datas[$i],$datamin[$i]); + if ($object->min_allowed) array_push($graph_datas[$i],$dataall[$i]); } $px3 = new DolGraph(); $px3->SetData($graph_datas); $arraylegends=array($langs->transnoentities("Balance")); - if ($acct->min_desired) array_push($arraylegends,$langs->transnoentities("BalanceMinimalDesired")); - if ($acct->min_allowed) array_push($arraylegends,$langs->transnoentities("BalanceMinimalAllowed")); + if ($object->min_desired) array_push($arraylegends,$langs->transnoentities("BalanceMinimalDesired")); + if ($object->min_allowed) array_push($arraylegends,$langs->transnoentities("BalanceMinimalAllowed")); $px3->SetLegend($arraylegends); $px3->SetLegendWidthMin(180); $px3->SetMaxValue($px3->GetCeilMaxValue()<0?0:$px3->GetCeilMaxValue()); @@ -605,11 +607,11 @@ else $data_credit[$i] = isset($credits[substr("0".($i+1),-2)]) ? $credits[substr("0".($i+1),-2)] : 0; $data_debit[$i] = isset($debits[substr("0".($i+1),-2)]) ? $debits[substr("0".($i+1),-2)] : 0; $labels[$i] = sprintf("%02d",$i+1); - $datamin[$i] = $acct->min_desired; + $datamin[$i] = $object->min_desired; } // Fabrication tableau 4a - $file= $conf->banque->dir_temp."/movement".$account."-".$year.$month.".png"; + $file= $conf->bank->dir_temp."/movement".$account."-".$year.$month.".png"; $fileurl=DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/movement".$account."-".$year.$month.".png"; $title=$langs->transnoentities("BankMovements").' - '.$langs->transnoentities("Month").': '.$month.' '.$langs->transnoentities("Year").': '.$year; $graph_datas=array(); @@ -714,11 +716,11 @@ else $data_credit[$i] = isset($credits[substr("0".($i+1),-2)]) ? $credits[substr("0".($i+1),-2)] : 0; $data_debit[$i] = isset($debits[substr("0".($i+1),-2)]) ? $debits[substr("0".($i+1),-2)] : 0; $labels[$i] = dol_print_date(dol_mktime(12,0,0,$i+1,1,2000),"%b"); - $datamin[$i] = $acct->min_desired; + $datamin[$i] = $object->min_desired; } // Fabrication tableau 4b - $file= $conf->banque->dir_temp."/movement".$account."-".$year.".png"; + $file= $conf->bank->dir_temp."/movement".$account."-".$year.".png"; $fileurl=DOL_URL_ROOT.'/viewimage.php?modulepart=banque_temp&file='."/movement".$account."-".$year.".png"; $title=$langs->transnoentities("BankMovements").' - '.$langs->transnoentities("Year").': '.$year; $graph_datas=array(); @@ -754,36 +756,33 @@ else // Onglets -$head=bank_prepare_head($acct); +$head=bank_prepare_head($object); dol_fiche_head($head,'graph',$langs->trans("FinancialAccount"),0,'account'); -print ''; $linkback = ''.$langs->trans("BackToList").''; -// Ref -print ''; -print ''; - -// Label -print ''; -print ''; - -print '
    '.$langs->trans("Ref").''; if ($account) { if (! preg_match('/,/',$account)) { $moreparam='&month='.$month.'&year='.$year.($mode=='showalltime'?'&mode=showalltime':''); + if ($_GET["option"]!='all') { $morehtml=''.$langs->trans("ShowAllAccounts").''; - print $form->showrefnav($acct, 'ref', $linkback, 1, 'ref', 'ref', '', $moreparam); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', '', $moreparam, 0, '', '', 1); } else { $morehtml=''.$langs->trans("BackToAccount").''; - print $langs->trans("All"); + print $langs->trans("AllAccounts"); //print $morehtml; } } else { - $bankaccount=new Account($db); + $bankaccount=new Account($db); $listid=explode(',',$account); foreach($listid as $key => $id) { @@ -795,25 +794,9 @@ if ($account) } } else -{ - print $langs->trans("All"); -} -print '
    '.$langs->trans("Label").''; -if ($account && $_GET["option"]!='all') -{ - print $acct->label; -} -else { print $langs->trans("AllAccounts"); } -print '
    '; dol_fiche_end(); diff --git a/htdocs/compta/bank/index.php b/htdocs/compta/bank/index.php index a5038fc2e78..56735d15fce 100644 --- a/htdocs/compta/bank/index.php +++ b/htdocs/compta/bank/index.php @@ -33,28 +33,154 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("banks"); $langs->load("categories"); +$action=GETPOST('action','alpha'); +$massaction=GETPOST('massaction','alpha'); +$show_files=GETPOST('show_files','int'); +$confirm=GETPOST('confirm','alpha'); +$toselect = GETPOST('toselect', 'array'); + +$search_ref=GETPOST('search_ref','alpha'); +$search_label=GETPOST('search_label','alpha'); +$search_number=GETPOST('search_number','alpha'); +$statut=GETPOST('statut')?GETPOST('statut', 'alpha'):'opened'; // 'all' or ''='opened' +$optioncss = GETPOST('optioncss','alpha'); + // Security check if ($user->societe_id) $socid=$user->societe_id; $result=restrictedArea($user,'banque'); -$statut=GETPOST('statut'); +$diroutputmassaction=$conf->bank->dir_output . '/temp/massgeneration/'.$user->id; +$limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if ($page == -1) { $page = 0; } +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) $sortfield='b.label'; +if (! $sortorder) $sortorder='ASC'; + +// Initialize technical object to manage context to save list fields +$contextpage='bankaccountlist'; + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array($contextpage)); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('bankaccount'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array( + 'b.ref'=>'Ref', + 'b.label'=>'Label', +); + +$checkedtypetiers=0; +$arrayfields=array( + 'b.ref'=>array('label'=>$langs->trans("BankAccounts"), 'checked'=>1), + 'accountype'=>array('label'=>$langs->trans("AccountType"), 'checked'=>1), + 'b.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 'b.number'=>array('label'=>$langs->trans("AccountIdShort"), 'checked'=>1), + 'toreconcile'=>array('label'=>$langs->trans("TransactionsToConciliate"), 'checked'=>1), + 'b.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'b.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), + 'b.clos'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), + 'balance'=>array('label'=>$langs->trans("Balance"), 'checked'=>1, 'position'=>1010), +); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); + } +} +/* + * Actions + */ + +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array('socid'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +{ + $statut = 'all'; + $search_ref=''; + $search_label=''; + $search_number=''; + $search_statut=''; +} + + + /* * View */ +$form=new Form($db); + $title=$langs->trans('BankAccounts'); // Load array of financial accounts (opened by default) $accounts = array(); -$sql = "SELECT rowid, courant, rappro"; -$sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; +$sql = "SELECT rowid, label, courant, rappro"; +// 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 +$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)"; $sql.= " WHERE entity IN (".getEntity('bank_account', 1).")"; -if ($statut != 'all') $sql.= " AND clos = 0"; -$sql.= $db->order('label', 'ASC'); +if ($statut == 'opened') $sql.= " AND clos = 0"; +if ($statut == 'closed') $sql.= " AND clos = 1"; +if ($search_ref != '') $sql.=natural_search('b.ref', $search_ref); +if ($search_label != '') $sql.=natural_search('b.label', $search_label); +if ($search_number != '') $sql.=natural_search('b.number', $search_number); +// Add where from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + $mode=0; + if (in_array($typ, array('int','double'))) $mode=1; // Search on a numeric + if ($val && ( ($crit != '' && ! in_array($typ, array('select'))) || ! empty($crit))) + { + $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); + } +} +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +$sql.= $db->order($sortfield,$sortorder); + +// Count total nb of records +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} + +$sql.= $db->plimit($limit + 1,$offset); $resql = $db->query($sql); if ($resql) @@ -69,39 +195,217 @@ if ($resql) } $db->free($resql); } +else dol_print_error($db); -$nbtotalofrecords = $num; $help_url='EN:Module_Banks_and_Cash|FR:Module_Banques_et_Caisses|ES:Módulo_Bancos_y_Cajas'; llxHeader('',$title,$help_url); $link=''; -if ($statut == '') $link=''.$langs->trans("IncludeClosedAccount").''; -if ($statut == 'all') $link=''.$langs->trans("OnlyOpenedAccount").''; - -print_barre_liste($title,$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,$link,$num,$nbtotalofrecords,'title_bank.png',0,'','',$limit, 1); +$num_rows = count($accounts); -/* - * Comptes courants (courant = 1) - */ -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; +$arrayofselected=is_array($toselect)?$toselect:array(); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($search_ref != '') $param.='&search_ref='.$search_ref; +if ($search_label != '') $param.='&search_label='.$search_label; +if ($search_number != '') $param.='&search_number='.$search_number; +if ($statut != '') $param.='&statut='.$statut; +if ($show_files) $param.='&show_files=' .$show_files; +if ($optioncss != '') $param.='&optioncss='.$optioncss; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +// List of mass actions available +$arrayofmassactions = array( +// 'presend'=>$langs->trans("SendByMail"), +// 'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->banque->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); +if ($massaction == 'presend') $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + + +// Lines of title fields +print ''; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($title,$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,'title_bank.png',0,'','',$limit, 1); + + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); +} + +$moreforfilter=''; + + +// Bank accounts +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook +if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; +else $moreforfilter = $hookmanager->resPrint; + +if (! empty($moreforfilter)) +{ + print '
    '; + print $moreforfilter; + print '
    '; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +//$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print '
    '.$langs->trans("CurrentAccounts").''.$langs->trans("Bank").''.$langs->trans("AccountIdShort").''.$langs->trans("TransactionsToConciliate").''.$langs->trans("Status").''.$langs->trans("BankBalance").'
    '."\n"; + +// Fields title +print ''; +if (! empty($arrayfields['b.ref']['checked'])) print_liste_field_titre($arrayfields['b.ref']['label'],$_SERVER["PHP_SELF"],'b.ref','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['b.label']['checked'])) print_liste_field_titre($arrayfields['b.label']['label'],$_SERVER["PHP_SELF"],'b.label','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['accountype']['checked'])) print_liste_field_titre($arrayfields['accountype']['label'],$_SERVER["PHP_SELF"],'','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['b.number']['checked'])) print_liste_field_titre($arrayfields['b.number']['label'],$_SERVER["PHP_SELF"],'b.number','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['toreconcile']['checked'])) print_liste_field_titre($arrayfields['toreconcile']['label'],$_SERVER["PHP_SELF"],'','',$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['b.clos']['checked'])) print_liste_field_titre($arrayfields['b.clos']['label'],$_SERVER["PHP_SELF"],'b.clos','',$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['balance']['checked'])) print_liste_field_titre($arrayfields['balance']['label'],$_SERVER["PHP_SELF"],'','',$param,'align="right"',$sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; + +print ''; +// Ref +if (! empty($arrayfields['b.ref']['checked'])) +{ + print ''; +} +// Label +if (! empty($arrayfields['b.label']['checked'])) +{ + print ''; +} +// Account type +if (! empty($arrayfields['accountype']['checked'])) +{ + print ''; +} +// Number +if (! empty($arrayfields['b.number']['checked'])) +{ + print ''; +} +// Transactions to reconcile +if (! empty($arrayfields['toreconcile']['checked'])) +{ + print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Date creation +if (! empty($arrayfields['b.datec']['checked'])) +{ + print ''; +} +// Date modification +if (! empty($arrayfields['b.tms']['checked'])) +{ + print ''; +} +// Statut +if (! empty($arrayfields['b.clos']['checked'])) +{ + print ''; +} +// Balance +print ''; +// Action column +print ''; +print ''; + + + $total = array(); $found = 0; $var=true; foreach ($accounts as $key=>$type) { - if ($type == 1) - { + //if ($type == 1) + //{ $found++; $acc = new Account($db); @@ -112,7 +416,10 @@ foreach ($accounts as $key=>$type) print ''; print ''; - print ''; + print ''; + print ''; print ''; print ''; - print ''; + // Status + print ''; + // print ''; - print ''; - - $total[$acc->currency_code] += $solde; - } -} -if (! $found) print ''; -// Total -foreach ($total as $key=>$solde) -{ - print ''; -} - -print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + print ''; + print ''; + $array=array( + 'opened'=>$langs->trans("Opened"), + 'closed'=>$langs->trans("Closed") + ); + print $form->selectarray("statut", $array, $statut, 1); + print ''; +$searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); +print $searchpitco; +print '
    '.$acc->getNomUrl(1).''.$acc->bank.''.$acc->label.''; + print $acc->type_lib[$acc->type]; + print ''.$acc->number.''; if ($acc->rappro) @@ -127,147 +434,41 @@ foreach ($accounts as $key=>$type) } else print $langs->trans("FeatureDisabled"); print ''.$acc->getLibStatut(2).''.$acc->getLibStatut(5).''; - print ''.price($solde, 0, $langs, 0, 0, -1, $acc->currency_code).''; + print ''.price($solde, 0, $langs, 0, 0, -1, $acc->currency_code).''; print '
    '.$langs->trans("None").'
    '.$langs->trans("Total").' '.$key.''.price($solde, 0, $langs, 0, 0, -1, $key).'
    '; -print '
    '; - -/* - * Comptes caisse/liquide (courant = 2) - */ -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print "\n"; - -$total = array(); $found = 0; -$var=true; -foreach ($accounts as $key=>$type) -{ - if ($type == 2) - { - $found++; - - $acc = new Account($db); - $acc->fetch($key); - - $var = !$var; - $solde = $acc->solde(1); - - print ""; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $total[$acc->currency_code] += $solde; - } -} -if (! $found) -{ - $var = !$var; - print ''; -} -// Total -foreach ($total as $key=>$solde) -{ - print ''; -} - -print '
    '.$langs->trans("CashAccounts").'   '.$langs->trans("Status").''.$langs->trans("BankBalance").'
    '.$acc->getNomUrl(1).''.$acc->bank.'  '.$acc->getLibStatut(2).''; - print ''.price($solde, 0, $langs, 0, 0, -1, $acc->currency_code).''; - print '
    '.$langs->trans("None").'
    '.$langs->trans("Total").' '.$key.''.price($solde, 0, $langs, 0, 0, -1, $key).'
    '; -print '
    '; - -/* - * Comptes placements (courant = 0) - */ -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print "\n"; - -$total = array(); $found = 0; -$var=true; -foreach ($accounts as $key=>$type) -{ - if ($type == 0) - { - $found++; - - $acc = new Account($db); - $acc->fetch($key); - - $var = !$var; - $solde = $acc->solde(1); - - print ""; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + if (! $i) $totalarray['nbfield']++; + print ''; $total[$acc->currency_code] += $solde; - } -} -if (! $found) -{ - $var = !$var; - print ''; + //} } +if (! $found) print ''; // Total foreach ($total as $key=>$solde) { - print ''; + print ''; } -print "
    '.$langs->trans("SavingAccounts").''.$langs->trans("Bank").''.$langs->trans("Numero").''.$langs->trans("TransactionsToConciliate").''.$langs->trans("Status").''.$langs->trans("BankBalance").'
    '.$acc->getNomUrl(1).''.$acc->bank.''.$acc->number.''; - if ($acc->rappro) + + // Action column + print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $result=$acc->load_board($user,$acc->id); - if ($result<0) { - setEventMessages($acc->error, $acc->errors, 'errors'); - } else { - print $result->nbtodo; - if ($result->nbtodolate) print ' ('.$result->nbtodolate.img_warning($langs->trans("Late")).')'; - } + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; } - else print $langs->trans("FeatureDisabled"); - print ''.$acc->getLibStatut(2).''; - print ''.price($solde, 0, $langs, 0, 0, -1, $acc->currency_code).''; print '
    '.$langs->trans("None").'
    '.$langs->trans("None").'
    '.$langs->trans("Total").' '.$key.''.price($solde, 0, $langs, 0, 0, -1, $key).'
    '.$langs->trans("Total").' '.$key.''.price($solde, 0, $langs, 0, 0, -1, $key).'
    "; +print ''; /* - * Boutons d'actions + * Buttons actions */ print '
    '."\n"; diff --git a/htdocs/compta/bank/ligne.php b/htdocs/compta/bank/ligne.php index 0d307115ed9..f02b4326a31 100644 --- a/htdocs/compta/bank/ligne.php +++ b/htdocs/compta/bank/ligne.php @@ -271,7 +271,7 @@ if ($result) print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print '"; diff --git a/htdocs/compta/bank/rappro.php b/htdocs/compta/bank/rappro.php deleted file mode 100644 index 8f6cd29afdb..00000000000 --- a/htdocs/compta/bank/rappro.php +++ /dev/null @@ -1,468 +0,0 @@ - - * Copyright (C) 2004-2015 Laurent Destailleur - * Copyright (C) 2010 Juanjo Menent - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2016 Marcos García - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/compta/bank/rappro.php - * \ingroup banque - * \brief Page to reconciliate bank transactions - */ - -require('../../main.inc.php'); -require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; -require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; -require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; - -$langs->load("banks"); -$langs->load("categories"); -$langs->load("bills"); - -if (! $user->rights->banque->consolidate) accessforbidden(); - -$action=GETPOST('action', 'alpha'); -$id=GETPOST('account', 'int'); - -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -if (! $sortorder) $sortorder="ASC"; -if (! $sortfield) $sortfield="dateo"; - - -/* - * Actions - */ - -// Conciliation -if ($action == 'rappro' && $user->rights->banque->consolidate) -{ - $error=0; - - // Definition, nettoyage parametres - $num_releve=trim($_POST["num_releve"]); - - if ($num_releve) - { - $bankline=new AccountLine($db); - - if (isset($_POST['rowid']) && is_array($_POST['rowid'])) - { - foreach($_POST['rowid'] as $row) - { - if($row > 0) - { - $result=$bankline->fetch($row); - $bankline->num_releve=$num_releve; //$_POST["num_releve"]; - $result=$bankline->update_conciliation($user,$_POST["cat"]); - if ($result < 0) - { - setEventMessages($bankline->error, $bankline->errors, 'errors'); - $error++; - break; - } - } - } - } - } - else - { - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); - } - - if (! $error) - { - header('Location: '.DOL_URL_ROOT.'/compta/bank/rappro.php?account='.$id); // To avoid to submit twice and allow back - exit; - } -} - -/* - * Action suppression ecriture - */ -if ($action == 'del') -{ - $bankline=new AccountLine($db); - - if ($bankline->fetch($_GET["rowid"]) > 0) { - $result = $bankline->delete($user); - if ($result < 0) { - dol_print_error($db, $bankline->error); - } - } else { - setEventMessage($langs->trans('ErrorRecordNotFound'), 'errors'); - } -} - -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; -$bankcateg = new BankCateg($db); -$options = array(); - -foreach ($bankcateg->fetchAll() as $bankcategory) { - $options[$bankcategory->id] = $bankcategory->label; -} - -/* - * View - */ - -$form=new Form($db); - -llxHeader(); - -$societestatic=new Societe($db); -$chargestatic=new ChargeSociales($db); -$memberstatic=new Adherent($db); -$paymentstatic=new Paiement($db); -$paymentsupplierstatic=new PaiementFourn($db); -$paymentvatstatic=new TVA($db); -$remisestatic = new RemiseCheque($db); - -$acct = new Account($db); -$acct->fetch($id); - -$now=dol_now(); - -$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type as type"; -$sql.= ", b.fk_bordereau"; -$sql.= ", bc.ref"; -$sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; -$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bordereau_cheque as bc ON bc.rowid=b.fk_bordereau'; -$sql.= " WHERE rappro=0 AND fk_account=".$acct->id; -$sql.= " ORDER BY $sortfield $sortorder"; -$sql.= " LIMIT 1000"; // Limit to avoid page overload - -/// ajax adjust value date -print ' - - -'; - -$resql = $db->query($sql); -if ($resql) -{ - $var=True; - $num = $db->num_rows($resql); - - print load_fiche_titre($langs->trans("Reconciliation").': '.$acct->label.'', '', 'title_bank.png'); - print '
    '; - - // Show last bank receipts - $nbmax=15; // We accept to show last 15 receipts (so we can have more than one year) - $liste=""; - $sql = "SELECT DISTINCT num_releve FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account=".$acct->id." AND num_releve IS NOT NULL"; - $sql.= $db->order("num_releve","DESC"); - $sql.= $db->plimit($nbmax+1); - print $langs->trans("LastAccountStatements").' : '; - $resqlr=$db->query($sql); - if ($resqlr) - { - $numr=$db->num_rows($resqlr); - $i=0; - $last_ok=0; - while (($i < $numr) && ($i < $nbmax)) - { - $objr = $db->fetch_object($resqlr); - if (! $last_ok) { - $last_releve = $objr->num_releve; - $last_ok=1; - } - $i++; - $liste=''.$objr->num_releve.'   '.$liste; - } - if ($numr >= $nbmax) $liste="...   ".$liste; - print $liste; - if ($numr > 0) print '

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

    '; - } - else - { - dol_print_error($db); - } - - - print ''; - print ''; - print ''; - print ''; - - print ''.$langs->trans("InputReceiptNumber").': '; - print ''; // The only default value is value we just entered - print '
    '; - if ($options) { - print $langs->trans("EventualyAddCategory").': '; - print Form::selectarray('cat', $options, GETPOST('cat'), 1); - print '
    '; - } - print '
    '.$langs->trans("ThenCheckLinesAndConciliate").' "'.$langs->trans("Conciliate").'"
    '; - - print '
    '; - - $paramlist=''; - $paramlist.="&account=".$acct->id; - - print '
    '.$langs->trans("Ref")."
    '; - print ''."\n"; - print_liste_field_titre($langs->trans("DateOperationShort"),$_SERVER["PHP_SELF"],"b.dateo","",$paramlist,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("DateValueShort"),$_SERVER["PHP_SELF"],"b.datev","",$paramlist,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"b.fk_type","",$paramlist,'align="left"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Description"),$_SERVER["PHP_SELF"],"b.label","",$paramlist,'align="left"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Debit"),$_SERVER["PHP_SELF"],"b.amount","",$paramlist,' width="60 align="right"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Credit"),$_SERVER["PHP_SELF"],"b.amount","",$paramlist,' width="60 align="right"',$sortfield,$sortorder); - print_liste_field_titre('',$_SERVER["PHP_SELF"],"","",$paramlist,' width="80 align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("ToConciliate"),$_SERVER["PHP_SELF"],"","",$paramlist,' align="center" width="80" ',$sortfield,$sortorder); - print "\n"; - - - $i = 0; - while ($i < $num) - { - $objp = $db->fetch_object($resql); - - $var=!$var; - print "\n"; -// print ''; -// print ''; - -// print "rowid."\">"; - - // Date op - print ''; - - // Date value - if (! $objp->rappro && ($user->rights->banque->modifier || $user->rights->banque->consolidate)) - { - print ''; - } - else - { - print ''; - } - - // Type + Number - $label=($langs->trans("PaymentType".$objp->type)!="PaymentType".$objp->type)?$langs->trans("PaymentType".$objp->type):$objp->type; // $objp->type is a code - if ($label=='SOLD') $label=''; - $link=''; - if ($objp->fk_bordereau>0) { - $remisestatic->id = $objp->fk_bordereau; - $remisestatic->ref = $objp->number; - $link = ' '.$remisestatic->getNomUrl(1); - } - print ''; - - // Description - print ''; - - if ($objp->amount < 0) - { - print "\n"; - } - else - { - print "\n"; - } - - if ($objp->rappro) - { - // If line already reconciliated, we show receipt - print ""; - } - else - { - // If not already reconciliated - if ($user->rights->banque->modifier) - { - print '"; - } - else - { - print ""; - } - } - - - // Show checkbox for conciliation - if ($db->jdate($objp->do) <= $now) - { - - print '"; - } - else - { - print ''; - } - - print "\n"; - - $i++; - } - $db->free($resql); - - print "
    '.dol_print_date($db->jdate($objp->do),"day").''."\n"; - print ''.dol_print_date($db->jdate($objp->dv),"day").""; - print ' '; - print ''; - print ''; - print img_edit_remove() . " "; - print ''; - print img_edit_add() .""; - print ''; - print ''; - print dol_print_date($db->jdate($objp->dv),"day"); - print ''.$label.($objp->num_chq?' '.$objp->num_chq:'').$link.''; - $reg=array(); - preg_match('/\((.+)\)/i',$objp->label,$reg); // Si texte entoure de parentheses on tente recherche de traduction - if ($reg[1] && $langs->trans($reg[1])!=$reg[1]) print $langs->trans($reg[1]); - else print $objp->label; - print ''; - - /* - * Ajout les liens (societe, company...) - */ - $newline=1; - $links = $acct->get_url($objp->rowid); - foreach($links as $key=>$val) - { - if ($newline == 0) print ' - '; - else if ($newline == 1) print '
    '; - if ($links[$key]['type']=='payment') { - $paymentstatic->id=$links[$key]['url_id']; - print ' '.$paymentstatic->getNomUrl(2); - $newline=0; - } - elseif ($links[$key]['type']=='payment_supplier') { - $paymentsupplierstatic->id=$links[$key]['url_id']; - $paymentsupplierstatic->ref=$links[$key]['label']; - print ' '.$paymentsupplierstatic->getNomUrl(1); - $newline=0; - } - elseif ($links[$key]['type']=='company') { - $societestatic->id=$links[$key]['url_id']; - $societestatic->name=$links[$key]['label']; - print $societestatic->getNomUrl(1,'',24); - $newline=0; - } - else if ($links[$key]['type']=='sc') { - $chargestatic->id=$links[$key]['url_id']; - $chargestatic->ref=$links[$key]['url_id']; - $chargestatic->lib=$langs->trans("SocialContribution"); - print ' '.$chargestatic->getNomUrl(1); - } - else if ($links[$key]['type']=='payment_sc') - { - // We don't show anything because there is 1 payment for 1 social contribution and we already show link to social contribution - /*print ''; - print img_object($langs->trans('ShowPayment'),'payment').' '; - print $langs->trans("SocialContributionPayment"); - print '';*/ - $newline=2; - } - else if ($links[$key]['type']=='payment_vat') - { - $paymentvatstatic->id=$links[$key]['url_id']; - $paymentvatstatic->ref=$links[$key]['url_id']; - $paymentvatstatic->ref=$langs->trans("VATPayment"); - print ' '.$paymentvatstatic->getNomUrl(1); - } - else if ($links[$key]['type']=='banktransfert') { - print ''; - print img_object($langs->trans('ShowTransaction'),'payment').' '; - print $langs->trans("TransactionOnTheOtherAccount"); - print ''; - } - else if ($links[$key]['type']=='member') { - print ''; - print img_object($langs->trans('ShowMember'),'user').' '; - print $links[$key]['label']; - print ''; - } - else { - //print ' - '; - print ''; - if (preg_match('/^\((.*)\)$/i',$links[$key]['label'],$reg)) - { - // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1]=='paiement') $reg[1]='Payment'; - print $langs->trans($reg[1]); - } - else - { - print $links[$key]['label']; - } - print ''; - $newline=0; - } - } - print '
    ".price($objp->amount * -1)."  ".price($objp->amount)."num_releve&account=$acct->id\">$objp->num_releve'; - - print ''; - print img_edit(); - print '  '; - - $now=dol_now(); - if ($db->jdate($objp->do) <= $now) { - print ''; - print img_delete(); - print ''; - } - else { - print " "; // We prevents the deletion because reconciliation can not be achieved until the date has elapsed and that writing appears well on the account. - } - print " '; - print 'rowid])?' checked':'').'>'; - print "'; - print $langs->trans("FutureTransaction"); - print '

    \n"; - - print '

    '; - - print "\n"; - -} -else -{ - dol_print_error($db); -} - - -llxFooter(); - -$db->close(); diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php index ff50b3e66e5..ddd86e414fa 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -21,7 +21,7 @@ /** * \file htdocs/compta/bank/releve.php * \ingroup banque - * \brief Page to show a bank receipt report + * \brief Page to show a bank statement report */ require('../../main.inc.php'); @@ -65,16 +65,29 @@ if ($user->rights->banque->consolidate && $action == 'dvprev' && ! empty($dvid)) } -$sortfield = GETPOST('sortfield', 'alpha'); -$sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +$pageplusone = GETPOST("pageplusone",'int'); +if ($pageplusone) $page = $pageplusone - 1; if ($page == -1) { $page = 0; } +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="s.nom"; -$offset = $conf->liste_limit * $page; -$pageprev = $page - 1; -$pagenext = $page + 1; +$object = new Account($db); +if ($id > 0 || ! empty($ref)) +{ + $result=$object->fetch($id, $ref); + $account = $object->id; // Force the search field on id of account +} + + +// Initialize technical object to manage context to save list fields +$contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id); /* @@ -96,12 +109,12 @@ $bankstatic=new Account($db); $banklinestatic=new AccountLine($db); $remisestatic = new RemiseCheque($db); -// Load account -$object = new Account($db); -if ($id > 0 || ! empty($ref)) -{ - $object->fetch($id, $ref); -} +// Must be before button action +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($id > 0) $param.='&id='.urlencode($id); + if (empty($num)) { @@ -126,30 +139,19 @@ if (empty($num)) $head=bank_prepare_head($object); dol_fiche_head($head,'statement',$langs->trans("FinancialAccount"),0,'account'); - print ''; - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - print ''; - - // Label - print ''; - print ''; - - print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref'); - print '
    '.$langs->trans("Label").''.$object->label.'
    '; - + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + dol_fiche_end(); + print '
    '; if ($object->canBeConciliated() > 0) { // If not cash account and can be reconciliate if ($user->rights->banque->consolidate) { - print ''.$langs->trans("Conciliate").''; + print ''.$langs->trans("Conciliate").''; } else { print ''.$langs->trans("Conciliate").''; } @@ -227,7 +229,7 @@ if (empty($num)) else { /** - * Affiche liste ecritures d'un releve + * Show list of bank statements */ $ve=$_GET["ve"]; @@ -286,7 +288,7 @@ else $mesprevnext.=''; @@ -297,7 +299,7 @@ else print ''; print ""; - print ''; + print '
    '; print ''; print ''; print ''; @@ -341,12 +343,12 @@ else $result = $db->query($sql); if ($result) { - $var=True; + $var=False; $numrows = $db->num_rows($result); $i = 0; // Ligne Solde debut releve - print ""; + print ""; print "\n"; while ($i < $numrows) @@ -362,13 +364,14 @@ else // Date de valeur print '\n"; - + print ''; + // Type and num if ($objp->fk_type == 'SOLD') { $type_label=' '; diff --git a/htdocs/compta/bank/search.php b/htdocs/compta/bank/search.php deleted file mode 100644 index 33e98f304c8..00000000000 --- a/htdocs/compta/bank/search.php +++ /dev/null @@ -1,380 +0,0 @@ - - * Copyright (C) 2004-2016 Laurent Destailleur - * Copyright (C) 2005-2010 Regis Houssin - * Copyright (C) 2012 Vinícius Nogueira - * Copyright (C) 2014 Florian Henry - * Copyright (C) 2015 Jean-François Ferry - * - * 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/compta/bank/search.php - * \ingroup banque - * \brief List of bank transactions - */ - -require('../../main.inc.php'); -require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; - -$langs->load("banks"); -$langs->load("categories"); -$langs->load("companies"); -$langs->load("margins"); - -// Security check -if ($user->societe_id) $socid=$user->societe_id; -$result=restrictedArea($user,'banque'); - -$search_ref=GETPOST('search_ref','int'); -$description=GETPOST("description",'alpha'); -$debit=GETPOST("debit",'alpha'); -$credit=GETPOST("credit",'alpha'); -$type=GETPOST("type",'alpha'); -$account=GETPOST("account",'int'); -$bid=GETPOST("bid","int"); -$search_dt_start = dol_mktime(0, 0, 0, GETPOST('search_start_dtmonth', 'int'), GETPOST('search_start_dtday', 'int'), GETPOST('search_start_dtyear', 'int')); -$search_dt_end = dol_mktime(0, 0, 0, GETPOST('search_end_dtmonth', 'int'), GETPOST('search_end_dtday', 'int'), GETPOST('search_end_dtyear', 'int')); -$search_thirdparty=GETPOST("thirdparty",'alpha'); -$search_req_nb=GETPOST("req_nb",'alpha'); - -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = GETPOST("page",'int'); -if ($page == -1) { $page = 0; } -$offset = $limit * $page; -$pageprev = $page - 1; -$pagenext = $page + 1; -if (! $sortorder) $sortorder='DESC'; -if (! $sortfield) $sortfield='b.dateo'; - - -/* - * Actions - */ - -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers -{ - $description=""; - $type=""; - $debit=""; - $credit=""; - $account=""; - $bid=""; - $search_ref=""; - $search_req_nb=''; - $search_thirdparty=''; - $thirdparty=''; -} - - -/* - * View - */ - -$companystatic=new Societe($db); -$bankaccountstatic=new Account($db); - -llxHeader('', $langs->trans("BankTransactions"), '', '', 0, 0, array(), array(), $param); - -$form = new Form($db); -$formother = new FormOther($db); - -if ($vline) $viewline = $vline; -else $viewline = 50; - -$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq,"; -$sql.= " b.fk_account, b.fk_type,"; -$sql.= " ba.rowid as bankid, ba.ref as bankref,"; -$sql.= " bu.url_id,"; -$sql.= " s.nom, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur"; -$sql.= " FROM "; -if ($bid) $sql.= MAIN_DB_PREFIX."bank_class as l,"; -$sql.= " ".MAIN_DB_PREFIX."bank_account as ba,"; -$sql.= " ".MAIN_DB_PREFIX."bank as b"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = b.rowid AND type = 'company'"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON bu.url_id = s.rowid"; -$sql.= " WHERE b.fk_account = ba.rowid"; -$sql.= " AND ba.entity IN (".getEntity('bank_account', 1).")"; -if ($search_ref) $sql.=natural_search("b.rowid", $search_ref); -if ($account > 0) $sql.=" AND b.fk_account = ".$account; -if ($search_req_nb) $sql.= " AND b.num_chq LIKE '%".$db->escape($search_req_nb)."%'"; -if ($search_thirdparty) $sql.=" AND s.nom LIKE '%".$db->escape($search_thirdparty)."%'"; -if ($bid) $sql.= " AND b.rowid=l.lineid AND l.fk_categ=".$bid; -if (! empty($type)) $sql.= " AND b.fk_type = '".$db->escape($type)."' "; -// Search period criteria -if (dol_strlen($search_dt_start)>0) $sql .= " AND b.dateo >= '" . $db->idate($search_dt_start) . "'"; -if (dol_strlen($search_dt_end)>0) $sql .= " AND b.dateo <= '" . $db->idate($search_dt_end) . "'"; -// Search criteria amount -$debit = price2num(str_replace('-','',$debit)); -$credit = price2num(str_replace('-','',$credit)); -if ($debit) $sql.= natural_search('- b.amount', $debit, 1); -if ($credit) $sql.= natural_search('b.amount', $credit, 1); -$sql.= $db->order($sortfield,$sortorder); - -$nbtotalofrecords = 0; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); -} - -$sql.= $db->plimit($limit+1,$offset); - -dol_syslog('compta/bank/search.php::', LOG_DEBUG); -$resql = $db->query($sql); -if ($resql) -{ - $var=True; - $num = $db->num_rows($resql); - $i = 0; - - $param=''; - if (!empty($search_ref)) $param.='&search_ref='.$search_ref; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if (!empty($description)) $param.='&description='.$description; - if (!empty($type)) $param.='&type='.$type; - if (!empty($debit)) $param.='&debit='.$debit; - if (!empty($credit)) $param.='&credit='.$credit; - if (!empty($account)) $param.='&account='.$account; - if (!empty($bid)) $param.='&bid='.$bid; - if (dol_strlen($search_dt_start) > 0) - $param .= '&search_start_dtmonth=' . GETPOST('search_start_dtmonth', 'int') . '&search_start_dtday=' . GETPOST('search_start_dtday', 'int') . '&search_start_dtyear=' . GETPOST('search_start_dtyear', 'int'); - if (dol_strlen($search_dt_end) > 0) - $param .= '&search_end_dtmonth=' . GETPOST('search_end_dtmonth', 'int') . '&search_end_dtday=' . GETPOST('search_end_dtday', 'int') . '&search_end_dtyear=' . GETPOST('search_end_dtyear', 'int'); - if (GETPOST("req_nb")) $param.='&req_nb='.urlencode(GETPOST("req_nb")); - if (GETPOST("thirdparty")) $param.='&thirdparty='.urlencode(GETPOST("thirdparty")); - - print '
    '."\n"; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - if (! empty($_REQUEST['bid'])) print ''; - - // Title - $bankcateg=new BankCateg($db); - if (GETPOST("bid")) - { - $result=$bankcateg->fetch(GETPOST("bid")); - print_barre_liste($langs->trans("BankTransactionForCategory",$bankcateg->label).' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_bank.png', 0, '', '', $limit); - } - else - { - print_barre_liste($langs->trans("BankTransactions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_bank.png', 0, '', '', $limit); - } - - $moreforfilter = ''; - $moreforfilter.='
    '; - $moreforfilter .= $langs->trans('Period') . ' ('.$langs->trans('DateOperationShort').') : '; - $moreforfilter .= '
    '.$langs->trans('DateStart') . ' '; - $moreforfilter .= $form->select_date($search_dt_start, 'search_start_dt', 0, 0, 1, "search_form", 1, 0, 1).'
    '; - $moreforfilter .= ' - '; - $moreforfilter .= '
    '.$langs->trans('DateEnd') . ' ' . $form->select_date($search_dt_end, 'search_end_dt', 0, 0, 1, "search_form", 1, 0, 1).'
    '; - $moreforfilter .= '
    '; - - if ($moreforfilter) - { - print '
    '; - print $moreforfilter; - print '
    '."\n"; - } - - print '
    '.$langs->trans("DateOperationShort").''.$langs->trans("DateValueShort").'
    id."\"> 
    id."\"> ".$langs->trans("InitialBankBalance")." :".price($total)." 
    '; - print ''; - print img_previous().' '; print dol_print_date($db->jdate($objp->dv),"day") .' '; + print ''; + print img_edit_remove() . " "; print ''; - print img_next().''; + print img_edit_add() .""; print "
    '."\n"; - print ''; - print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'b.rowid','',$param,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('DateOperationShort'),$_SERVER['PHP_SELF'],'b.dateo','',$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Value'),$_SERVER['PHP_SELF'],'b.datev','',$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Type"),$_SERVER['PHP_SELF'],'','',$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Numero"),$_SERVER['PHP_SELF'],'b.num_releve','',$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Description"),$_SERVER['PHP_SELF'],'','',$param,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER['PHP_SELF'],'bu.label','',$param,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Debit"),$_SERVER['PHP_SELF'],'b.amount','',$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Credit"),$_SERVER['PHP_SELF'],'b.amount','',$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Account"),$_SERVER['PHP_SELF'],'ba.ref','',$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre(''); - print "\n"; - - print ''; - print ''; - print ''; - print ''; - print ''; - // Numero - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - // Loop on each record - $total_debit=0; - $total_credit=0; - while ($i < min($num,$limit)) { - $objp = $db->fetch_object($resql); - $printline=false; - //Search Description - if ($description) { - preg_match('/\((.+)\)/i',$objp->label,$reg); // Si texte entoure de parenthese on tente recherche de traduction - if ($reg[1]) { - if ($langs->transnoentities($reg[1])==$description) { - $printline=true; - } - } elseif ($objp->label==$description) { - $printline=true; - } - } else { - $printline=true; - } - - if ($printline) { - $var=!$var; - - print ""; - - // Ref - print ''; - - // Date ope - print '\n"; - - // Date value - print '\n"; - - // Payment type - print '\n"; - - // Num - print '\n"; - - // Description - print "'; - - // Third party - print "'; - - // Debit/Credit - if ($objp->amount < 0) - { - print '\n"; - $total_debit+=$objp->amount; - } - else - { - print "\n"; - $total_credit+=$objp->amount; - } - - // Bank account - print '\n"; - - print ''; - - print ""; - } - $i++; - } - if ($num>0) { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - - print "
    '; - print ''; - print '  '; - $form->select_types_paiements(empty($type)?'':$type, 'type', '', 2, 0, 1); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $form->select_comptes($account,'account',0,'',1); - print ''; - $searchpitco=$form->showFilterAndCheckAddButtons(0); - print $searchpitco; - print '
    '; - print "rowid.'">'.img_object($langs->trans("ShowPayment").': '.$objp->rowid, 'payment', 'class="classfortooltip"').' '.$objp->rowid."   "; - print ''.dol_print_date($db->jdate($objp->do),"day")."'.dol_print_date($db->jdate($objp->dv),"day")."'; - $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db,$objp->fk_type,'c_paiement','code','libelle'); - if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); - else print $labeltype; - print "'.($objp->num_chq?$objp->num_chq:"").""; - - print "rowid."&account=".$objp->fk_account."\">"; - $reg=array(); - preg_match('/\((.+)\)/i',$objp->label,$reg); // Si texte entoure de parenthee on tente recherche de traduction - if ($reg[1] && $langs->trans($reg[1])!=$reg[1]) print $langs->trans($reg[1]); - else print dol_trunc($objp->label,40); - print " "; - - print '"; - if ($objp->url_id) - { - $companystatic->id=$objp->url_id; - $companystatic->name=$objp->nom; - $companystatic->name_alias=$objp->name_alias; - $companystatic->client=$objp->client; - $companystatic->fournisseur=$objp->fournisseur; - $companystatic->code_client=$objp->code_client; - $companystatic->code_fournisseur=$objp->code_fournisseur; - print $companystatic->getNomUrl(1); - } - else - { - print ' '; - } - print ''.price($objp->amount * -1)."  ".price($objp->amount)."'; - $bankaccountstatic->id=$objp->bankid; - $bankaccountstatic->label=$objp->bankref; - print $bankaccountstatic->getNomUrl(1); - print "
    ' . $langs->trans('Total') . '' . price($total_debit * - 1) . '' . price($total_credit) . '
    "; - print ''; - $db->free($resql); -} -else -{ - dol_print_error($db); -} - -// If no data to display after a search -if ($_POST["action"] == "search" && ! $num) -{ - print '
    '.$langs->trans("NoRecordFound").'
    '; -} - -llxFooter(); - -$db->close(); diff --git a/htdocs/compta/bank/virement.php b/htdocs/compta/bank/transfer.php similarity index 92% rename from htdocs/compta/bank/virement.php rename to htdocs/compta/bank/transfer.php index abb06d17d76..9e26d532348 100644 --- a/htdocs/compta/bank/virement.php +++ b/htdocs/compta/bank/transfer.php @@ -21,7 +21,7 @@ */ /** - * \file htdocs/compta/bank/virement.php + * \file htdocs/compta/bank/transfer.php * \ingroup banque * \brief Page de saisie d'un virement */ @@ -91,11 +91,11 @@ if ($action == 'add') $result=0; // By default, electronic transfert from bank to bank - $typefrom='PRE'; + $typefrom='VIR'; $typeto='VIR'; if ($accountto->courant == Account::TYPE_CASH || $accountfrom->courant == Account::TYPE_CASH) { - // This is transfert of change + // This is transfer of change $typefrom='LIQ'; $typeto='LIQ'; } @@ -112,7 +112,7 @@ if ($action == 'add') if (! $error) { - $mesgs = $langs->trans("TransferFromToDone","
    id."\">".$accountfrom->label."","id."\">".$accountto->label."",$amount,$langs->transnoentities("Currency".$conf->currency)); + $mesgs = $langs->trans("TransferFromToDone","id."\">".$accountfrom->label."","id."\">".$accountto->label."",$amount,$langs->transnoentities("Currency".$conf->currency)); setEventMessages($mesgs, null, 'mesgs'); $db->commit(); } @@ -157,7 +157,7 @@ print load_fiche_titre($langs->trans("MenuBankInternalTransfer"), '', 'title_ban print $langs->trans("TransferDesc"); print "

    "; -print "
    "; +print ''; print ''; print ''; diff --git a/htdocs/compta/bank/treso.php b/htdocs/compta/bank/treso.php index 2b3593cd5bd..3de977f29cf 100644 --- a/htdocs/compta/bank/treso.php +++ b/htdocs/compta/bank/treso.php @@ -22,7 +22,7 @@ /** * \file htdocs/compta/bank/treso.php * \ingroup banque - * \brief Page de detail du budget de tresorerie + * \brief Page to estimate future balance */ require '../../main.inc.php'; @@ -77,42 +77,32 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $viewline = 20; } - $acct = new Account($db); + $object = new Account($db); if ($_GET["account"]) { - $result=$acct->fetch($_GET["account"]); + $result=$object->fetch($_GET["account"]); } if ($_GET["ref"]) { - $result=$acct->fetch(0,$_GET["ref"]); - $_GET["account"]=$acct->id; + $result=$object->fetch(0,$_GET["ref"]); + $_GET["account"]=$object->id; } // Onglets - $head=bank_prepare_head($acct); + $head=bank_prepare_head($object); dol_fiche_head($head,'cash',$langs->trans("FinancialAccount"),0,'account'); print ''; $linkback = ''.$langs->trans("BackToList").''; - // Ref - print ''; - print ''; - - // Label - print ''; - print ''; - - print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($acct, 'ref', $linkback, 1, 'ref'); - print '
    '.$langs->trans("Label").''.$acct->label.'
    '; + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); dol_fiche_end(); - $solde = $acct->solde(0); + $solde = $object->solde(0); /* * Affiche tableau des echeances a venir @@ -154,7 +144,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; $sql.= " WHERE f.entity = ".$conf->entity; $sql.= " AND f.paye = 0 AND f.fk_statut = 1"; // Not paid - $sql.= " AND (f.fk_account IN (0, ".$acct->id.") OR f.fk_account IS NULL)"; // Id bank account of invoice + $sql.= " AND (f.fk_account IN (0, ".$object->id.") OR f.fk_account IS NULL)"; // Id bank account of invoice $sql.= " ORDER BY dlr ASC"; // Supplier invoices @@ -164,7 +154,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON ff.fk_soc = s.rowid"; $sql2.= " WHERE ff.entity = ".$conf->entity; $sql2.= " AND ff.paye = 0 AND fk_statut = 1"; // Not paid - $sql2.= " AND (ff.fk_account IN (0, ".$acct->id.") OR ff.fk_account IS NULL)"; // Id bank account of supplier invoice + $sql2.= " AND (ff.fk_account IN (0, ".$object->id.") OR ff.fk_account IS NULL)"; // Id bank account of supplier invoice $sql2.= " ORDER BY dlr ASC"; // Social contributions @@ -174,7 +164,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $sql3.= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as ccs ON cs.fk_type = ccs.id"; $sql3.= " WHERE cs.entity = ".$conf->entity; $sql3.= " AND cs.paye = 0"; // Not paid - $sql3.= " AND (cs.fk_account IN (0, ".$acct->id.") OR cs.fk_account IS NULL)"; // Id bank account of social contribution + $sql3.= " AND (cs.fk_account IN (0, ".$object->id.") OR cs.fk_account IS NULL)"; // Id bank account of social contribution $sql3.= " ORDER BY dlr ASC"; $error=0; @@ -332,8 +322,8 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) // Solde actuel $var=!$var; print ''; - print ''.$langs->trans("FutureBalance").' ('.$acct->currency_code.')'; - print ''.price($solde, 0, $langs, 0, 0, -1, $acct->currency_code).''; + print ''.$langs->trans("FutureBalance").' ('.$object->currency_code.')'; + print ''.price($solde, 0, $langs, 0, 0, -1, $object->currency_code).''; print ''; print ""; diff --git a/htdocs/compta/clients.php b/htdocs/compta/clients.php index 6c2d9023902..db9d4e623ca 100644 --- a/htdocs/compta/clients.php +++ b/htdocs/compta/clients.php @@ -43,7 +43,6 @@ accessforbidden(); $langs->load("companies"); $mode=GETPOST("mode"); -$modesearch=GETPOST("mode_search"); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); @@ -70,20 +69,15 @@ if ($action == 'note') $result = $db->query($sql); } -if ($mode == 'search') { - if ($modesearch == 'soc') { - $sql = "SELECT s.rowid FROM ".MAIN_DB_PREFIX."societe as s "; - $sql.= " WHERE s.nom LIKE '%".$db->escape(strtolower($socname))."%'"; - $sql.= " AND s.entity IN (".getEntity('societe', 1).")"; - } - +if ($mode == 'search') +{ $resql=$db->query($sql); if ($resql) { if ( $db->num_rows($resql) == 1) { $obj = $db->fetch_object($resql); $socid = $obj->rowid; } - $db->free(); + $db->free($resql); } } diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index 934c970accf..bf3e311c313 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -213,13 +213,13 @@ else if ($action == 'setdated' && $user->rights->deplacement->creer) { $dated=dol_mktime(GETPOST('datedhour','int'), GETPOST('datedmin','int'), GETPOST('datedsec','int'), GETPOST('datedmonth','int'), GETPOST('datedday','int'), GETPOST('datedyear','int')); $object->fetch($id); - $result=$object->setValueFrom('dated',$dated,'','','date'); + $result=$object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY'); if ($result < 0) dol_print_error($db, $object->error); } else if ($action == 'setkm' && $user->rights->deplacement->creer) { $object->fetch($id); - $result=$object->setValueFrom('km',GETPOST('km','int')); + $result=$object->setValueFrom('km', GETPOST('km','int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); if ($result < 0) dol_print_error($db, $object->error); } diff --git a/htdocs/compta/facture.php b/htdocs/compta/facture.php index 99cf9372617..40be555b2b4 100644 --- a/htdocs/compta/facture.php +++ b/htdocs/compta/facture.php @@ -70,7 +70,6 @@ if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); if (! empty($conf->margin->enabled)) $langs->load('margins'); -$sall = trim(GETPOST('sall')); $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility @@ -259,7 +258,7 @@ if (empty($reshook)) else if ($action == 'set_thirdparty' && $user->rights->facture->creer) { $object->fetch($id); - $object->setValueFrom('fk_soc', $socid); + $object->setValueFrom('fk_soc', $socid, '', null, 'int', '', $user, 'BILL_MODIFY'); header('Location: ' . $_SERVER["PHP_SELF"] . '?facid=' . $id); exit(); @@ -400,10 +399,10 @@ if (empty($reshook)) } } - else if ($action == 'set_ref_client' && $user->rights->facture->creer) + else if ($action == 'setref_client' && $user->rights->facture->creer) { $object->fetch($id); - $object->set_ref_client($_POST['ref_client']); + $object->set_ref_client(GETPOST('ref_client')); } // Classify to validated @@ -899,8 +898,7 @@ if (empty($reshook)) // Source facture $object->fac_rec = GETPOST('fac_rec'); - $id = $object->create($user); - var_dump('ggg'); + $id = $object->create($user); // This include recopy of links from recurring invoice } } @@ -1060,9 +1058,10 @@ if (empty($reshook)) $langs->trans('Deposit'), $amountdeposit, // subprice 1, // quantity - $lines[$i]->tva_tx, 0, // localtax1_tx + $lines[$i]->tva_tx, // vat rate + 0, // localtax1_tx 0, // localtax2_tx - 0, // fk_product + (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT)?0:$conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product 0, // remise_percent 0, // date_start 0, // date_end @@ -1804,6 +1803,7 @@ if (empty($reshook)) $trigger_name='BILL_SENTBYMAIL'; $paramname='id'; $mode='emailfrominvoice'; + $trackid='inv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; @@ -1982,7 +1982,7 @@ if ($action == 'create') if (empty($socid)) $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)); + $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)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); @@ -2011,9 +2011,11 @@ if ($action == 'create') if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; } - - if(!empty($soc->id)) $absolute_discount = $soc->getAvailableDiscounts(); - + + if (!empty($soc->id)) $absolute_discount = $soc->getAvailableDiscounts(); + $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc)?$objectsrc->note_public:null)); + $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null)); + if (! empty($conf->use_javascript_ajax)) { require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; @@ -2094,13 +2096,19 @@ if ($action == 'create') } print '' . "\n"; - // Predefined invoices + // 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')); $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'; @@ -2333,7 +2341,7 @@ if ($action == 'create') '; $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; // $text.=''; - $text .= ' '; @@ -2416,7 +2424,7 @@ if ($action == 'create') } // Payment term - print '' . $langs->trans('PaymentConditionsShort') . ''; + print '' . $langs->trans('PaymentConditionsShort') . ''; $form->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id'); print ''; @@ -2450,7 +2458,14 @@ if ($action == 'create') print ''; print ''; print ''; - print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:'')); + $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 ''; } @@ -2484,7 +2499,6 @@ if ($action == 'create') print ''; print '' . $langs->trans('NotePublic') . ''; print ''; - $note_public = $object->getDefaultCreateValueFor('note_public', (is_object($objectsrc)?$objectsrc->note_public:null)); $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); @@ -2494,7 +2508,6 @@ if ($action == 'create') print ''; print '' . $langs->trans('NotePrivate') . ''; print ''; - $note_private = $object->getDefaultCreateValueFor('note_private', ((! empty($origin) && ! empty($originid) && is_object($objectsrc))?$objectsrc->note_private:null)); $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); // print ' @@ -2900,78 +2913,60 @@ else if ($id > 0 || ! empty($ref)) // Invoice content - print ''; - $linkback = '' . $langs->trans("BackToList") . ''; - // Ref - print ''; - print ''; - + $morehtmlref='
    '; // Ref customer - print '
    '; - print ''; + $morehtmlref.=''; - // Third party - print ''; + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + + dol_banner_tab($object, 'ref', $linkback, 1, 'facnumber', 'ref', $morehtmlref, '', 0, '', $morehtmlright); + + print '
    '; + print '
    '; + print '
    '; + + print '
    ' . $langs->trans('Ref') . ''; - $morehtmlright = ''; - $discount = new DiscountAbsolute($db); - $result = $discount->fetch(0, $object->id); - if ($result > 0) { - $morehtmlright = '  (' . $langs->trans("CreditNoteConvertedIntoDiscount", $discount->getNomUrl(1, 'discount')) . ')'; - } - if ($result < 0) { - dol_print_error('', $discount->error); - } - print $form->showrefnav($object, 'ref', $linkback, 1, 'facnumber', 'ref', '', '', 0, '', '', $morehtmlright); - print '
    '; - print ''; - if ($action != 'refclient' && ! empty($object->brouillon)) - print ''; - print '
    '; - print $langs->trans('RefCustomer'); - print '' . img_edit($langs->trans('Modify')) . '
    '; - print '
    '; - if ($user->rights->facture->creer && $action == 'refclient') { - print ''; - print ''; - print ''; - print ''; - print ' '; - print ''; - } else { - print $object->ref_client; + $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.=''; + } + } } - print '
    '; - print ''; - print ''; - print ''; - print '
    ' . $langs->trans('Company') . ''; - if (! empty($conf->global->FACTURE_CHANGE_THIRDPARTY) && $action != 'editthirdparty' && $object->brouillon && $user->rights->facture->creer) - print 'id . '">' . img_edit($langs->trans('SetLinkToAnotherThirdParty'), 1) . '
    '; - print '
    '; - if ($action == 'editthirdparty') { - $form->form_thirdparty($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, 'socid','client>0'); - } else { - print '  ' . $soc->getNomUrl(1, 'compta'); - print '   '; - print '(' . $langs->trans('OtherBills') . ''; - // Outstanding Bill - $outstandingBills = $soc->get_OutstandingBill(); - print ' - ' . $langs->trans('CurrentOutstandingBill') . ': '; - print price($outstandingBills, '', $langs, 0, 0, - 1, $conf->currency); - if ($soc->outstanding_limit != '') - { - if ($outstandingBills > $soc->outstanding_limit) - print img_warning($langs->trans("OutstandingBillReached")); - print ' / ' . price($soc->outstanding_limit); - } - print ')'; - } - print '
    '; // Type - print ''; print '
    ' . $langs->trans('Type') . ''; + print '
    ' . $langs->trans('Type') . ''; print $object->getLibType(); if ($object->type == Facture::TYPE_REPLACEMENT) { $facreplaced = new Facture($db); @@ -3012,7 +3007,7 @@ else if ($id > 0 || ! empty($ref)) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '
    ' . $langs->trans('Discounts'); - print ''; + print ''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); else @@ -3036,7 +3031,7 @@ else if ($id > 0 || ! empty($ref)) } } } else { - // Remise dispo de type remise fixe (not credit note) + // Discount available of type fixed amount (not credit note) print '
    '; $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')'); } @@ -3093,340 +3088,21 @@ else if ($id > 0 || ! empty($ref)) if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && ! empty($object->brouillon) && $user->rights->facture->creer && empty($conf->global->FAC_FORCE_DATE_VALIDATION)) print '
    id . '">' . img_edit($langs->trans('SetDate'), 1) . '
    '; - print ''; + print ''; if ($object->type != Facture::TYPE_CREDIT_NOTE) { if ($action == 'editinvoicedate') { $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date, 'invoicedate'); } else { - print dol_print_date($object->date, 'daytext'); + print dol_print_date($object->date, 'day'); } } else { - print dol_print_date($object->date, 'daytext'); + print dol_print_date($object->date, 'day'); } print ''; - // List of payments - - $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; - - 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 ''; - - $total_prev_ht = $total_prev_ttc = 0; - $var = true; - 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 ''; - - $var = !$var; - } - - print ''; - 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; - - $var = true; - 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 ''; - - $var = !$var; - } - - 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') . ' 
    '.$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) . ' 
    ' . $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).'
    ' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
    '; - } - - print ''; - - // List of payments already done - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) - print ''; - print ''; - print ''; print ''; - $var = true; - - // 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'; - $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 .= ' ORDER BY p.datep, p.tms'; - - $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); - $var = ! $var; - 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 ''; - print ''; - print ''; - $i ++; - } - } else { - print ''; - } - // } - $db->free($result); - } else { - dol_print_error($db); - } - - if ($object->type != Facture::TYPE_CREDIT_NOTE) - { - // Total already paid - print ''; - - $resteapayeraffiche = $resteapayer; - - // 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 == 2 || $object->statut == 3) && $object->close_code == 'discount_vat') { - print ''; - $resteapayeraffiche = 0; - } - // Paye partiellement ou Abandon 'badcustomer' - if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'badcustomer') { - print ''; - // $resteapayeraffiche=0; - } - // Paye partiellement ou Abandon 'product_returned' - if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'product_returned') { - print ''; - $resteapayeraffiche = 0; - } - // Paye partiellement ou Abandon 'abandon' - if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'abandon') { - print ''; - $resteapayeraffiche = 0; - } - - // Billed - print ''; - - // Remainder to pay - print ''; - print ''; - print ''; - } - else // Credit note - { - // Total already paid back - print ''; - - // Billed - print ''; - - // Remainder to pay back - print ''; - 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') . ' 
    '; - $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 $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) . ' 
    ' . $langs->trans("None") . '
    '; - if ($object->type != Facture::TYPE_DEPOSIT) - print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); - else - print $langs->trans('AlreadyPaid'); - print ' :' . 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 '
    '; - 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) . ' 
    '; - if ($resteapayeraffiche >= 0) - print $langs->trans('RemainderToPay'); - else - print $langs->trans('ExcessReceived'); - print ' :' . price($resteapayeraffiche) . ' 
    '; - print $langs->trans('AlreadyPaidBack'); - print ' :' . price($sign * $totalpaye) . ' 
    ' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
    '; - if ($resteapayeraffiche <= 0) - print $langs->trans('RemainderToPayBack'); - else - print $langs->trans('ExcessPaydBack'); - print ' :' . price($sign * $resteapayeraffiche) . ' 
    '.$langs->trans('TotalTTC').' :'.price($sign * - // $object->total_ttc).' 
    '; - - // Margin Infos - if (! empty($conf->margin->enabled)) - { - print '
    '; - $formmargin->displayMarginInfos($object, $object->statut > 0); - } - - print ''; - if (! empty($conf->global->INVOICE_POINTOFTAX_DATE)) { // Date invoice @@ -3436,16 +3112,16 @@ else if ($id > 0 || ! empty($ref)) print ''; print 'id . '">' . img_edit($langs->trans('SetDate'), 1) . ''; print ''; - print ''; + print ''; if ($action == 'editdate_pointoftax') { $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_pointoftax, 'date_pointoftax'); } else { - print dol_print_date($object->date_pointoftax, 'daytext'); + print dol_print_date($object->date_pointoftax, 'day'); } print ''; } - // Conditions de reglement + // Payment term print ''; print ''; print '
    '; print $langs->trans('PaymentConditionsShort'); @@ -3453,7 +3129,7 @@ else if ($id > 0 || ! empty($ref)) if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer) print 'id . '">' . img_edit($langs->trans('SetConditions'), 1) . '
    '; - print ''; + print ''; if ($object->type != Facture::TYPE_CREDIT_NOTE) { if ($action == 'editconditions') { @@ -3474,13 +3150,13 @@ else if ($id > 0 || ! empty($ref)) if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && ! empty($object->brouillon) && $user->rights->facture->creer) print 'id . '">' . img_edit($langs->trans('SetDate'), 1) . ''; print ''; - print ''; + print ''; if ($object->type != Facture::TYPE_CREDIT_NOTE) { if ($action == 'editpaymentterm') { $form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_lim_reglement, 'paymentterm'); } else { - print dol_print_date($object->date_lim_reglement, 'daytext'); + print dol_print_date($object->date_lim_reglement, 'day'); if ($object->hasDelay()) { print img_warning($langs->trans('Late')); } @@ -3498,7 +3174,7 @@ else if ($id > 0 || ! empty($ref)) if ($action != 'editmode' && ! empty($object->brouillon) && $user->rights->facture->creer) print 'id . '">' . img_edit($langs->trans('SetMode'), 1) . ''; print ''; - print ''; + print ''; if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT'); @@ -3521,7 +3197,7 @@ else if ($id > 0 || ! empty($ref)) if ($action != 'editmulticurrencycode' && ! empty($object->brouillon)) print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . ''; print ''; - print ''; + print ''; if ($action == 'editmulticurrencycode') { $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); } else { @@ -3530,21 +3206,24 @@ else if ($id > 0 || ! empty($ref)) print ''; // Multicurrency rate - print ''; - print ''; - print ''; - if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon)) - print ''; - print '
    '; - print fieldLabel('CurrencyRate','multicurrency_tx'); - print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
    '; - print ''; - if ($action == 'editmulticurrencyrate') { - $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); - } - print ''; + //if ($object->multicurrency_code != $conf->currency) + //{ + print ''; + print ''; + print ''; + if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon)) + print ''; + print '
    '; + print fieldLabel('CurrencyRate','multicurrency_tx'); + print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
    '; + print ''; + if ($action == 'editmulticurrencyrate') { + $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); + } + print ''; + //} } // Bank Account @@ -3555,7 +3234,7 @@ else if ($id > 0 || ! empty($ref)) if (($action != 'editbankaccount') && $user->rights->facture->creer && ! empty($object->brouillon)) print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).''; print ''; - print ''; + print ''; if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); @@ -3568,7 +3247,7 @@ else if ($id > 0 || ! empty($ref)) print ''; // Situations - if (! empty($conf->global->INVOICE_US_SITUATION)) + if (! empty($conf->global->INVOICE_USE_SITUATION)) { if ($object->type == 5 && ($object->situation_counter > 1)) { @@ -3588,7 +3267,7 @@ else if ($id > 0 || ! empty($ref)) print $object->situation_counter; print ''; - print ''; + print ''; $prevsits_total_amount = 0; foreach ($prevsits as $situation) { @@ -3609,7 +3288,7 @@ else if ($id > 0 || ! empty($ref)) print $prevsits[$i]->situation_counter; print ''; - print ''; + print ''; print '- ' . price($prevsits[$i]->total_ht); print ''; print '' . $langs->trans('Currency' . $conf->currency) . ''; @@ -3617,100 +3296,6 @@ else if ($id > 0 || ! empty($ref)) } } - // Amount - print '' . $langs->trans('AmountHT') . ''; - print '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . ''; - print '' . $langs->trans('AmountVAT') . '' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . ''; - print ''; - - // 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) . ''; - } - 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) . ''; - } - - // 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 ''; - } - - // Total with tax - print '' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency) . ''; - - 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 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 ''; - } - - // Statut - print '' . $langs->trans('Status') . ''; - print '' . ($object->getLibStatut(4, $totalpaye)) . ''; - - // Project - if (! empty($conf->projet->enabled)) { - $langs->load('projects'); - print ''; - print ''; - - print ''; - if ($action != 'classify') { - print ''; - } - print '
    '; - print $langs->trans('Project'); - print 'id . '">'; - print img_edit($langs->trans('SetProject'), 1); - print '
    '; - - print ''; - if ($action == 'classify') { - $form->form_project($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1); - } else { - $form->form_project($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0); - } - print ''; - print ''; - } - // Incoterms if (!empty($conf->incoterm->enabled)) { @@ -3722,7 +3307,7 @@ else if ($id > 0 || ! empty($ref)) else print ' '; print ''; print ''; - print ''; + print ''; if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1); @@ -3735,10 +3320,406 @@ else if ($id > 0 || ! empty($ref)) } // Other attributes - $cols = 5; + $cols = 2; include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print '
    '; + print ''; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + { + // Multicurrency Amount HT + print ''; + print ''; + print ''; + + // Multicurrency Amount VAT + print ''; + print ''; + print ''; + + // Multicurrency Amount TTC + print ''; + print ''; + print ''; + } + + // Amount + print ''; + print ''; + + // Vat + print ''; + print ''; + + // Amount Local Taxes + if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 + { + print ''; + print ''; + } + if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 + { + print ''; + print ''; + } + + // Revenue stamp + if ($selleruserevenustamp) // Test company use revenue stamp + { + print ''; + } + + // Total with tax + 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('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)) . '
    ' . $langs->trans('AmountHT') . '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountVAT') . '' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '
    '; + 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 '
    ' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency) . '
    '; + + // List of payments + + $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; + + 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 ''; + + $total_prev_ht = $total_prev_ttc = 0; + $var = true; + 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 ''; + + $var = ! $var; + } + + print ''; + 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; + + $var = true; + 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 ''; + + $var = ! $var; + } + + 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') . ' 
    ' . $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) . ' 
    ' . $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) . '
    ' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
    '; + } + + print ''; + + // List of payments already done + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) { + print ''; + } + print ''; + print ''; + print ''; + + $var = true; + + // 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'; + $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 .= ' ORDER BY p.datep, p.tms'; + + $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); + $var = ! $var; + 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 ''; + print ''; + print ''; + $i ++; + } + } else { + print ''; + } + // } + $db->free($result); + } else { + dol_print_error($db); + } + + if ($object->type != Facture::TYPE_CREDIT_NOTE) { + // Total already paid + print ''; + + $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); + } + + // 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 ''; + + // Remainder to pay + print ''; + print ''; + print ''; + } + else // Credit note + { + // Total already paid back + print ''; + + // Billed + print ''; + + // Remainder to pay back + print ''; + 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') . ' 
    '; + $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 $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) . ' 
    ' . $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 ($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) . ' 
    ' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
    '; + if ($resteapayeraffiche >= 0) + print $langs->trans('RemainderToPay'); + else + print $langs->trans('ExcessReceived'); + print ' :' . price($resteapayeraffiche) . ' 
    '; + print $langs->trans('AlreadyPaidBack'); + print ' :' . price($sign * $totalpaye) . ' 
    ' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
    '; + if ($resteapayeraffiche <= 0) + print $langs->trans('RemainderToPayBack'); + else + print $langs->trans('ExcessPaydBack'); + print ' :' . price($sign * $resteapayeraffiche) . ' 
    '.$langs->trans('TotalTTC').' :'.price($sign * + // $object->total_ttc).' 
    '; + + // Margin Infos + if (! empty($conf->margin->enabled)) { + $formmargin->displayMarginInfos($object); + } + + print '
    '; + print '
    '; + print '
    '; + + print '

    '; if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; @@ -3769,7 +3750,7 @@ else if ($id > 0 || ! empty($ref)) print ''; // Show global modifiers - if (! empty($conf->global->INVOICE_US_SITUATION)) + if (! empty($conf->global->INVOICE_USE_SITUATION)) { if ($object->situation_cycle_ref && $object->statut == 0) { print ''; @@ -3850,8 +3831,7 @@ else if ($id > 0 || ! empty($ref)) print '
    '; $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { // Editer une facture deja validee, sans paiement effectue et pas exporte en compta if ($object->statut == 1) @@ -3883,7 +3863,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 - && $user->rights->facture->creer) // 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 { @@ -4021,7 +4001,7 @@ else if ($id > 0 || ! empty($ref)) { if (! $objectidnext) { - print ''; + print ''; } } @@ -4158,10 +4138,12 @@ else if ($id > 0 || ! empty($ref)) 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 = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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='inv'.$object->id; if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { diff --git a/htdocs/compta/facture/class/api_deprecated_invoice.class.php b/htdocs/compta/facture/class/api_deprecated_invoice.class.php index 353a48b79ef..51e047e4412 100644 --- a/htdocs/compta/facture/class/api_deprecated_invoice.class.php +++ b/htdocs/compta/facture/class/api_deprecated_invoice.class.php @@ -89,12 +89,12 @@ class InvoiceApi extends DolibarrApi * * Get a list of invoices * - * @param int $socid Filter list with thirdparty ID - * @param string $mode Filter by invoice status : draft | unpaid | paid | cancelled * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number + * @param int $socid Filter list with thirdparty ID + * @param string $mode Filter by invoice status : draft | unpaid | paid | cancelled * * @return array Array of invoice objects * @@ -103,12 +103,12 @@ class InvoiceApi extends DolibarrApi * @url GET thirdparty/{socid}/invoice/list * @url GET thirdparty/{socid}/invoice/list/{mode} */ - function getList($socid=0, $mode='', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { + function getList($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid=0, $mode='') { global $db, $conf; $obj_ret = array(); - $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : ''; + $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $socid; // If the internal user must only see his customers, force searching by him if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; @@ -160,7 +160,7 @@ class InvoiceApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $invoice_static = new Facture($db); diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index e14ed12dce3..0b2b7f58781 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -83,59 +83,59 @@ class Invoices extends DolibarrApi * * Get a list of invoices * - * FIXME this parameter is overwritten in the code and thus ignored - * @param int $socid Filter list with thirdparty ID - * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @return array Array of invoice objects + * @param int $socid Filter list with thirdparty ID + * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of invoice objects * * @throws RestException */ - function index($socid=0, $status='', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid=0, $status='', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); - $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : ''; + $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $socid; // If the internal user must only see his customers, force searching by him if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; - $sql = "SELECT s.rowid"; + $sql = "SELECT t.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"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as t"; 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', 1).')'; - 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 - + $sql.= ' WHERE t.entity IN ('.getEntity('facture', 1).')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc"; + if ($socid) $sql.= " AND t.fk_soc = ".$socid; + if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale // Filter by status - if ($status == 'draft') $sql.= " AND s.fk_statut IN (0)"; - if ($status == 'unpaid') $sql.= " AND s.fk_statut IN (1)"; - if ($status == 'paid') $sql.= " AND s.fk_statut IN (2)"; - if ($status == 'cancelled') $sql.= " AND s.fk_statut IN (3)"; - + if ($status == 'draft') $sql.= " AND t.fk_statut IN (0)"; + if ($status == 'unpaid') $sql.= " AND t.fk_statut IN (1)"; + if ($status == 'paid') $sql.= " AND t.fk_statut IN (2)"; + if ($status == 'cancelled') $sql.= " AND t.fk_statut IN (3)"; // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - - // TODO remove this, useless for WS - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + // Add sql filters + if ($sqlfilters) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + 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) @@ -151,7 +151,7 @@ class Invoices extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $invoice_static = new Facture($db); diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 1d75be61f6c..41c1171ccef 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -42,7 +42,9 @@ class FactureRec extends CommonInvoice public $table_element='facture_rec'; public $table_element_line='facturedet_rec'; public $fk_element='fk_facture'; - + public $picto='bill'; + + var $entity; var $number; var $date; var $amount; @@ -241,7 +243,7 @@ class FactureRec extends CommonInvoice */ function fetch($rowid, $ref='', $ref_ext='', $ref_int='') { - $sql = 'SELECT f.rowid, f.titre, f.fk_soc, f.amount, f.tva, f.total, f.total_ttc, f.remise_percent, f.remise_absolue, f.remise'; + $sql = 'SELECT f.rowid, f.entity, f.titre, f.fk_soc, f.amount, f.tva, f.total, f.total_ttc, f.remise_percent, f.remise_absolue, f.remise'; $sql.= ', f.date_lim_reglement as dlr'; $sql.= ', f.note_private, f.note_public, f.fk_user_author'; $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet'; @@ -269,6 +271,7 @@ class FactureRec extends CommonInvoice $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; + $this->entity = $obj->entity; $this->titre = $obj->titre; $this->ref = $obj->titre; $this->ref_client = $obj->ref_client; @@ -438,14 +441,14 @@ class FactureRec extends CommonInvoice /** * Delete template invoice * - * @param int $rowid Id of invoice to delete. If empty, we delete current instance of invoice + * @param User $user User that delete. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @param int $idwarehouse Id warehouse to use for stock change. * @return int <0 if KO, >0 if OK */ - function delete($rowid=0, $notrigger=0, $idwarehouse=-1) + function delete($user, $notrigger=0, $idwarehouse=-1) { - if (empty($rowid)) $rowid=$this->id; + $rowid=$this->id; dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); @@ -519,6 +522,7 @@ class FactureRec extends CommonInvoice { // Clean parameters $remise_percent=price2num($remise_percent); + if (empty($remise_percent)) $remise_percent=0; $qty=price2num($qty); if (! $qty) $qty=1; if (! $info_bits) $info_bits=0; @@ -579,12 +583,12 @@ class FactureRec extends CommonInvoice $sql.= ", ".price2num($txtva); $sql.= ", ".(! empty($fk_product)?"'".$fk_product."'":"null"); $sql.= ", ".$product_type; - $sql.= ", '".price2num($remise_percent)."'"; - $sql.= ", '".price2num($pu_ht)."'"; + $sql.= ", ".price2num($remise_percent); + $sql.= ", ".price2num($pu_ht); $sql.= ", null"; - $sql.= ", '".price2num($total_ht)."'"; - $sql.= ", '".price2num($total_tva)."'"; - $sql.= ", '".price2num($total_ttc)."'"; + $sql.= ", ".price2num($total_ht); + $sql.= ", ".price2num($total_tva); + $sql.= ", ".price2num($total_ttc); $sql.= ", ".$rang; $sql.= ", ".$special_code; $sql.= ", ".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null").")"; @@ -721,14 +725,16 @@ class FactureRec extends CommonInvoice } /** - * Create all recurrents invoices. - * A result may also be provided into this->output + * Create all recurrents invoices (for all entities if multicompany is used). + * A result may also be provided into this->output. + * + * WARNING: This method change context $conf->entity to be in correct context for each recurring invoice found. * * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) */ function createRecurringInvoices() { - global $langs, $db, $user; + global $conf, $langs, $db, $user; $langs->load("bills"); @@ -743,6 +749,7 @@ class FactureRec extends CommonInvoice $sql.= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency $sql.= " AND (date_when IS NULL OR date_when <= '".$db->idate($today)."')"; $sql.= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)'; + $sql.= $db->order('entity', 'ASC'); //print $sql;exit; $resql = $db->query($sql); @@ -754,7 +761,9 @@ class FactureRec extends CommonInvoice if ($num) $this->output.=$langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n"; else $this->output.=$langs->trans("NoQualifiedRecurringInvoiceTemplateFound"); - while ($i < $num) + $saventity = $conf->entity; + + while ($i < $num) // Loop on each template invoice { $line = $db->fetch_object($resql); @@ -763,7 +772,10 @@ class FactureRec extends CommonInvoice $facturerec = new FactureRec($db); $facturerec->fetch($line->rowid); - dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); + // Set entity context + $conf->entity = $facturerec->entity; + + dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity); $error=0; @@ -774,7 +786,7 @@ class FactureRec extends CommonInvoice $facture->date = $facturerec->date_when; // We could also use dol_now here but we prefer date_when so invoice has real date when we would like even if we generate later. $facture->socid = $facturerec->socid; - $invoiceidgenerated = $facture->create($user); // This will also update fields of recurring invoice + $invoiceidgenerated = $facture->create($user); if ($invoiceidgenerated <= 0) { $this->errors = $facture->errors; @@ -794,18 +806,20 @@ class FactureRec extends CommonInvoice if (! $error && $invoiceidgenerated >= 0) { - $db->commit(); + $db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation"); $nb_create++; $this->output.=$langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n"; } else { - $db->rollback(); + $db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); } $i++; } + + $conf->entity = $saventity; // Restore entity context } else dol_print_error($db); @@ -1027,7 +1041,7 @@ class FactureRec extends CommonInvoice $sql.= ' SET frequency = '.($frequency?$this->db->escape($frequency):'null'); if (!empty($unit)) { - $sql.= ', unit_frequency = "'.$this->db->escape($unit).'"'; + $sql.= ', unit_frequency = \''.$this->db->escape($unit).'\''; } $sql.= ' WHERE rowid = '.$this->id; @@ -1060,7 +1074,7 @@ class FactureRec extends CommonInvoice return -1; } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; - $sql.= ' SET date_when = "'.$this->db->idate($date).'"'; + $sql.= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); if ($increment_nb_gen_done>0) $sql.= ', nb_gen_done = nb_gen_done + 1'; $sql.= ' WHERE rowid = '.$this->id; @@ -1190,4 +1204,4 @@ class FactureLigneRec extends CommonInvoiceLine } } -} \ No newline at end of file +} diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 3bc60390d61..2e76d9ce4db 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -53,7 +53,8 @@ class Facture extends CommonInvoice 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 $picto='bill'; + /** * {@inheritdoc} */ @@ -218,9 +219,9 @@ class Facture extends CommonInvoice } /** - * Create invoice in database - * Note: this->ref can be set or empty. If empty, we will use "(PROV)" - * Note: this->fac_rec must be set to create from recurring invoice + * Create invoice in database. + * Note: this->ref can be set or empty. If empty, we will use "(PROV999)" + * Note: this->fac_rec must be set to create invoice from a recurring invoice * * @param User $user Object user that create * @param int $notrigger 1=Does not execute triggers, 0 otherwise @@ -241,7 +242,8 @@ class Facture extends CommonInvoice if (! $this->cond_reglement_id) $this->cond_reglement_id = 0; if (! $this->mode_reglement_id) $this->mode_reglement_id = 0; $this->brouillon = 1; - + if (empty($this->entity)) $this->entity = $conf->entity; + // Multicurrency (test on $this->multicurrency_tx because we sould take the default rate only if not using origin rate) if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency,$this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); @@ -280,9 +282,11 @@ class Facture extends CommonInvoice require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; $_facrec = new FactureRec($this->db); $result=$_facrec->fetch($this->fac_rec); + $result=$_facrec->fetchObjectLinked(); // This load $_facrec->linkedObjectsIds - $this->socid = $_facrec->socid; - + $this->socid = $_facrec->socid; // Invoice created on same thirdparty than template + $this->entity = $_facrec->entity; // Invoice created in same entity than template + // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI $this->fk_project = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project; $this->note_public = GETPOST('note_public') ? GETPOST('note_public') : $_facrec->note_public; @@ -309,15 +313,19 @@ class Facture extends CommonInvoice if (! $this->mode_reglement_id) $this->mode_reglement_id = 0; $this->brouillon = 1; + $this->linked_objects = $_facrec->linkedObjectsIds; + $forceduedate = $this->calculate_date_lim_reglement(); - // For recurrn invoices, update date and number of last generation of recurring template invoice, before inserting new invoice + // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice if ($_facrec->frequency > 0) { + dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); + if (empty($_facrec->date_when)) $_facrec->date_when = $now; $next_date = $_facrec->getNextDate(); // Calculate next date - $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date'); + $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. - $_facrec->setNextDate($next_date,1); + $result = $_facrec->setNextDate($next_date,1); } } @@ -352,7 +360,7 @@ class Facture extends CommonInvoice $sql.= ")"; $sql.= " VALUES ("; $sql.= "'(PROV)'"; - $sql.= ", ".$conf->entity; + $sql.= ", ".$this->entity; $sql.= ", ".($this->ref_ext?"'".$this->db->escape($this->ref_ext)."'":"null"); $sql.= ", '".$this->db->escape($this->type)."'"; $sql.= ", '".$socid."'"; @@ -399,15 +407,31 @@ class Facture 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) + foreach($this->linked_objects as $origin => $tmp_origin_id) { - $ret = $this->add_object_linked($origin, $origin_id); - if (! $ret) - { - dol_print_error($this->db); - $error++; - } - + if (is_array($tmp_origin_id)) // New baheviour, 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 (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) { $originforcontact = $origin; @@ -415,7 +439,7 @@ class Facture extends CommonInvoice if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order { require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php'; - $exp = new Expedition($db); + $exp = new Expedition($this->db); $exp->fetch($origin_id); $exp->fetchObjectLinked(); if (count($exp->linkedObjectsIds['commande']) > 0) @@ -974,11 +998,14 @@ class Facture extends CommonInvoice * @param int $max Maxlength of ref * @param int $short 1=Return just URL * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip * @return string String with URL */ - function getNomUrl($withpicto=0,$option='',$max=0,$short=0,$moretitle='') + function getNomUrl($withpicto=0,$option='',$max=0,$short=0,$moretitle='',$notooltip=0) { - global $langs, $conf; + global $langs, $conf, $user; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips $result=''; @@ -991,28 +1018,44 @@ class Facture extends CommonInvoice if ($this->type == self::TYPE_REPLACEMENT) $picto.='r'; // Replacement invoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto.='a'; // Credit note if ($this->type == self::TYPE_DEPOSIT) $picto.='d'; // Deposit invoice + $label=''; + + if ($user->rights->facture->lire) { + $label = '' . $langs->trans("ShowInvoice") . ''; + if (! empty($this->ref)) + $label .= '
    '.$langs->trans('Ref') . ': ' . $this->ref; + if (! empty($this->ref_client)) + $label .= '
    ' . $langs->trans('RefCustomer') . ': ' . $this->ref_client; + if (! empty($this->total_ht)) + $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_ttc)) + $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); + if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref; + if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref; + if ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref; + if ($this->type == self::TYPE_SITUATION) $label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref; + if ($moretitle) $label.=' - '.$moretitle; + } + + $linkclose=''; + if (empty($notooltip) && $user->rights->facture->lire) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowInvoice"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } - $label = '' . $langs->trans("ShowInvoice") . ''; - if (! empty($this->ref)) - $label .= '
    '.$langs->trans('Ref') . ': ' . $this->ref; - if (! empty($this->ref_client)) - $label .= '
    ' . $langs->trans('RefCustomer') . ': ' . $this->ref_client; - if (! empty($this->total_ht)) - $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_tva)) - $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (! empty($this->total_ttc)) - $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($this->type == self::TYPE_REPLACEMENT) $label=$langs->transnoentitiesnoconv("ShowInvoiceReplace").': '.$this->ref; - if ($this->type == self::TYPE_CREDIT_NOTE) $label=$langs->transnoentitiesnoconv("ShowInvoiceAvoir").': '.$this->ref; - if ($this->type == self::TYPE_DEPOSIT) $label=$langs->transnoentitiesnoconv("ShowInvoiceDeposit").': '.$this->ref; - if ($this->type == self::TYPE_SITUATION) $label=$langs->transnoentitiesnoconv("ShowInvoiceSituation").': '.$this->ref; - if ($moretitle) $label.=' - '.$moretitle; - - $linkstart=''; + $linkstart=''; $linkend=''; - if ($withpicto) $result.=($linkstart.img_object(($max?dol_trunc($label,$max):$label), $picto, 'class="classfortooltip"').$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; return $result; @@ -1034,7 +1077,8 @@ class Facture extends CommonInvoice if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1; - $sql = 'SELECT f.rowid,f.facnumber,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc,f.amount,f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp'; + $sql = 'SELECT f.rowid,f.facnumber,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc,f.amount'; + $sql.= ', f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp'; $sql.= ', f.remise_percent, f.remise_absolue, f.remise'; $sql.= ', f.datef as df, f.date_pointoftax'; $sql.= ', f.date_lim_reglement as dlr'; @@ -1180,7 +1224,7 @@ class Facture extends CommonInvoice { $this->lines=array(); - $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.tva_tx, '; + $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; $sql.= ' l.situation_percent, l.fk_prev_id,'; $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,'; $sql.= ' l.rang, l.special_code,'; @@ -1219,6 +1263,8 @@ class Facture extends CommonInvoice $line->fk_product_type = $objp->fk_product_type; // Type of product $line->qty = $objp->qty; $line->subprice = $objp->subprice; + + $line->vat_src_code = $objp->vat_src_code; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; $line->localtax2_tx = $objp->localtax2_tx; @@ -1506,11 +1552,13 @@ class Facture extends CommonInvoice * Set customer ref * * @param string $ref_client Customer ref - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_ref_client($ref_client, $notrigger=0) { + global $user; + $error=0; $this->db->begin(); @@ -1903,7 +1951,7 @@ class Facture extends CommonInvoice * @param User $user Object user that validate * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease) - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function validate($user, $force_number='', $idwarehouse=0, $notrigger=0) @@ -2120,7 +2168,8 @@ class Facture extends CommonInvoice if (!empty($conf->global->INVOICE_USE_SITUATION)) { $final = True; - while ($i < count($this->lines) && $final == True) { + $nboflines = count($this->lines); + while (($i < $nboflines) && $final) { $final = ($this->lines[$i]->situation_percent == 100); $i++; } @@ -2284,7 +2333,7 @@ class Facture extends CommonInvoice * @param string $desc Description of line * @param double $pu_ht Unit price without tax (> 0 even for credit note) * @param double $qty Quantity - * @param double $txtva Force vat rate, -1 for auto + * @param double $txtva Force Vat rate, -1 for auto * @param double $txlocaltax1 Local tax 1 rate (deprecated) * @param double $txlocaltax2 Local tax 2 rate (deprecated) * @param int $fk_product Id of predefined product/service @@ -2336,6 +2385,16 @@ class Facture extends CommonInvoice if (empty($fk_prev_id)) $fk_prev_id = 'null'; if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; + $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); + + // 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. + } + $remise_percent=price2num($remise_percent); $qty=price2num($qty); $pu_ht=price2num($pu_ht); @@ -2381,9 +2440,6 @@ class Facture extends CommonInvoice // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc); - $txtva = preg_replace('/\s*\(.*\)/','',$txtva); // Remove code into vatrate. - $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx); $total_ht = $tabprice[0]; @@ -2418,6 +2474,7 @@ class Facture extends CommonInvoice $this->line->qty= ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty); // For credit note, quantity is always positive and unit price negative $this->line->subprice= ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise + $this->line->vat_src_code=$vat_src_code; $this->line->tva_tx=$txtva; $this->line->localtax1_tx=$txlocaltax1; $this->line->localtax2_tx=$txlocaltax2; @@ -2569,7 +2626,14 @@ class Facture extends CommonInvoice // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc); - $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. + } $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx); @@ -2632,11 +2696,14 @@ class Facture extends CommonInvoice $this->line->label = $label; $this->line->desc = $desc; $this->line->qty = ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty); // For credit note, quantity is always positive and unit price negative + + $this->line->vat_src_code = $vat_src_code; $this->line->tva_tx = $txtva; $this->line->localtax1_tx = $txlocaltax1; $this->line->localtax2_tx = $txlocaltax2; $this->line->localtax1_type = $localtaxes_type[0]; $this->line->localtax2_type = $localtaxes_type[2]; + $this->line->remise_percent = $remise_percent; $this->line->subprice = ($this->type==2?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise $this->line->date_start = $date_start; @@ -2815,7 +2882,7 @@ class Facture extends CommonInvoice * * @param User $user User that set discount * @param double $remise Discount - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ function set_remise($user, $remise, $notrigger=0) @@ -2879,7 +2946,7 @@ class Facture extends CommonInvoice * * @param User $user User that set discount * @param double $remise Discount - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function set_remise_absolue($user, $remise, $notrigger=0) @@ -3934,7 +4001,7 @@ class Facture extends CommonInvoice * Sets the invoice as a final situation * * @param User $user Object user - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function setFinal(User $user, $notrigger=0) @@ -4288,7 +4355,7 @@ class FactureLigne extends CommonInvoiceLine // Insertion dans base de la ligne $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet'; $sql.= ' (fk_facture, fk_parent_line, label, description, qty,'; - $sql.= ' tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; + $sql.= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,'; $sql.= ' fk_product, product_type, remise_percent, subprice, fk_remise_except,'; $sql.= ' date_start, date_end, fk_code_ventilation, '; $sql.= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,'; @@ -4302,6 +4369,7 @@ class FactureLigne extends CommonInvoiceLine $sql.= " ".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null").","; $sql.= " '".$this->db->escape($this->desc)."',"; $sql.= " ".price2num($this->qty).","; + $sql.= " ".(empty($this->vat_src_code)?"''":"'".$this->vat_src_code."'").","; $sql.= " ".price2num($this->tva_tx).","; $sql.= " ".price2num($this->localtax1_tx).","; $sql.= " ".price2num($this->localtax2_tx).","; @@ -4482,42 +4550,43 @@ class FactureLigne extends CommonInvoiceLine // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; $sql.= " description='".$this->db->escape($this->desc)."'"; - $sql.= ",label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); - $sql.= ",subprice=".price2num($this->subprice).""; - $sql.= ",remise_percent=".price2num($this->remise_percent).""; - if ($this->fk_remise_except) $sql.= ",fk_remise_except=".$this->fk_remise_except; - else $sql.= ",fk_remise_except=null"; - $sql.= ",tva_tx=".price2num($this->tva_tx).""; - $sql.= ",localtax1_tx=".price2num($this->localtax1_tx).""; - $sql.= ",localtax2_tx=".price2num($this->localtax2_tx).""; - $sql.= ",localtax1_type='".$this->localtax1_type."'"; - $sql.= ",localtax2_type='".$this->localtax2_type."'"; - $sql.= ",qty=".price2num($this->qty).""; - $sql.= ",date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); - $sql.= ",date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); - $sql.= ",product_type=".$this->product_type; - $sql.= ",info_bits='".$this->info_bits."'"; - $sql.= ",special_code='".$this->special_code."'"; + $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); + $sql.= ", subprice=".price2num($this->subprice).""; + $sql.= ", remise_percent=".price2num($this->remise_percent).""; + if ($this->fk_remise_except) $sql.= ", fk_remise_except=".$this->fk_remise_except; + else $sql.= ", fk_remise_except=null"; + $sql.= ", vat_src_code = '".(empty($this->vat_src_code)?'':$this->vat_src_code)."'"; + $sql.= ", tva_tx=".price2num($this->tva_tx).""; + $sql.= ", localtax1_tx=".price2num($this->localtax1_tx).""; + $sql.= ", localtax2_tx=".price2num($this->localtax2_tx).""; + $sql.= ", localtax1_type='".$this->localtax1_type."'"; + $sql.= ", localtax2_type='".$this->localtax2_type."'"; + $sql.= ", qty=".price2num($this->qty).""; + $sql.= ", date_start=".(! empty($this->date_start)?"'".$this->db->idate($this->date_start)."'":"null"); + $sql.= ", date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); + $sql.= ", product_type=".$this->product_type; + $sql.= ", info_bits='".$this->info_bits."'"; + $sql.= ", special_code='".$this->special_code."'"; if (empty($this->skip_update_total)) { - $sql.= ",total_ht=".price2num($this->total_ht).""; - $sql.= ",total_tva=".price2num($this->total_tva).""; - $sql.= ",total_ttc=".price2num($this->total_ttc).""; - $sql.= ",total_localtax1=".price2num($this->total_localtax1).""; - $sql.= ",total_localtax2=".price2num($this->total_localtax2).""; + $sql.= ", total_ht=".price2num($this->total_ht).""; + $sql.= ", total_tva=".price2num($this->total_tva).""; + $sql.= ", total_ttc=".price2num($this->total_ttc).""; + $sql.= ", total_localtax1=".price2num($this->total_localtax1).""; + $sql.= ", total_localtax2=".price2num($this->total_localtax2).""; } - $sql.= " , fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null"); - $sql.= " , buy_price_ht='".price2num($this->pa_ht)."'"; - $sql.= ",fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); + $sql.= ", fk_product_fournisseur_price=".(! empty($this->fk_fournprice)?"'".$this->db->escape($this->fk_fournprice)."'":"null"); + $sql.= ", buy_price_ht='".price2num($this->pa_ht)."'"; + $sql.= ", fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null"); if (! empty($this->rang)) $sql.= ", rang=".$this->rang; - $sql .= ", situation_percent=" . $this->situation_percent; - $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); + $sql.= ", situation_percent=" . $this->situation_percent; + $sql.= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); // Multicurrency - $sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice).""; - $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; - $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; - $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; + $sql.= ", multicurrency_subprice=".price2num($this->multicurrency_subprice).""; + $sql.= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht).""; + $sql.= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva).""; + $sql.= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc).""; $sql.= " WHERE rowid = ".$this->rowid; diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index d524c501698..2899e3fae56 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -42,7 +42,7 @@ class PaymentTerm // extends CommonObject var $active; var $libelle; var $libelle_facture; - var $fdm; + var $type_cdr; var $nbjour; var $decalage; @@ -80,7 +80,7 @@ class PaymentTerm // extends CommonObject if (isset($this->active)) $this->active=trim($this->active); if (isset($this->libelle)) $this->libelle=trim($this->libelle); if (isset($this->libelle_facture)) $this->libelle_facture=trim($this->libelle_facture); - if (isset($this->fdm)) $this->fdm=trim($this->fdm); + if (isset($this->type_cdr)) $this->type_cdr=trim($this->type_cdr); if (isset($this->nbjour)) $this->nbjour=trim($this->nbjour); if (isset($this->decalage)) $this->decalage=trim($this->decalage); @@ -98,7 +98,7 @@ class PaymentTerm // extends CommonObject $sql.= "active,"; $sql.= "libelle,"; $sql.= "libelle_facture,"; - $sql.= "fdm,"; + $sql.= "type_cdr,"; $sql.= "nbjour,"; $sql.= "decalage"; @@ -111,7 +111,7 @@ class PaymentTerm // extends CommonObject $sql.= " ".(! isset($this->active)?'NULL':"'".$this->active."'").","; $sql.= " ".(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").","; $sql.= " ".(! isset($this->libelle_facture)?'NULL':"'".$this->db->escape($this->libelle_facture)."'").","; - $sql.= " ".(! isset($this->fdm)?'NULL':"'".$this->fdm."'").","; + $sql.= " ".(! isset($this->type_cdr)?'NULL':"'".$this->type_cdr."'").","; $sql.= " ".(! isset($this->nbjour)?'NULL':"'".$this->nbjour."'").","; $sql.= " ".(! isset($this->decalage)?'NULL':"'".$this->decalage."'").""; @@ -178,7 +178,7 @@ class PaymentTerm // extends CommonObject $sql.= " t.active,"; $sql.= " t.libelle,"; $sql.= " t.libelle_facture,"; - $sql.= " t.fdm,"; + $sql.= " t.type_cdr,"; $sql.= " t.nbjour,"; $sql.= " t.decalage"; @@ -201,7 +201,7 @@ class PaymentTerm // extends CommonObject $this->active = $obj->active; $this->libelle = $obj->libelle; $this->libelle_facture = $obj->libelle_facture; - $this->fdm = $obj->fdm; + $this->type_cdr = $obj->type_cdr; $this->nbjour = $obj->nbjour; $this->decalage = $obj->decalage; @@ -274,7 +274,7 @@ class PaymentTerm // extends CommonObject if (isset($this->active)) $this->active=trim($this->active); if (isset($this->libelle)) $this->libelle=trim($this->libelle); if (isset($this->libelle_facture)) $this->libelle_facture=trim($this->libelle_facture); - if (isset($this->fdm)) $this->fdm=trim($this->fdm); + if (isset($this->type_cdr)) $this->type_cdr=trim($this->type_cdr); if (isset($this->nbjour)) $this->nbjour=trim($this->nbjour); if (isset($this->decalage)) $this->decalage=trim($this->decalage); @@ -291,7 +291,7 @@ class PaymentTerm // extends CommonObject $sql.= " active=".(isset($this->active)?$this->active:"null").","; $sql.= " libelle=".(isset($this->libelle)?"'".$this->db->escape($this->libelle)."'":"null").","; $sql.= " libelle_facture=".(isset($this->libelle_facture)?"'".$this->db->escape($this->libelle_facture)."'":"null").","; - $sql.= " fdm=".(isset($this->fdm)?$this->fdm:"null").","; + $sql.= " type_cdr=".(isset($this->type_cdr)?$this->type_cdr:"null").","; $sql.= " nbjour=".(isset($this->nbjour)?$this->nbjour:"null").","; $sql.= " decalage=".(isset($this->decalage)?$this->decalage:"null").""; @@ -471,7 +471,7 @@ class PaymentTerm // extends CommonObject $this->active=''; $this->libelle=''; $this->libelle_facture=''; - $this->fdm=''; + $this->type_cdr=''; $this->nbjour=''; $this->decalage=''; } diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index 9a15b7875d8..246e5595779 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -149,6 +149,7 @@ if ($id > 0 || ! empty($ref)) $modulepart = 'facture'; $permission = $user->rights->facture->creer; + $permtoedit = $user->rights->facture->creer; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index b6b9ca87ac5..33da64e3221 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -7,6 +7,7 @@ * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2012 Cedric Salvador * Copyright (C) 2015 Alexandre Spangaro + * Copyright (C) 2016 Meziane Sof * * 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 @@ -30,10 +31,12 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; -require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.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'; +} $langs->load('bills'); $langs->load('compta'); @@ -86,11 +89,11 @@ if (($id > 0 || $ref) && $action != 'create' && $action != 'add') } // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('invoicecard','globalcard')); +$hookmanager->initHooks(array('invoicereccard','globalcard')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels -$extralabels = $extrafields->fetch_name_optionals_label('facturerec'); +$extralabels = $extrafields->fetch_name_optionals_label('facture'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); $permissionnote = $user->rights->facture->creer; // Used by the include of actions_setnotes.inc.php @@ -123,689 +126,738 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -// Set note -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once +$parameters = array('socid' => $socid); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - -if (GETPOST('cancel')) $action=''; - -// Create predefined invoice -if ($action == 'add') +if (empty($reshook)) { - 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; - - 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'); - $object->note_public = GETPOST('note_public'); - $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->fk_project = $projectid; - - $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')); - - $srcObject->fetchObjectLinked(); - - 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; - } - } - - $db->begin(); - - $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"; - } - - if (! $error) - { - $db->commit(); - - header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); - exit; - } - else - { - $db->rollback(); - - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } - } -} - -// Delete -if ($action == 'delete' && $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')); - -} -// 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) -{ - $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha')); - if ($result > 0) + if (GETPOST('cancel')) $action=''; + + // 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_lineupdown.inc.php'; // Must be include, not include_once + + // Do we click on purge search criteria ? + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers { - $object->titre = GETPOST('ref', 'alpha'); - $object->ref = $object->titre; + $search_ref=''; + $search_societe=''; + $search_montant_ht=''; + $search_montant_vat=''; + $search_montant_ttc=''; + $day=''; + $year=''; + $month=''; + $day_date_when=''; + $year_date_when=''; + $month_date_when=''; + $search_frequency=''; + $search_array_options=array(); } -} -// 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(); - - $db->begin(); - $line=new FactureLigneRec($db); - - // For triggers - $line->id = $lineid; - - if ($line->delete() > 0) + // Create predefined invoice + if ($action == 'add') { - $result=$object->update_price(1); + 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; + + 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'); + $object->note_public = GETPOST('note_public'); + $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->fk_project = $projectid; + + $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')); + + $srcObject->fetchObjectLinked(); + + 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; + } + } + + $db->begin(); + + $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"; + } + + if (! $error) + { + $db->commit(); + + header("Location: " . $_SERVER['PHP_SELF'] . '?facid=' . $object->id); + exit; + } + else + { + $db->rollback(); + + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } + } + } + + // Delete + if ($action == 'confirm_deleteinvoice' && $confirm == 'yes' && $user->rights->facture->supprimer) + { + $object->delete(); + 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')); + + } + // 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) { - $db->commit(); - $object->fetch($object->id); // Reload lines - } - else - { - $db->rollback(); - setEventMessages($db->lasterror(), null, 'errors'); + $object->titre = GETPOST('ref', 'alpha'); + $object->ref = $object->titre; } + else dol_print_error($db, $object->error, $object->errors); } - else + // Set bank account + elseif ($action == 'setbankaccount' && $user->rights->facture->creer) { - $db->rollback(); - setEventMessages($line->error, $line->errors, 'errors'); + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } -} - -// Add a new line -if ($action == 'addline' && $user->rights->facture->creer) -{ - $langs->load('errors'); - $error = 0; - - // 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') + // Set frequency and unit frequency + elseif ($action == 'setfrequency' && $user->rights->facture->creer) { - $idprod=0; - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); } - else + // Set next date of execution + elseif ($action == 'setdate_when' && $user->rights->facture->creer) { - $idprod=GETPOST('idprod', 'int'); - $tva_tx = ''; + $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); } - - $qty = GETPOST('qty' . $predef); - $remise_percent = GETPOST('remise_percent' . $predef); - - // 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 (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 '' + // Set max period + elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); - $error ++; + $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); } - 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 ++; + // Set auto validate + elseif ($action == 'setauto_validate' && $user->rights->facture->creer) + { + $object->setAutoValidate(GETPOST('auto_validate', 'int')); } - 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(); - - // 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'); - - // Define special_code for special lines - $special_code = 0; - // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices - - // Ecrase $pu par celui du produit - // Ecrase $desc par celui du produit - // Ecrase $txtva 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); - - $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); - - // 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; - - // 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'; - - $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; - $prod->tva_tx = $prodcustprice->lines[0]->tva_tx; - } - } - } - - // if price ht was forced (ie: from gui when calculated by margin rate and cost price) - if (! empty($price_ht)) - { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 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 ($tva_tx != $prod->tva_tx) - { - if ($price_base_type != 'HT') - { - $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); - } - else - { - $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU'); - } - } - - $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')) - $newlang = GETPOST('lang_id'); - 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 = 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); - } - - $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'); - } + // Delete line + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id); + $object->fetch_thirdparty(); + + $db->begin(); + + $line=new FactureLigneRec($db); + + // For triggers + $line->id = $lineid; + + if ($line->delete() > 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'); + } + } + + // Add a new line + if ($action == 'addline' && $user->rights->facture->creer) + { + $langs->load('errors'); + $error = 0; + + // 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 = ''; + } + + $qty = GETPOST('qty' . $predef); + $remise_percent = GETPOST('remise_percent' . $predef); + + // 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 (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 ++; + } - // 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); - - $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, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); - - if ($result > 0) + 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(); + + // 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'); + + // Define special_code for special lines + $special_code = 0; + // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices + + // Ecrase $pu par celui du produit + // Ecrase $desc par celui du produit + // Ecrase $txtva par celui du produit + // Ecrase $base_price_type par celui du produit + // Replaces $fk_unit with the product's + if (! empty($idprod)) { - /*if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); - 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) setEventMessages($object->error, $object->errors, 'errors'); - }*/ - $object->fetch($object->id); // Reload lines - - 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['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'); - } - - $action = ''; + $prod = new Product($db); + $prod->fetch($idprod); + + $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); + + // 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; + + // 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'; + + $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; + $prod->tva_tx = $prodcustprice->lines[0]->tva_tx; + } + } + } + + // if price ht was forced (ie: from gui when calculated by margin rate and cost price) + if (! empty($price_ht)) + { + $pu_ht = price2num($price_ht, 'MU'); + $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 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 ($tva_tx != $prod->tva_tx) + { + if ($price_base_type != 'HT') + { + $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); + } + else + { + $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU'); + } + } + + $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')) + $newlang = GETPOST('lang_id'); + 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 = 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); + + } + + $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'); + } + + // 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); + + $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, $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)) + { + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + 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) setEventMessages($object->error, $object->errors, 'errors'); + }*/ + $object->fetch($object->id); // Reload lines + + 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['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'); + } + + $action = ''; + } } } -} - -elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel')) -{ - 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') ? GETPOST('product_desc') : GETPOST('desc')); - $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 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 - - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); - // Unset extrafield - if (is_array($extralabelsline)) { - // Get extra fields - foreach ($extralabelsline as $key => $value) { - unset($_POST["options_" . $key]); + + elseif ($action == 'updateligne' && $user->rights->facture->creer && ! GETPOST('cancel')) + { + 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') ? GETPOST('product_desc') : GETPOST('desc')); + $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 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 + + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); + // 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; - - /*$line = new FactureLigne($db); - $line->fetch(GETPOST('lineid')); - $percent = $line->get_prev_progress($object->id); - - if (GETPOST('progress') < $percent) - { - $mesg = '
    ' . $langs->trans("CantBeLessThanMinPercent") . '
    '; - setEventMessages($mesg, null, 'warnings'); - $error++; - $result = -1; - }*/ - - // Check minimum price - $productid = GETPOST('productid', 'int'); - if (! empty($productid)) - { - $product = new Product($db); - $product->fetch($productid); - - $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]; - - $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'); + + // Define special_code for special lines + $special_code=GETPOST('special_code'); + if (! GETPOST('qty')) $special_code=3; + + /*$line = new FactureLigne($db); + $line->fetch(GETPOST('lineid')); + $percent = $line->get_prev_progress($object->id); + + if (GETPOST('progress') < $percent) + { + $mesg = '
    ' . $langs->trans("CantBeLessThanMinPercent") . '
    '; + setEventMessages($mesg, null, 'warnings'); + $error++; + $result = -1; + }*/ + + // Check minimum price + $productid = GETPOST('productid', 'int'); + if (! empty($productid)) + { + $product = new Product($db); + $product->fetch($productid); + + $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]; + + $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 parameters + if (GETPOST('type') < 0) { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), 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'); + } + if ($qty < 0) { + $langs->load("errors"); + setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), 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, 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)) { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) - $newlang = GETPOST('lang_id'); - 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($id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - }*/ - - $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['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['situations']); - unset($_POST['progress']); - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + + // Update line + if (! $error) + { + $result = $object->updateline( + GETPOST('lineid'), + $description, + $pu_ht, + $qty, + $vat_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)) { + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) + $newlang = GETPOST('lang_id'); + 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($id); // Reload to get new records + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + }*/ + + $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['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['situations']); + unset($_POST['progress']); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } } -// Do we click on purge search criteria ? -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers -{ - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $day=''; - $year=''; - $month=''; - $day_date_when=''; - $year_date_when=''; - $month_date_when=''; - $search_frequency=''; - $search_array_options=array(); -} - - /* * View @@ -815,6 +867,7 @@ llxHeader('',$langs->trans("RepeatableInvoices"),'ch-facture.html#s-fac-facture- $form = new Form($db); $formother = new FormOther($db); +if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $companystatic = new Societe($db); $now = dol_now(); @@ -837,7 +890,7 @@ if ($action == 'create') { $result = $object->getLinesArray(); - print '
    '; + print ''; print ''; print ''; print ''; @@ -885,15 +938,15 @@ if ($action == 'create') print "
    "; // Project - if (! empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0) - { - $projectid = $object->fk_project; - $langs->load('projects'); - print ''; - } + if (! empty($conf->projet->enabled) && is_object($object->thirdparty) && $object->thirdparty->id > 0) + { + $projectid = $object->fk_project; + $langs->load('projects'); + print ''; + } // Bank account if ($object->fk_account > 0) @@ -932,8 +985,8 @@ if ($action == 'create') // Auto validate the invoice print ""; print "
    ' . $langs->trans('Project') . ''; - $numprojet = $formproject->select_projects($socid, $projectid, 'projectid', 0); - print '   id).'">' . $langs->trans("AddProject") . ''; - print '
    ' . $langs->trans('Project') . ''; + $numprojet = $formproject->select_projects($socid, $projectid, 'projectid', 0); + print '   id).'">' . $langs->trans("AddProject") . ''; + print '
    ".$langs->trans("StatusOfGeneratedInvoices").""; - $select = array('0'=>$langs->trans('BillStatusDraft'),'1'=>$langs->trans('BillStatusValidated')); - print $form->selectarray('auto_validate', $select, GETPOST('auto_validate')); + $select = array('0'=>$langs->trans('BillStatusDraft'),'1'=>$langs->trans('BillStatusValidated')); + print $form->selectarray('auto_validate', $select, GETPOST('auto_validate')); print "
    "; @@ -999,11 +1052,16 @@ else $object->fetch_thirdparty(); // Confirmation de la suppression d'une ligne produit - if ($action == 'ask_deleteline') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1); - } + if ($action == 'ask_deleteline') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1); + } - print $formconfirm; + // Confirm delete of repeatable invoice + if ($action == 'ask_deleteinvoice') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteRepeatableInvoice'), $langs->trans('ConfirmDeleteRepeatableInvoice'), 'confirm_deleteinvoice', '', 'no', 1); + } + + print $formconfirm; $author = new User($db); $author->fetch($object->user_author); @@ -1016,11 +1074,64 @@ else dol_fiche_head($head, 'card', $langs->trans("RepeatableInvoice"),0,'bill'); // Add a div - print ''; - + // Recurring invoice content + $linkback = '' . $langs->trans("BackToList") . ''; + + $morehtmlref=''; + 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.='
    '; + + dol_banner_tab($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref, '', 0, '', $morehtmlright); + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; // Ref + /* print ''; - print ''; print ''; - - print ""; + */ + + print '"; print ''; print ''; @@ -1056,9 +1167,12 @@ else print ''; // Project - if (! empty($conf->projet->enabled)) { + /* + if (! empty($conf->projet->enabled)) + { $langs->load('projects'); print ''; print ''; print ''; - } + }*/ // Bank Account print '"; print ''; - print "
    '; //print $langs->trans('Ref'); print $form->editfieldkey($langs->trans("Ref"), 'ref', $object->ref, $object, $user->rights->facture->creer); @@ -1030,11 +1141,11 @@ else print $form->showrefnav($object, 'ref', $linkback, 1, 'titre', 'none', $morehtmlref); print '
    '.$langs->trans("Customer").''.$object->thirdparty->getNomUrl(1,'customer').'
    ".$langs->trans("Author").''.$author->getFullName($langs)."
    '.$langs->trans("Author").''.$author->getFullName($langs)."
    '.$langs->trans("AmountHT").''.price($object->total_ht,'',$langs,1,-1,-1,$conf->currency).''; if ($object->type != Facture::TYPE_CREDIT_NOTE) { - if ($action == 'editconditions') { + if ($action == 'editconditions') + { $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id'); - } else { + } + else + { $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none'); } } else { @@ -1102,7 +1216,9 @@ else print '
    '; @@ -1125,7 +1241,7 @@ else } print '
    '; @@ -1147,10 +1263,15 @@ else print "
    "; - - print '
    '; - + print ''; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + /* * Recurrence */ @@ -1160,36 +1281,36 @@ else print '
    '; // if "frequency" is empty or = 0, the reccurence is disabled - print ''; @@ -1203,7 +1324,7 @@ else { print $langs->trans("NextDateToExecution"); } - print '
    '; + print '
    '; print ''; if ($action != 'editfrequency' && ! empty($object->brouillon) && $user->rights->facture->creer) print ''; print '
    '; print $langs->trans('Frequency'); print 'id . '">' . img_edit($langs->trans('Edit'), 1) . '
    '; - print '
    '; + print ''; if ($action == 'editfrequency') { print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
    '; - print " ".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency?$object->unit_frequency:'m')); - print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + print " ".$form->selectarray('unit_frequency', array('d'=>$langs->trans('Day'), 'm'=>$langs->trans('Month'), 'y'=>$langs->trans('Year')), ($object->unit_frequency?$object->unit_frequency:'m')); + print '
    '; } else { - if ($object->frequency > 0) - { - print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); - } - else - { - print $langs->trans("NotARecurringInvoiceTemplate"); - } + if ($object->frequency > 0) + { + print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); + } + else + { + print $langs->trans("NotARecurringInvoiceTemplate"); + } } print '
    '; + 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'); @@ -1221,7 +1342,7 @@ else { print $langs->trans("MaxPeriodNumber"); } - print ''; + 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); @@ -1239,8 +1360,8 @@ else print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); else print $langs->trans("StatusOfGeneratedInvoices"); - print ''; - $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); + print ''; + $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); @@ -1250,20 +1371,21 @@ else print '
    '; - print '
    '; - // Frequencry/Recurring section - if ($object->frequency > 0) - { - if (empty($conf->cron->enabled)) + if ($object->frequency > 0) + { + print '
    '; + + if (empty($conf->cron->enabled)) { print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); } - print ''; + print '
    '; + print '
    '; // Nb of generation already done - print ''; + print ''; print ''; @@ -1272,7 +1394,7 @@ else // Date last print ''; print ''; @@ -1282,6 +1404,13 @@ else print '
    '; } + print ''; + print ''; + print ''; + + print '

    '; + + // Lines print ' @@ -1332,34 +1461,34 @@ else //if ($object->statut == Facture::STATUS_DRAFT) // there is no draft status on templates. //{ - if ($user->rights->facture->creer) - { - if (! empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) - { - print ''; - } - else - { - if (empty($object->frequency) || $object->date_when <= $today) - { - print ''; - } - else - { - print ''; - } - } - } - else - { - print ''; - } + if ($user->rights->facture->creer) + { + if (! empty($object->frequency) && $object->nb_gen_max > 0 && ($object->nb_gen_done >= $object->nb_gen_max)) + { + print ''; + } + else + { + if (empty($object->frequency) || $object->date_when <= $today) + { + print ''; + } + else + { + print ''; + } + } + } + else + { + print ''; + } //} //if ($object->statut == Facture::STATUS_DRAFT && $user->rights->facture->supprimer) if ($user->rights->facture->supprimer) { - print ''; + print ''; } print ''; @@ -1371,8 +1500,9 @@ else // Show links to link elements - //$linktoelem = $form->showLinkToObjectBlock($object, null, array('order')); - $somethingshown = $form->showLinkedObjectBlock($object, ''); + $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); + + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); print ''; @@ -1394,6 +1524,9 @@ else if ($search_montant_ht != '') $sql.= natural_search('f.total', $search_montant_ht, 1); if ($search_montant_vat != '') $sql.= natural_search('f.tva', $search_montant_vat, 1); if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); + if ($search_frequency == '1') $sql.= ' AND f.frequency > 0'; + if ($search_frequency == '0') $sql.= ' AND (f.frequency IS NULL or f.frequency = 0)'; + if ($month > 0) { if ($year > 0 && empty($day)) @@ -1413,8 +1546,8 @@ else $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($year_date_when,$month_date_when,false))."' AND '".$db->idate(dol_get_last_day($year_date_when,$month_date_when,false))."'"; else if ($year_date_when > 0 && ! empty($day_date_when)) $sql.= " AND f.date_date_when_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date_when, $day_date_when, $year_date_when))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date_when, $day_date_when, $year_date_when))."'"; - else - $sql.= " AND date_format(f.date_when, '%m') = '".$month_date_when."'"; + else + $sql.= " AND date_format(f.date_when, '%m') = '".$month_date_when."'"; } else if ($year_date_when > 0) { @@ -1422,14 +1555,14 @@ else } $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - } + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + { + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + } - $sql.= $db->order($sortfield, $sortorder); - $sql.= $db->plimit($limit+1,$offset); + $sql.= $db->order($sortfield, $sortorder); + $sql.= $db->plimit($limit+1,$offset); $resql = $db->query($sql); if ($resql) @@ -1437,7 +1570,7 @@ else $num = $db->num_rows($resql); $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($day) $param.='&day='.$day; if ($month) $param.='&month='.$month; @@ -1528,8 +1661,8 @@ else if (! empty($arrayfields['f.frequency']['checked'])) { // Amount - print ''; } // Date invoice diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index bab9ab00769..48ed568e3f9 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -70,6 +70,7 @@ $userid=GETPOST('userid','int'); $search_product_category=GETPOST('search_product_category','int'); $search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha'); $search_refcustomer=GETPOST('search_refcustomer','alpha'); +$search_type=GETPOST('search_type','int'); $search_societe=GETPOST('search_societe','alpha'); $search_montant_ht=GETPOST('search_montant_ht','alpha'); $search_montant_vat=GETPOST('search_montant_vat','alpha'); @@ -142,6 +143,7 @@ $checkedtypetiers=0; $arrayfields=array( 'f.facnumber'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'f.ref_client'=>array('label'=>$langs->trans("RefCustomer"), 'checked'=>1), + 'f.type'=>array('label'=>$langs->trans("Type"), 'checked'=>0), 'f.date'=>array('label'=>$langs->trans("DateInvoice"), 'checked'=>1), 'f.date_lim_reglement'=>array('label'=>$langs->trans("DateDue"), 'checked'=>1), 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1), @@ -191,6 +193,7 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter") || GETPOS $search_product_category=''; $search_ref=''; $search_refcustomer=''; + $search_type=''; $search_project=''; $search_societe=''; $search_montant_ht=''; @@ -275,7 +278,7 @@ if ($search_user > 0) $sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql.= ' WHERE f.fk_soc = s.rowid'; -$sql.= " AND f.entity = ".$conf->entity; +$sql.= ' AND f.entity IN ('.getEntity('facture', 1).')'; if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$search_product_category; if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; @@ -295,6 +298,15 @@ if ($filtre) } if ($search_ref) $sql .= natural_search('f.facnumber', $search_ref); if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer); +if ($search_type != '' && $search_type >= 0) +{ + if ($search_type == '0') $sql.=" AND f.type = 0"; // standard + if ($search_type == '1') $sql.=" AND f.type = 1"; // replacement + if ($search_type == '2') $sql.=" AND f.type = 2"; // credit note + if ($search_type == '3') $sql.=" AND f.type = 3"; // deposit + if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma + if ($search_type == '5') $sql.=" AND f.type = 5"; // situation +} if ($search_project) $sql .= natural_search('p.ref', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_town) $sql.= natural_search('s.town', $search_town); @@ -310,7 +322,7 @@ if ($search_status != '' && $search_status >= 0) { if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed - if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some correupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) + if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned } if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$search_paymentmode.""; @@ -367,12 +379,17 @@ $sql.=$hookmanager->resPrint; if (! $sall) { - $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, fk_mode_reglement, f.total, f.tva, f.total_ttc,'; + $sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total, f.tva, f.total_ttc,'; $sql.= ' f.datef, f.date_lim_reglement,'; $sql.= ' f.paye, f.fk_statut,'; $sql.= ' f.datec, f.tms,'; - $sql.= ' s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code'; - $sql.= ' ,state.code_departement, state.nom'; + $sql.= ' s.rowid, s.nom, s.town, s.zip, s.fk_pays, s.code_client, s.client, typent.code,'; + $sql.= ' state.code_departement, state.nom'; + + foreach ($extrafields->attribute_label as $key => $val) //prevent error with sql_mode=only_full_group_by + { + $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); + } } else { @@ -400,7 +417,7 @@ if ($resql) $num = $db->num_rows($resql); $arrayofselected=is_array($toselect)?$toselect:array(); - + if ($socid) { $soc = new Societe($db); @@ -410,6 +427,7 @@ if ($resql) $param='&socid='.$socid; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($sall) $param.='&sall='.$sall; if ($day) $param.='&day='.urlencode($day); if ($month) $param.='&month='.urlencode($month); if ($year) $param.='&year=' .urlencode($year); @@ -418,6 +436,7 @@ if ($resql) if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); if ($search_ref) $param.='&search_ref=' .urlencode($search_ref); if ($search_refcustomer) $param.='&search_refcustomer=' .urlencode($search_refcustomer); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); if ($search_societe) $param.='&search_societe=' .urlencode($search_societe); if ($search_sale > 0) $param.='&search_sale=' .urlencode($search_sale); if ($search_user > 0) $param.='&search_user=' .urlencode($search_user); @@ -437,7 +456,7 @@ if ($resql) $tmpkey=preg_replace('/search_options_/','',$key); if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } - + $arrayofmassactions=array( 'presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge") @@ -456,7 +475,7 @@ if ($resql) } if ($massaction == 'presend') $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - + $i = 0; print ''."\n"; if ($optioncss != '') print ''; @@ -466,7 +485,7 @@ if ($resql) print ''; print ''; print ''; - + print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit); if ($massaction == 'presend') @@ -495,7 +514,7 @@ if ($resql) print ''; include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); + $formmail = new FormMail($db); dol_fiche_head(null, '', ''); @@ -506,10 +525,12 @@ if ($resql) include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); $formmail->withform=-1; - $formmail->fromtype = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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; + + } if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set { $formmail->trackid='inv'.$object->id; @@ -614,12 +635,13 @@ if ($resql) $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - + print '
    '.$langs->trans("NbOfGenerationDone").'
    '.$langs->trans("NbOfGenerationDone").''; print $object->nb_gen_done?$object->nb_gen_done:'0'; print '
    '; print $langs->trans("DateLastGeneration"); - print ''; + print ''; print dol_print_date($object->date_last_gen, 'dayhour'); print '
    '; - //print ''; + print ''; + print $form->selectyesno('search_frequency', $search_frequency, 1, false, 1); print '
    '."\n"; - + print ''; if (! empty($arrayfields['f.facnumber']['checked'])) print_liste_field_titre($arrayfields['f.facnumber']['label'],$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'],$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'],$_SERVER["PHP_SELF"],'f.type','',$param,'',$sortfield,$sortorder); if (! empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'],$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'],$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder); @@ -672,6 +694,20 @@ if ($resql) print ''; print ''; } + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print ''; + } // Date invoice if (! empty($arrayfields['f.date']['checked'])) { @@ -718,7 +754,7 @@ if ($resql) if (! empty($arrayfields['typent.code']['checked'])) { print ''; } // Payment mode @@ -829,6 +865,7 @@ if ($resql) $facturestatic->type=$obj->type; $facturestatic->statut=$obj->fk_statut; $facturestatic->date_lim_reglement=$db->jdate($obj->datelimite); + $facturestatic->type=$obj->type; print ''; if (! empty($arrayfields['f.facnumber']['checked'])) @@ -864,7 +901,7 @@ if ($resql) print "\n"; if (! $i) $totalarray['nbfield']++; } - + // Customer ref if (! empty($arrayfields['f.ref_client']['checked'])) { @@ -873,7 +910,16 @@ if ($resql) print ''; if (! $i) $totalarray['nbfield']++; } - + + // Type + if (! empty($arrayfields['f.type']['checked'])) + { + print '"; + if (! $i) $totalarray['nbfield']++; + } + // Date if (! empty($arrayfields['f.date']['checked'])) { @@ -882,7 +928,7 @@ if ($resql) print ''; if (! $i) $totalarray['nbfield']++; } - + // Date limit if (! empty($arrayfields['f.date_lim_reglement']['checked'])) { @@ -894,7 +940,7 @@ if ($resql) print ''; if (! $i) $totalarray['nbfield']++; } - + // Third party if (! empty($arrayfields['s.nom']['checked'])) { @@ -948,7 +994,7 @@ if ($resql) print ''; if (! $i) $totalarray['nbfield']++; } - + // Payment mode if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { @@ -957,7 +1003,7 @@ if ($resql) print ''; if (! $i) $totalarray['nbfield']++; } - + // Amount HT if (! empty($arrayfields['f.total_ht']['checked'])) { @@ -998,7 +1044,7 @@ if ($resql) if (! $i) $totalarray['totalrtpfield']=$totalarray['nbfield']; $totalarray['totalrtp'] += $remaintopay; } - + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { @@ -1109,10 +1155,6 @@ if ($resql) $genallowed=$user->rights->facture->lire; $delallowed=$user->rights->facture->lire; - print '
    '; - $paramwithoutshowfiles=preg_replace('/show_files=1&?/','',$param); - $title=$langs->trans("MassFilesArea").' ('.$langs->trans("Hide").')'; - print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index 9ca0c2f7718..5c5aa8489be 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -36,6 +36,8 @@ $mode=GETPOST("mode")?GETPOST("mode"):'customer'; if ($mode == 'customer' && ! $user->rights->facture->lire) accessforbidden(); if ($mode == 'supplier' && ! $user->rights->fournisseur->facture->lire) accessforbidden(); +$object_status=GETPOST('object_status'); + $userid=GETPOST('userid','int'); $socid=GETPOST('socid','int'); // Security check @@ -80,7 +82,14 @@ print load_fiche_titre($title, $mesg, 'title_accountancy.png'); 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 ('.$object_status.')'; +} +if ($mode == 'supplier') +{ + if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$object_status.')'; +} // Build graphic number of object // $data = array(array('Lib',val1,val2,val3),...) @@ -246,6 +255,19 @@ print '
    '; print '
    '; + // Status + print ''; // Year print ''; print ''; print ''; - print ''; + if (!empty($conf->multicurrency->enabled)) print ''; if (!empty($conf->multicurrency->enabled)) print ''; - print ''; if (!empty($conf->multicurrency->enabled)) print ''; - print ''; if (!empty($conf->multicurrency->enabled)) print ''; + print ''; + print ''; + print ''; print ''; if (!empty($conf->multicurrency->enabled)) print ''; print ''; @@ -624,12 +631,35 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie // Date print '\n"; - - // Price - print ''; - + + // Currency + if (!empty($conf->multicurrency->enabled)) print '\n"; + // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) print ''; + if (!empty($conf->multicurrency->enabled)) + { + print ''; + + // Multicurrency Price + print ''; + + // Multicurrency Price + print ''; + } + + // Price + print ''; // Received or paid back print ''; - // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) - { - print ''; - } - // Remain to take or to pay back print ''; //$test= price(price2num($objp->total_ttc - $paiement - $creditnotes - $deposits)); - // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) - { - print ''; - } - // Amount print '"; // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) + if (! empty($conf->multicurrency->enabled)) { print '"; } @@ -727,16 +745,16 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie { // Print total print ''; - print ''; - print ''; + print ''; if (!empty($conf->multicurrency->enabled)) print ''; + if (!empty($conf->multicurrency->enabled)) print ''; + if (!empty($conf->multicurrency->enabled)) print ''; + print ''; print ''; - if (!empty($conf->multicurrency->enabled)) print ''; print ''; - if (!empty($conf->multicurrency->enabled)) print ''; print ''; if (!empty($conf->multicurrency->enabled)) print ''; print ''; diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php index 0ffaf49b955..94686162687 100644 --- a/htdocs/compta/paiement/cheque/card.php +++ b/htdocs/compta/paiement/cheque/card.php @@ -3,8 +3,8 @@ * Copyright (C) 2007-2011 Laurent Destailleur * Copyright (C) 2009-2012 Regis Houssin * Copyright (C) 2011-2016 Juanjo Menent - * Copyright (C) 2013 Philippe Grand - * Copyright (C) 2015 Alexandre Spangaro + * Copyright (C) 2013 Philippe Grand + * Copyright (C) 2015-2016 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 @@ -21,9 +21,9 @@ */ /** - * \file htdocs/compta/paiement/cheque/card.php - * \ingroup bank, invoice - * \brief Page for cheque deposits + * \file htdocs/compta/paiement/cheque/card.php + * \ingroup bank, invoice + * \brief Page for cheque deposits */ require '../../../main.inc.php'; @@ -57,7 +57,7 @@ if ($page < 0) { $page = 0 ; } $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $offset = $limit * $page ; -$dir=$conf->banque->dir_output.'/bordereau/'; +$dir=$conf->bank->dir_output.'/checkdeposits/'; $filterdate=dol_mktime(0, 0, 0, GETPOST('fdmonth'), GETPOST('fdday'), GETPOST('fdyear')); $filteraccountid=GETPOST('accountid'); @@ -95,7 +95,7 @@ if ($action == 'setrefext' && $user->rights->banque->cheque) { $ref_ext = GETPOST('ref_ext'); - $result=$object->setValueFrom('ref_ext', $ref_ext); + $result=$object->setValueFrom('ref_ext', $ref_ext, '', null, 'text', '', $user, 'CHECKDEPOSIT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -298,7 +298,9 @@ if (GETPOST('removefilter')) $filteraccountid=0; } -llxHeader(); +$title=$langs->trans("Cheques") . " - " . $langs->trans("Card"); +$helpurl=""; +llxHeader("",$title,$helpurl); $form = new Form($db); $formfile = new FormFile($db); @@ -386,7 +388,7 @@ if ($action == 'new') print '
    '; + $listtype=array( + Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), + Facture::TYPE_REPLACEMENT=>$langs->trans("InvoiceReplacement"), + Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), + Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), + ); + //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. + print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); + print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100'); print '
    '; + print $facturestatic->getLibType(); + print "
    '.$langs->trans("CreatedBy").''; print $form->select_dolusers($userid, 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); print '
    '.$langs->trans("Status").''; + if ($mode == 'customer') + { + $liststatus=array('0'=>$langs->trans("BillStatusDraft"), '1'=>$langs->trans("BillStatusNotPaid"), '2'=>$langs->trans("BillStatusPaid"), '3'=>$langs->trans("BillStatusCanceled")); + print $form->selectarray('object_status', $liststatus, $object_status, 1); + } + if ($mode == 'supplier') + { + $liststatus=array('0'=>$langs->trans("BillStatusDraft"),'1'=>$langs->trans("BillStatusNotPaid"), '2'=>$langs->trans("BillStatusPaid")); + print $form->selectarray('object_status', $liststatus, $object_status, 1); + } + print '
    '.$langs->trans("Year").''; if (! in_array($year,$arrayyears)) $arrayyears[$year]=$year; diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index 1dd1c46299a..40e3b80a510 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -577,7 +577,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -663,7 +663,7 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us $i = 0; print '
    '.$langs->trans("ContributionsToPay").($num?' '.$num.'':'').''.$langs->trans("ContributionsToPay").($num?' '.$num.'':'').''.$langs->trans("DateDue").''.$langs->trans("AmountTTC").''.$langs->trans("Paid").'
    '; print ""; - print ''; + print ''; if (! empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; print ''; diff --git a/htdocs/compta/localtax/index.php b/htdocs/compta/localtax/index.php index d7b6b897ec3..642c37b9d65 100644 --- a/htdocs/compta/localtax/index.php +++ b/htdocs/compta/localtax/index.php @@ -277,7 +277,8 @@ $sql.= " WHERE f.entity = ".$conf->entity; $sql.= " AND f.datev >= '".$db->idate(dol_get_first_day($y,1,false))."'"; $sql.= " AND f.datev <= '".$db->idate(dol_get_last_day($y,12,false))."'"; $sql.= " AND localtaxtype=".$localTaxType; -$sql.= " GROUP BY dm ASC ORDER BY dm ASC"; +$sql.= " GROUP BY dm"; +$sql.= " ORDER BY dm ASC"; pt($db, $sql,$langs->trans("Year")." $y"); diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index c11b2c815bc..a1f50959aa4 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005 Marc Barilley / Ocebo * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke @@ -38,6 +38,7 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $langs->load('companies'); $langs->load('bills'); $langs->load('banks'); +$langs->load('multicurrency'); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm'); @@ -362,7 +363,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie if (code == \'CHQ\' || code == \'VIR\') { - $(\'.fieldrequireddyn\').addClass(\'fieldrequired\'); + if (code == \'CHQ\') + { + $(\'.fieldrequireddyn\').addClass(\'fieldrequired\'); + } if ($(\'#fieldchqemetteur\').val() == \'\') { var emetteur = ('.$facture->type.' == 2) ? \''.dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM).'\' : jQuery(\'#thirdpartylabel\').val(); @@ -394,7 +398,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie json["invoice_type"] = $("#invoice_type").val(); json["amountPayment"] = $("#amountpayment").attr("value"); json["amounts"] = _elemToJson(form.find("input.amount")); - json["remains"] = _elemToJson(form.find("input.remain]")); + json["remains"] = _elemToJson(form.find("input.remain")); if (imgId != null) { json["imgClicked"] = imgId; @@ -433,7 +437,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie '; print ' });'."\n"; - if(!empty($conf->global->INVOICE_AUTO_FILLJS)){ + if (!empty($conf->use_javascript_ajax)){ //Add js for AutoFill print ' $(document).ready(function () {'; print ' $(".AutoFillAmout").on(\'click touchstart\', function(){ @@ -457,24 +461,19 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '
    '.$langs->trans("OrdersToBill").' '.$num.''.$langs->trans("OrdersDeliveredToBill").' '.$num.''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("ToBill").'
    '; // Third party - print '\n"; + print '\n"; // Date payment print ''; - print ''; - - $rowspan=5; + print ''; // Payment mode print '\n"; - print ''; print ''; // Bank account @@ -489,7 +488,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } else { - print ''; + print ''; } print "\n"; @@ -511,14 +510,21 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print ''; print ''; + // Comments + print ''; + print ''; + print '
    '.$langs->trans('Company').''.$facture->thirdparty->getNomUrl(4)."
    '.$langs->trans('Company').''.$facture->thirdparty->getNomUrl(4)."
    '.$langs->trans('Date').''; $datepayment = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); $datepayment= ($datepayment == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE)?-1:'') : $datepayment); $form->select_date($datepayment,'','','',0,"add_paiement",1,1,0,0,'','',$facture->date); - print ''.$langs->trans('Comments').'
    '.$langs->trans('PaymentMode').''; $form->select_types_paiements((GETPOST('paiementcode')?GETPOST('paiementcode'):$facture->mode_reglement_code),'paiementcode','',2); print "'; - print '
      
    '.$langs->trans('Comments').''; + print '
    '; dol_fiche_end(); + /* * List of unpaid invoices */ - $sql = 'SELECT f.rowid as facid, f.facnumber, f.total_ttc, f.multicurrency_total_ttc, f.type, '; + + $sql = 'SELECT f.rowid as facid, f.facnumber, f.total_ttc, f.multicurrency_code, f.multicurrency_total_ttc, f.type, '; $sql.= ' f.datef as df, f.fk_soc as socid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; @@ -572,12 +578,13 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '
    '.$arraytitle.''.$langs->trans('Date').''.$langs->trans('AmountTTC').''.$langs->trans('Currency').''.$langs->trans('MulticurrencyAmountTTC').''.$alreadypayedlabel.''.$multicurrencyalreadypayedlabel.''.$remaindertopay.''.$multicurrencyremaindertopay.''.$langs->trans('AmountTTC').''.$alreadypayedlabel.''.$remaindertopay.''.$langs->trans('PaymentAmount').''.$langs->trans('MulticurrencyPaymentAmount').' '.dol_print_date($db->jdate($objp->df),'day')."'.price($sign * $objp->total_ttc).''.$objp->multicurrency_code."'.price($sign * $objp->multicurrency_total_ttc).''; + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $objp->multicurrency_total_ttc); + print ''; + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) + { + print price($sign * $multicurrency_payment); + if ($multicurrency_creditnotes) print '+'.price($multicurrency_creditnotes); + if ($multicurrency_deposits) print '+'.price($multicurrency_deposits); + } + print ''; + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) print price($sign * $multicurrency_remaintopay); + print ''.price($sign * $objp->total_ttc).''.price($sign * $paiement); @@ -637,25 +667,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie if ($deposits) print '+'.price($deposits); print ''.price($sign * $multicurrency_payment); - if ($multicurrency_creditnotes) print '+'.price($multicurrency_creditnotes); - if ($multicurrency_deposits) print '+'.price($multicurrency_deposits); - print ''.price($sign * $remaintopay).''.price($sign * $multicurrency_remaintopay).''; @@ -665,7 +680,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie if ($action != 'add_paiement') { - if(!empty($conf->global->INVOICE_AUTO_FILLJS)) + if (!empty($conf->use_javascript_ajax)) print img_picto("Auto fill",'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'"); print ''; print ''; @@ -678,7 +693,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print "'; @@ -686,17 +701,20 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $namef = 'multicurrency_amount_'.$objp->facid; $nameRemain = 'multicurrency_remain_'.$objp->facid; - if ($action != 'add_paiement') + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { - if(!empty($conf->global->INVOICE_AUTO_FILLJS)) - print img_picto("Auto fill",'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'"); - print ''; - print ''; - } - else - { - print ''; - print ''; + if ($action != 'add_paiement') + { + if (!empty($conf->use_javascript_ajax)) + print img_picto("Auto fill",'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'"); + print ''; + print ''; + } + else + { + print ''; + print ''; + } } print "
    '.$langs->trans('TotalTTC').''.price($sign * $total_ttc).''.$langs->trans('TotalTTC').''.price($sign * $total_ttc).''.price($sign * $totalrecu); if ($totalrecucreditnote) print '+'.price($totalrecucreditnote); if ($totalrecudeposits) print '+'.price($totalrecudeposits); print ''.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits,'MT')).' 
    '; //print ''; // Filter - print ''; print '\n"; print '\n"; print ''; - + // Link to payment print ''; - + print '' ; @@ -563,7 +565,7 @@ else $accountstatic->label=$object->account_label; print '
    '.$langs->trans('Date').''.dol_print_date($now,'day').'
    '.$langs->trans("DateChequeReceived").''; + print '
    '.$langs->trans("DateChequeReceived").''; print $form->select_date($filterdate,'fd',0,0,1,'',1,1,1); print '
    '.$langs->trans("BankAccount").''; @@ -502,7 +504,7 @@ if ($action == 'new') print ''.$value["emetteur"]."'.$value["banque"]."'.price($value["amount"], 0, $langs, 1, -1, -1, $conf->currency).''; $paymentstatic->id=$value["paymentid"]; @@ -528,7 +530,7 @@ if ($action == 'new') print ' '; } print ''; print ''; print '
    '; - print '\n"; + $i++; } -print '
    '; +print "
    '; + print '
    '; print ''; diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 12195e5e05e..5bc09419666 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -1525,7 +1525,8 @@ class BonPrelevement extends CommonObject */ static function buildRumNumber($row_code_client, $row_datec, $row_drum) { - $pre = ($row_datec > 1359673200) ? 'RUM-' : '++R'; + global $langs; + $pre = ($row_datec > 1359673200) ? $langs->trans('RUM').'-' : '++R'; return $pre.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec); } @@ -1565,7 +1566,7 @@ class BonPrelevement extends CommonObject $XML_DEBITOR =''; $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.$CrLf; - $XML_DEBITOR .=' '.('AS-'.$row_facnumber.'-'.$Rowing).''.$CrLf; + $XML_DEBITOR .=' '.('AS-'.dol_trunc($row_facnumber,20).'-'.$Rowing).''.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters $XML_DEBITOR .=' '.$CrLf; $XML_DEBITOR .=' '.round($row_somme, 2).''.$CrLf; $XML_DEBITOR .=' '.$CrLf; diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index 3350f5c34a3..8be897990ed 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -122,7 +122,7 @@ if ($nb < 0 || $nb1 < 0 || $nb11 < 0) } print '
    '; print $langs->trans('Ref'); @@ -760,7 +762,7 @@ else dol_print_error($db); } - dol_fiche_end(); + dol_fiche_end(); } @@ -799,7 +801,7 @@ if ($action != 'new') $filedir=$dir.get_exdir($object->ref,0,1,0,$object,'cheque') . dol_sanitizeFileName($object->ref); $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $formfile->show_documents('remisecheque', $filename, $filedir, $urlsource, 1, 1); + print $formfile->showdocuments('remisecheque', $filename, $filedir, $urlsource, 1, 1); print '
    '; } diff --git a/htdocs/compta/paiement/cheque/class/remisecheque.class.php b/htdocs/compta/paiement/cheque/class/remisecheque.class.php index 6ab43a277c0..998fd1db7c3 100644 --- a/htdocs/compta/paiement/cheque/class/remisecheque.class.php +++ b/htdocs/compta/paiement/cheque/class/remisecheque.class.php @@ -597,7 +597,7 @@ class RemiseCheque extends CommonObject // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. $sav_charseSupprimert_output=$outputlangs->charset_output; - $result=$docmodel->write_file($this, $conf->banque->dir_output.'/bordereau', $this->ref, $outputlangs); + $result=$docmodel->write_file($this, $conf->bank->dir_output.'/checkdeposits', $this->ref, $outputlangs); if ($result > 0) { //$outputlangs->charset_output=$sav_charset_output; diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php index ebfd598ee0b..df02264badc 100644 --- a/htdocs/compta/paiement/cheque/list.php +++ b/htdocs/compta/paiement/cheque/list.php @@ -191,7 +191,7 @@ if ($resql) // Bank print '
    '; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; else print ' '; print '
    '; -print ''; +print ''; print ''; diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 95ea2bfe46c..63d4b9930ed 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -149,6 +149,11 @@ $hselected = 'report'; report_header($name,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); +if (! empty($conf->accounting->enabled)) +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + // Show report array print '
    '.$langs->trans("NbOfInvoiceToWithdraw").'
    '.$langs->trans("NbOfInvoiceToWithdraw").''; print $nb; print '
    '; print ''; @@ -710,13 +715,22 @@ if (! empty($conf->expensereport->enabled)) if (! empty($conf->don->enabled)) { print ''; - $sql = "SELECT p.societe as name, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; - $sql.= " WHERE p.entity = ".$conf->entity; if ($modecompta == 'CREANCES-DETTES') - $sql.= " AND fk_statut in (1,2)"; + { + $sql = "SELECT p.societe as name, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + $sql.= " AND fk_statut in (1,2)"; + } else - $sql.= " AND fk_statut=2"; + { + $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " WHERE p.entity = ".getEntity('donation',1); + $sql.= " AND fk_statut >= 2"; + } if (! empty($date_start) && ! empty($date_end)) $sql.= " AND p.datedon >= '".$db->idate($date_start)."' AND p.datedon <= '".$db->idate($date_end)."'"; $sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index 861b44edd6c..62ef55fb711 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -93,6 +93,12 @@ $hselected='report'; report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); +if (! empty($conf->accounting->enabled)) +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + + /* * Factures clients @@ -474,9 +480,11 @@ $parameters["mode"] = $modecompta; $hookmanager->initHooks(array('externalbalance')); $reshook=$hookmanager->executeHooks('addReportInfo',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + /* * Salaries */ + if (! empty($conf->salaries->enabled)) { if ($modecompta == 'CREANCES-DETTES') { @@ -580,15 +588,23 @@ if (! empty($conf->don->enabled)) { $subtotal_ht = 0; $subtotal_ttc = 0; - $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; - $sql.= " WHERE p.entity = ".$conf->entity; - if ($modecompta == 'CREANCES-DETTES') - $sql.= " AND fk_statut in (1,2)"; - else - $sql.= " AND fk_statut=2"; - $sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; + if ($modecompta == 'CREANCES-DETTES') { + $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + $sql.= " AND fk_statut in (1,2)"; + } + else { + $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_donation as pe ON pe.fk_donation = p.rowid"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; + $sql.= " WHERE p.entity = ".getEntity('donation',1); + $sql.= " AND fk_statut >= 2"; + } + $sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; + dol_syslog("get donation payments"); $result=$db->query($sql); if ($result) diff --git a/htdocs/compta/salaries/card.php b/htdocs/compta/salaries/card.php index ea0070ef50b..a7921e53859 100644 --- a/htdocs/compta/salaries/card.php +++ b/htdocs/compta/salaries/card.php @@ -73,8 +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; - $object->accountid=GETPOST("accountid","int"); - $object->fk_user=GETPOST("fk_user","int"); + $object->accountid=GETPOST("accountid") > 0 ? GETPOST("accountid","int") : 0; + $object->fk_user=GETPOST("fk_user") > 0 ? GETPOST("fk_user","int") : 0; $object->datev=$datev; $object->datep=$datep; $object->amount=price2num(GETPOST("amount")); @@ -82,7 +82,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $object->datesp=$datesp; $object->dateep=$dateep; $object->note=GETPOST("note"); - $object->type_payment=GETPOST("paymenttype"); + $object->type_payment=GETPOST("paymenttype") > 0 ? GETPOST("paymenttype", "int") : 0; $object->num_payment=GETPOST("num_payment"); $object->fk_user_author=$user->id; @@ -113,7 +113,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) } if (! empty($conf->banque->enabled) && ! $object->accountid > 0) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Account")), null, 'errors'); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); $error++; } @@ -282,7 +282,7 @@ if ($action == 'create') if (! empty($conf->banque->enabled)) { print ''; } diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php index 3e3fca22ffa..4de0e829538 100644 --- a/htdocs/compta/salaries/index.php +++ b/htdocs/compta/salaries/index.php @@ -158,7 +158,7 @@ if ($result) print_liste_field_titre($langs->trans("Label"),$_SERVER["PHP_SELF"],"s.label","",$param,'align="left"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DatePayment"),$_SERVER["PHP_SELF"],"s.datep","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("PaymentMode"),$_SERVER["PHP_SELF"],"type","",$param,'align="left"',$sortfield,$sortorder); - if (! empty($conf->banque->enabled)) print_liste_field_titre($langs->trans("Account"),$_SERVER["PHP_SELF"],"ba.label","",$param,"",$sortfield,$sortorder); + if (! empty($conf->banque->enabled)) print_liste_field_titre($langs->trans("BankAccount"),$_SERVER["PHP_SELF"],"ba.label","",$param,"",$sortfield,$sortorder); print_liste_field_titre($langs->trans("PayedByThisPayment"),$_SERVER["PHP_SELF"],"s.amount","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; diff --git a/htdocs/compta/sociales/class/cchargesociales.class.php b/htdocs/compta/sociales/class/cchargesociales.class.php index 494e563b587..538754e63b2 100644 --- a/htdocs/compta/sociales/class/cchargesociales.class.php +++ b/htdocs/compta/sociales/class/cchargesociales.class.php @@ -530,7 +530,7 @@ class Cchargesociales if ($withpicto) { - $result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); + $result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto != 2) $result.=' '; } $result.= $link . $this->ref . $linkend; diff --git a/htdocs/compta/sociales/index.php b/htdocs/compta/sociales/index.php index fc106de2ad1..6a4f7f836e7 100644 --- a/htdocs/compta/sociales/index.php +++ b/htdocs/compta/sociales/index.php @@ -40,6 +40,7 @@ $result = restrictedArea($user, 'tax', '', '', 'charges'); $search_ref = GETPOST('search_ref','int'); $search_label = GETPOST('search_label','alpha'); $search_amount = GETPOST('search_amount','alpha'); +$search_status = GETPOST('search_status','int'); $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -52,8 +53,8 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield="cs.date_ech"; if (! $sortorder) $sortorder="DESC"; -$year=$_GET["year"]; -$filtre=$_GET["filtre"]; +$year=GETPOST("year",'int'); +$filtre=GETPOST("filtre",'int'); if (empty($_REQUEST['typeid'])) { @@ -75,6 +76,7 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETP $search_ref=""; $search_label=""; $search_amount=""; + $search_status=''; $typeid=""; $year=""; $month=""; @@ -88,7 +90,7 @@ $form = new Form($db); $formsocialcontrib = new FormSocialContrib($db); $chargesociale_static=new ChargeSociales($db); -llxHeader(); +llxHeader('', $langs->trans("SocialContributions")); $sql = "SELECT cs.rowid as id, cs.fk_type as type, "; $sql.= " cs.amount, cs.date_ech, cs.libelle, cs.paye, cs.periode,"; @@ -99,11 +101,11 @@ $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; $sql.= " WHERE cs.fk_type = c.id"; $sql.= " AND cs.entity = ".$conf->entity; - // Search criteria -if ($search_ref) $sql.=" AND cs.rowid=".$search_ref; +if ($search_ref) $sql.=" AND cs.rowid=".$db->escape($search_ref); if ($search_label) $sql.=natural_search("cs.libelle", $search_label); if ($search_amount) $sql.=natural_search("cs.amount", price2num(trim($search_amount)), 1); +if ($search_status != '' && $search_status >= 0) $sql.=" AND cs.paye = ".$db->escape($search_status); if ($year > 0) { $sql .= " AND ("; @@ -118,7 +120,7 @@ if ($filtre) { $sql .= " AND ".$filtre; } if ($typeid) { - $sql .= " AND cs.fk_type=".$typeid; + $sql .= " AND cs.fk_type=".$db->escape($typeid); } $sql.= " GROUP BY cs.rowid, cs.fk_type, cs.amount, cs.date_ech, cs.libelle, cs.paye, cs.periode, c.libelle"; $sql.= $db->order($sortfield,$sortorder); @@ -204,7 +206,10 @@ if ($resql) print ''; print ''; // Status - print ''; + print ''; print ''; -print ''; print ''; @@ -340,6 +365,33 @@ print_liste_field_titre( "", $sortfield,$sortorder ); +print_liste_field_titre( + $langs->trans("Zip"), + $_SERVER["PHP_SELF"], + "zip", + "", + $paramslink, + "", + $sortfield,$sortorder + ); +print_liste_field_titre( + $langs->trans("Town"), + $_SERVER["PHP_SELF"], + "town", + "", + $paramslink, + "", + $sortfield,$sortorder + ); +print_liste_field_titre( + $langs->trans("Country"), + $_SERVER["PHP_SELF"], + "country", + "", + $paramslink, + "", + $sortfield,$sortorder + ); if ($modecompta == 'CREANCES-DETTES') { print_liste_field_titre( $langs->trans('AmountHT'), @@ -383,6 +435,27 @@ print_liste_field_titre( 'align="center" width="20%"' ); print "\n"; + +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + $var=true; if (count($amount)) { @@ -412,6 +485,30 @@ if (count($amount)) { arsort($amount); $arrayforsort=$amount; } + if ($sortfield == 'zip' && $sortorder == 'asc') { + asort($address_zip); + $arrayforsort=$address_zip; + } + if ($sortfield == 'zip' && $sortorder == 'desc') { + arsort($address_zip); + $arrayforsort=$address_zip; + } + if ($sortfield == 'town' && $sortorder == 'asc') { + asort($address_town); + $arrayforsort=$address_town; + } + if ($sortfield == 'town' && $sortorder == 'desc') { + arsort($address_town); + $arrayforsort=$address_town; + } + if ($sortfield == 'country' && $sortorder == 'asc') { + asort($address_pays); + $arrayforsort=$address_town; + } + if ($sortfield == 'country' && $sortorder == 'desc') { + arsort($address_pays); + $arrayforsort=$address_town; + } foreach($arrayforsort as $key=>$value) { $var=!$var; @@ -429,6 +526,18 @@ if (count($amount)) { } print "\n"; + print ''; + + print ''; + + print ''; + // Amount w/o VAT print ''; print ''; + print ''; + print ''; + print ''; if ($modecompta != 'CREANCES-DETTES') { print ''; } else { diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index eb9a425c2af..1a343cbcb0b 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -85,6 +85,11 @@ $moreparam=array(); if (! empty($modecompta)) $moreparam['modecompta']=$modecompta; report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode); +if (! empty($conf->accounting->enabled)) +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + if ($modecompta == 'CREANCES-DETTES') { @@ -135,7 +140,7 @@ else { dol_print_error($db); } -// On ajoute les paiements anciennes version, non lies par paiement_facture +// On ajoute les paiements anciennes version, non lies par paiement_facture (very old versions) if ($modecompta != 'CREANCES-DETTES') { $sql = "SELECT date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount_ttc"; diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 31eb96d633f..a2f97d9ad93 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -54,7 +54,6 @@ $confirm = GETPOST('confirm','alpha'); $backtopage = GETPOST('backtopage','alpha'); $id = GETPOST('id','int'); $socid = GETPOST('socid','int'); -if ($user->societe_id) $socid=$user->societe_id; $object = new Contact($db); $extrafields = new ExtraFields($db); @@ -74,6 +73,7 @@ if (! empty($canvas)) } // Security check +if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', $objcanvas); // If we create a contact with no company (shared contacts), no check on write permission // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array @@ -1254,9 +1254,9 @@ else print load_fiche_titre($langs->trans("TasksHistoryForThisContact"),$out,''); - print show_actions_todo($conf,$langs,$db,$objsoc,$object); + //print show_actions_todo($conf,$langs,$db,$objsoc,$object); - print show_actions_done($conf,$langs,$db,$objsoc,$object); + print show_actions_done($conf,$langs,$db,$objsoc,$object,0,'',''); } } } diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index c10d2b508dc..4e045ccd449 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -1090,24 +1090,24 @@ class Contact extends CommonObject } elseif ($mode == 2) { - if ($statut==0 || $statut==5) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); - elseif ($statut==1 || $statut==4) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($statut==0 || $statut==5) return img_picto($langs->trans('Disabled'),'statut5', 'class="pictostatus"').' '.$langs->trans('Disabled'); + elseif ($statut==1 || $statut==4) return img_picto($langs->trans('Enabled'),'statut4', 'class="pictostatus"').' '.$langs->trans('Enabled'); } elseif ($mode == 3) { - if ($statut==0 || $statut==5) return img_picto($langs->trans('Disabled'),'statut5'); - elseif ($statut==1 || $statut==4) return img_picto($langs->trans('Enabled'),'statut4'); + if ($statut==0 || $statut==5) return img_picto($langs->trans('Disabled'),'statut5', 'class="pictostatus"'); + elseif ($statut==1 || $statut==4) return img_picto($langs->trans('Enabled'),'statut4', 'class="pictostatus"'); } elseif ($mode == 4) { - if ($statut==0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); - elseif ($statut==1 || $statut==4) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($statut==0) return img_picto($langs->trans('Disabled'),'statut5', 'class="pictostatus"').' '.$langs->trans('Disabled'); + elseif ($statut==1 || $statut==4) return img_picto($langs->trans('Enabled'),'statut4', 'class="pictostatus"').' '.$langs->trans('Enabled'); } elseif ($mode == 5) { - if ($statut==0 || $statut==5) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); - elseif ($statut==1 || $statut==4) return ''.$langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); + if ($statut==0 || $statut==5) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5', 'class="pictostatus"'); + elseif ($statut==1 || $statut==4) return ''.$langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4', 'class="pictostatus"'); } } diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index 988dfc28dad..825c1e8dab5 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -37,9 +37,22 @@ $id = GETPOST('id','int'); $action = GETPOST("action"); $confirm = GETPOST('confirm', 'alpha'); +$object = new Contact($db); + +// Get object canvas (By default, this is not defined, so standard usage of dolibarr) +$object->getCanvas($id); +$objcanvas=null; +$canvas = (! empty($object->canvas)?$object->canvas:GETPOST("canvas")); +if (! empty($canvas)) +{ + require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; + $objcanvas = new Canvas($db, $action); + $objcanvas->getCanvas('contact', 'contactcard', $canvas); +} + // Security check if ($user->societe_id) $socid=$user->societe_id; -$result = restrictedArea($user, 'contact', $id, '',''); +$result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', $objcanvas); // If we create a contact with no company (shared contacts), no check on write permission // Get parameters $sortfield = GETPOST("sortfield",'alpha'); @@ -54,7 +67,6 @@ $pagenext = $page + 1; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="name"; -$object = new Contact($db); if ($id > 0) $object->fetch($id); $upload_dir = $conf->societe->dir_output.'/contact/'.dol_sanitizeFileName($object->ref); @@ -138,6 +150,7 @@ if ($object->id) $modulepart = 'contact'; $permission = $user->rights->societe->contact->creer; + $permtoedit = $user->rights->societe->contact->creer; $param = '&id=' . $object->id; include DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 5504d43671c..7b2e5528eb6 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -129,18 +129,18 @@ $fieldstosearchall = array( $arrayfields=array( 'p.lastname'=>array('label'=>$langs->trans("Lastname"), 'checked'=>1), 'p.firstname'=>array('label'=>$langs->trans("Firstname"), 'checked'=>1), - 'p.poste'=>array('label'=>$langs->trans("Post"), 'checked'=>1), + 'p.poste'=>array('label'=>$langs->trans("PostOrFunction"), 'checked'=>1), 'p.town'=>array('label'=>$langs->trans("Town"), 'checked'=>0), 'p.zip'=>array('label'=>$langs->trans("Zip"), 'checked'=>0), - 'p.phone'=>array('label'=>$langs->trans("PhonePro"), 'checked'=>1), + 'p.phone'=>array('label'=>$langs->trans("Phone"), 'checked'=>1), 'p.phone_perso'=>array('label'=>$langs->trans("PhonePerso"), 'checked'=>0), 'p.phone_mobile'=>array('label'=>$langs->trans("PhoneMobile"), 'checked'=>1), 'p.fax'=>array('label'=>$langs->trans("Fax"), 'checked'=>1), - 'p.email'=>array('label'=>$langs->trans("Email"), 'checked'=>1), + 'p.email'=>array('label'=>$langs->trans("EMail"), 'checked'=>1), 'p.skype'=>array('label'=>$langs->trans("Skype"), 'checked'=>1, 'enabled'=>(! empty($conf->skype->enabled))), 'p.thirdparty'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'enabled'=>empty($conf->global->SOCIETE_DISABLE_CONTACTS)), 'p.priv'=>array('label'=>$langs->trans("ContactVisibility"), 'checked'=>1, 'position'=>200), - 'p.datec'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0, 'position'=>500), + 'p.datec'=>array('label'=>$langs->trans("DateCreationShort"), 'checked'=>0, 'position'=>500), 'p.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500), 'p.statut'=>array('label'=>$langs->trans("Status"), 'checked'=>1, 'position'=>1000), ); @@ -165,39 +165,51 @@ if (($id > 0 || ! empty($ref)) && $action != 'add') * Actions */ +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (empty($reshook)) { - + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter')) // All tests are required to be compatible with all browsers + { + $sall=""; + $search_firstlast_only=""; + $search_lastname=""; + $search_firstname=""; + $search_societe=""; + $search_poste=""; + $search_phone=""; + $search_phone_perso=""; + $search_phone_pro=""; + $search_phone_mobile=""; + $search_fax=""; + $search_email=""; + $search_skype=""; + $search_priv=""; + $search_status=-1; + $search_categ=''; + $search_categ_thirdparty=''; + $search_categ_supplier=''; + $search_array_options=array(); + } + + // Mass actions + $objectclass='Contact'; + $objectlabel='Contact'; + $permtoread = $user->rights->societe->lire; + $permtodelete = $user->rights->societe->delete; + $uploaddir = $conf->societe->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } -if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter')) // All tests are required to be compatible with all browsers -{ - $sall=""; - $search_firstlast_only=""; - $search_lastname=""; - $search_firstname=""; - $search_societe=""; - $search_poste=""; - $search_phone=""; - $search_phone_perso=""; - $search_phone_pro=""; - $search_phone_mobile=""; - $search_fax=""; - $search_email=""; - $search_skype=""; - $search_priv=""; - $search_status=-1; - $search_categ=''; - $search_categ_thirdparty=''; - $search_categ_supplier=''; - $search_array_options=array(); -} if ($search_priv < 0) $search_priv=''; @@ -210,7 +222,6 @@ $formother=new FormOther($db); $contactstatic=new Contact($db); $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -llxHeader('',$title,'EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'); $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql.= " p.rowid as cidp, p.lastname as lastname, p.statut, p.firstname, p.zip, p.town, p.poste, p.email, p.skype,"; @@ -343,7 +354,6 @@ foreach ($search_array_options as $key => $val) $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; - // Add order if ($view == "recent") { @@ -367,218 +377,371 @@ $sql.= $db->plimit($limit+1, $offset); //print $sql; dol_syslog("contact/list.php", LOG_DEBUG); $result = $db->query($sql); -if ($result) +if (! $result) { - $num = $db->num_rows($result); - $i = 0; + dol_print_error($db); + exit; +} - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - $param.='&begin='.urlencode($begin).'&view='.urlencode($view).'&userid='.urlencode($userid).'&contactname='.urlencode($sall); - $param.='&type='.urlencode($type).'&view='.urlencode($view); - if (!empty($search_categ)) $param.='&search_categ='.urlencode($search_categ); - if (!empty($search_categ_thirdparty)) $param.='&search_categ_thirdparty='.urlencode($search_categ_thirdparty); - if (!empty($search_categ_supplier)) $param.='&search_categ_supplier='.urlencode($search_categ_supplier); - if ($search_lastname != '') $param.='&search_lastname='.urlencode($search_lastname); - if ($search_firstname != '') $param.='&search_firstname='.urlencode($search_firstname); - if ($search_societe != '') $param.='&search_societe='.urlencode($search_societe); - if ($search_zip != '') $param.='&search_zip='.urlencode($search_zip); - if ($search_town != '') $param.='&search_town='.urlencode($search_town); - if ($search_job != '') $param.='&search_job='.urlencode($search_job); - if ($search_phone_pro != '') $param.='&search_phone_pro='.urlencode($search_phone_pro); - if ($search_phone_perso != '') $param.='&search_phone_perso='.urlencode($search_phone_perso); - if ($search_phone_mobile != '') $param.='&search_phone_mobile='.urlencode($search_phone_mobile); - if ($search_fax != '') $param.='&search_fax='.urlencode($search_fax); - if ($search_email != '') $param.='&search_email='.urlencode($search_email); - if ($search_status != '') $param.='&search_status='.urlencode($search_status); - if ($search_priv == '0' || $search_priv == '1') $param.="&search_priv=".urlencode($search_priv); - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; +$num = $db->num_rows($result); - print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit); +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) +{ + $obj = $db->fetch_object($resql); + $id = $obj->cidp; + header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); + exit; +} - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } - if ($search_firstlast_only) +llxHeader('',$title,'EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +$param.='&begin='.urlencode($begin).'&view='.urlencode($view).'&userid='.urlencode($userid).'&contactname='.urlencode($sall); +$param.='&type='.urlencode($type).'&view='.urlencode($view); +if (!empty($search_categ)) $param.='&search_categ='.urlencode($search_categ); +if (!empty($search_categ_thirdparty)) $param.='&search_categ_thirdparty='.urlencode($search_categ_thirdparty); +if (!empty($search_categ_supplier)) $param.='&search_categ_supplier='.urlencode($search_categ_supplier); +if ($sall != '') $param.='&sall='.urlencode($sall); +if ($search_lastname != '') $param.='&search_lastname='.urlencode($search_lastname); +if ($search_firstname != '') $param.='&search_firstname='.urlencode($search_firstname); +if ($search_societe != '') $param.='&search_societe='.urlencode($search_societe); +if ($search_zip != '') $param.='&search_zip='.urlencode($search_zip); +if ($search_town != '') $param.='&search_town='.urlencode($search_town); +if ($search_job != '') $param.='&search_job='.urlencode($search_job); +if ($search_phone_pro != '') $param.='&search_phone_pro='.urlencode($search_phone_pro); +if ($search_phone_perso != '') $param.='&search_phone_perso='.urlencode($search_phone_perso); +if ($search_phone_mobile != '') $param.='&search_phone_mobile='.urlencode($search_phone_mobile); +if ($search_fax != '') $param.='&search_fax='.urlencode($search_fax); +if ($search_email != '') $param.='&search_email='.urlencode($search_email); +if ($search_status != '') $param.='&search_status='.urlencode($search_status); +if ($search_priv == '0' || $search_priv == '1') $param.="&search_priv=".urlencode($search_priv); +if ($optioncss != '') $param.='&optioncss='.$optioncss; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +print ''; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit); + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); +} +if ($search_firstlast_only) +{ + print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); +} + +if (! empty($conf->categorie->enabled)) +{ + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('Categories'). ': '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_CONTACT,$search_categ,'search_categ',1); + $moreforfilter.='
    '; + if (empty($type) || $type == 'c' || $type == 'p') { - print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); - } - - if (! empty($conf->categorie->enabled)) - { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_CONTACT,$search_categ,'search_categ',1); + if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; + else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; + else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); $moreforfilter.='
    '; - if (empty($type) || $type == 'c' || $type == 'p') - { - $moreforfilter.='
    '; - if ($type == 'c') $moreforfilter.=$langs->trans('CustomersCategoriesShort'). ': '; - else if ($type == 'p') $moreforfilter.=$langs->trans('ProspectsCategoriesShort'). ': '; - else $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_CUSTOMER,$search_categ_thirdparty,'search_categ_thirdparty',1); - $moreforfilter.='
    '; - } - if (empty($type) || $type == 'f') - { - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('SuppliersCategoriesShort'). ': '; - $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); - $moreforfilter.='
    '; - } - } - if ($moreforfilter) - { - print '
    '; - print $moreforfilter; - $parameters=array('type'=>$type); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '
    '; - } - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '
    '.$langs->trans("Donation").'
    '; - print fieldLabel('Account','selectaccountid',1).''; + print fieldLabel('BankAccount','selectaccountid',1).''; $form->select_comptes($_POST["accountid"],"accountid",0,'',1); // Affiche liste des comptes courant print '
      '; + $liststatus=array('0'=>$langs->trans("Unpaid"), '1'=>$langs->trans("Paid")); + print $form->selectarray('search_status', $liststatus, $search_status, 1); + print ''; $searchpitco=$form->showFilterAndCheckAddButtons(0); diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index 8e4aabd9339..befc9d5c208 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -178,6 +178,11 @@ if ($modecompta=="CREANCES-DETTES") { report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); +if (! empty($conf->accounting->enabled)) +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + // SQL request $catotal=0; diff --git a/htdocs/compta/stats/cabyuser.php b/htdocs/compta/stats/cabyuser.php index cb8151cf33c..e5a4bc37f78 100644 --- a/htdocs/compta/stats/cabyuser.php +++ b/htdocs/compta/stats/cabyuser.php @@ -162,6 +162,11 @@ if (! empty($modecompta)) $moreparam['modecompta']=$modecompta; report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode); +if (! empty($conf->accounting->enabled)) +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + // Show array print ''; diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index 08eb5c001de..e2e092b032f 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -27,8 +27,10 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; @@ -63,6 +65,10 @@ if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accountin // Date range $year=GETPOST("year"); $month=GETPOST("month"); +$search_societe = GETPOST("search_societe"); +$search_zip = GETPOST("search_zip"); +$search_town = GETPOST("search_town"); +$search_country = GETPOST("search_country"); $date_startyear = GETPOST("date_startyear"); $date_startmonth = GETPOST("date_startmonth"); $date_startday = GETPOST("date_startday"); @@ -130,6 +136,10 @@ $headerparams['q'] = $q; $tableparams = array(); $tableparams['search_categ'] = $selected_cat; +$tableparams['search_societe'] = $search_societe; +$tableparams['search_zip'] = $search_zip; +$tableparams['search_town'] = $search_town; +$tableparams['search_country'] = $search_country; $tableparams['subcat'] = ($subcat === true)?'yes':''; // Adding common parameters @@ -178,11 +188,16 @@ if ($modecompta=="CREANCES-DETTES") report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); +if (! empty($conf->accounting->enabled)) +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + // Show Array $catotal=0; if ($modecompta == 'CREANCES-DETTES') { - $sql = "SELECT DISTINCT s.rowid as socid, s.nom as name,"; + $sql = "SELECT DISTINCT s.rowid as socid, s.nom as name, s.zip, s.town, s.fk_pays,"; $sql.= " sum(f.total) as amount, sum(f.total_ttc) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s"; if ($selected_cat === -2) // Without any category @@ -218,7 +233,7 @@ if ($modecompta == 'CREANCES-DETTES') { * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin) */ - $sql = "SELECT s.rowid as socid, s.nom as name, sum(pf.amount) as amount_ttc"; + $sql = "SELECT s.rowid as socid, s.nom as name, s.zip, s.town, s.fk_pays, sum(pf.amount) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf"; $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; @@ -248,9 +263,13 @@ if ($modecompta == 'CREANCES-DETTES') { $sql.= " AND cs.fk_categorie = c.rowid AND cs.fk_soc = s.rowid"; } } +if(!empty($search_societe)) $sql.= ' AND s.nom LIKE "%'.$search_societe.'%"'; +if(!empty($search_zip)) $sql.= ' AND s.zip LIKE "%'.$search_zip.'%"'; +if(!empty($search_town)) $sql.= ' AND s.town LIKE "%'.$search_town.'%"'; +if($search_country > 0) $sql.= ' AND s.fk_pays = '.$search_country.''; $sql.= " AND f.entity = ".$conf->entity; if ($socid) $sql.= " AND f.fk_soc = ".$socid; -$sql.= " GROUP BY s.rowid, s.nom"; +$sql.= " GROUP BY s.rowid, s.nom, s.zip, s.town, s.fk_pays"; $sql.= " ORDER BY s.rowid"; //echo $sql; @@ -264,6 +283,9 @@ if ($result) { $amount_ht[$obj->socid] = $obj->amount; $amount[$obj->socid] = $obj->amount_ttc; $name[$obj->socid] = $obj->name.' '.$obj->firstname; + $address_zip[$obj->socid] = $obj->zip; + $address_town[$obj->socid] = $obj->town; + $address_pays[$obj->socid] = getCountry($obj->fk_pays); $catotal_ht+=$obj->amount; $catotal+=$obj->amount_ttc; $i++; @@ -296,6 +318,9 @@ if ($modecompta != 'CREANCES-DETTES') { $obj = $db->fetch_object($result); $amount[$obj->rowid] += $obj->amount_ttc; $name[$obj->rowid] = $obj->name; + $address_zip[$obj->rowid] = $obj->zip; + $address_town[$obj->rowid] = $obj->town; + $address_pays[$obj->rowid] = getCountry($obj->fk_pays); $catotal+=$obj->amount_ttc; $i++; } @@ -325,7 +350,7 @@ if ($subcat) { print ' checked'; } print'>'; +print ''; print ''; print '
    '; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print $form->select_country($search_country, 'search_country'); +//print ''; +print '    
    ".$linkname."'; + print $address_zip[$key]; + print ''; + print $address_town[$key]; + print ''; + print $address_pays[$key]; + print ''; if ($modecompta != 'CREANCES-DETTES') { @@ -488,6 +597,9 @@ if (count($amount)) { // Total print '
    '.$langs->trans("Total").'   
    '; - - // Ligne des titres - print ''; - if (! empty($arrayfields['p.lastname']['checked'])) print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"p.lastname", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.firstname']['checked'])) print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"p.firstname", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.zip']['checked'])) print_liste_field_titre($langs->trans("Zip"),$_SERVER["PHP_SELF"],"p.zip", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.town']['checked'])) print_liste_field_titre($langs->trans("Town"),$_SERVER["PHP_SELF"],"p.town", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.poste']['checked'])) print_liste_field_titre($langs->trans("PostOrFunction"),$_SERVER["PHP_SELF"],"p.poste", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.phone']['checked'])) print_liste_field_titre($langs->trans("Phone"),$_SERVER["PHP_SELF"],"p.phone", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre($langs->trans("PhonePerso"),$_SERVER["PHP_SELF"],"p.phone_perso", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.phone_mobile']['checked'])) print_liste_field_titre($langs->trans("PhoneMobile"),$_SERVER["PHP_SELF"],"p.phone_mobile", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.fax']['checked'])) print_liste_field_titre($langs->trans("Fax"),$_SERVER["PHP_SELF"],"p.fax", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.email']['checked'])) print_liste_field_titre($langs->trans("EMail"),$_SERVER["PHP_SELF"],"p.email", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.skype']['checked'])) print_liste_field_titre($langs->trans("Skype"),$_SERVER["PHP_SELF"],"p.skype", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.thirdparty']['checked'])) print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom", $begin, $param, '', $sortfield,$sortorder); - if (! empty($arrayfields['p.priv']['checked'])) print_liste_field_titre($langs->trans("ContactVisibility"),$_SERVER["PHP_SELF"],"p.priv", $begin, $param, 'align="center"', $sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + if (empty($type) || $type == 'f') + { + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('SuppliersCategoriesShort'). ': '; + $moreforfilter.=$formother->select_categories(Categorie::TYPE_SUPPLIER,$search_categ_supplier,'search_categ_supplier',1); + $moreforfilter.='
    '; + } +} +if ($moreforfilter) +{ + print '
    '; + print $moreforfilter; + $parameters=array('type'=>$type); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($langs->trans("DateCreationShort"),$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($langs->trans("DateModificationShort"),$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.statut']['checked'])) print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"p.statut","",$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); - print "
    \n"; + print ''; +} - // Lines for filter fields - print ''; +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print '
    '; + +// Ligne des titres +print ''; +if (! empty($arrayfields['p.lastname']['checked'])) print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"p.lastname", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.firstname']['checked'])) print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"p.firstname", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.zip']['checked'])) print_liste_field_titre($langs->trans("Zip"),$_SERVER["PHP_SELF"],"p.zip", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.town']['checked'])) print_liste_field_titre($langs->trans("Town"),$_SERVER["PHP_SELF"],"p.town", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.poste']['checked'])) print_liste_field_titre($langs->trans("PostOrFunction"),$_SERVER["PHP_SELF"],"p.poste", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.phone']['checked'])) print_liste_field_titre($langs->trans("Phone"),$_SERVER["PHP_SELF"],"p.phone", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre($langs->trans("PhonePerso"),$_SERVER["PHP_SELF"],"p.phone_perso", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.phone_mobile']['checked'])) print_liste_field_titre($langs->trans("PhoneMobile"),$_SERVER["PHP_SELF"],"p.phone_mobile", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.fax']['checked'])) print_liste_field_titre($langs->trans("Fax"),$_SERVER["PHP_SELF"],"p.fax", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.email']['checked'])) print_liste_field_titre($langs->trans("EMail"),$_SERVER["PHP_SELF"],"p.email", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.skype']['checked'])) print_liste_field_titre($langs->trans("Skype"),$_SERVER["PHP_SELF"],"p.skype", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.thirdparty']['checked'])) print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.priv']['checked'])) print_liste_field_titre($langs->trans("ContactVisibility"),$_SERVER["PHP_SELF"],"p.priv", $begin, $param, 'align="center"', $sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($langs->trans("DateCreationShort"),$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($langs->trans("DateModificationShort"),$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['p.statut']['checked'])) print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"p.statut","",$param,'align="center"',$sortfield,$sortorder); +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); +print "\n"; + +// Lines for filter fields +print ''; +if (! empty($arrayfields['p.lastname']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.firstname']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.poste']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.zip']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.town']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.phone']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.phone_perso']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.phone_mobile']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.fax']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.email']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.skype']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.thirdparty']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.priv']['checked'])) +{ + print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Date creation +if (! empty($arrayfields['p.datec']['checked'])) +{ + print ''; +} +// Date modification +if (! empty($arrayfields['p.tms']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.statut']['checked'])) +{ + print ''; +} +print ''; + +print ''; + +$var=True; +$i = 0; +while ($i < min($num,$limit)) +{ + $obj = $db->fetch_object($result); + + $var=!$var; + print ""; + + $contactstatic->lastname=$obj->lastname; + $contactstatic->firstname=''; + $contactstatic->id=$obj->cidp; + $contactstatic->statut=$obj->statut; + $contactstatic->poste=$obj->poste; + $contactstatic->phone_pro=$obj->phone_pro; + $contactstatic->phone_perso=$obj->phone_perso; + $contactstatic->phone_mobile=$obj->phone_mobile; + $contactstatic->zip=$obj->zip; + $contactstatic->town=$obj->town; + + // Name if (! empty($arrayfields['p.lastname']['checked'])) { - print ''; + print ''; } + // Firstname if (! empty($arrayfields['p.firstname']['checked'])) { - print ''; - } - if (! empty($arrayfields['p.poste']['checked'])) - { - print ''; + print ''; } + // Zip if (! empty($arrayfields['p.zip']['checked'])) { - print ''; + print ''; } + // Town if (! empty($arrayfields['p.town']['checked'])) { - print ''; + print ''; } - if (! empty($arrayfields['p.phone']['checked'])) + // Function + if (! empty($arrayfields['p.poste']['checked'])) { - print ''; + print ''; } - if (! empty($arrayfields['p.phone_perso']['checked'])) + // Phone + if (! empty($arrayfields['p.phone']['checked'])) { - print ''; + print ''; } + // Phone perso + if (! empty($arrayfields['p.phone_perso']['checked'])) + { + print ''; + } + // Phone mobile if (! empty($arrayfields['p.phone_mobile']['checked'])) { - print ''; + print ''; } + // Fax if (! empty($arrayfields['p.fax']['checked'])) { - print ''; + print ''; } + // EMail if (! empty($arrayfields['p.email']['checked'])) { - print ''; + print ''; } + // Skype if (! empty($arrayfields['p.skype']['checked'])) { - print ''; + if (! empty($conf->skype->enabled)) { print ''; } } + // Company if (! empty($arrayfields['p.thirdparty']['checked'])) { - print ''; } + + // Private/Public if (! empty($arrayfields['p.priv']['checked'])) { - print ''; + print ''; } + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { @@ -586,204 +749,58 @@ if ($result) { if (! empty($arrayfields["ef.".$key]['checked'])) { - print ''; } } } // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation if (! empty($arrayfields['p.datec']['checked'])) { - print ''; } // Date modification if (! empty($arrayfields['p.tms']['checked'])) { - print ''; } + // Status if (! empty($arrayfields['p.statut']['checked'])) { - print ''; + print ''; } - print ''; - - print ''; + // Action column - Links Add action and Export vcard + print ''; - $var=True; - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($result); - - $var=!$var; - print ""; - - $contactstatic->lastname=$obj->lastname; - $contactstatic->firstname=''; - $contactstatic->id=$obj->cidp; - $contactstatic->statut=$obj->statut; - $contactstatic->poste=$obj->poste; - $contactstatic->phone_pro=$obj->phone_pro; - $contactstatic->phone_perso=$obj->phone_perso; - $contactstatic->phone_mobile=$obj->phone_mobile; - $contactstatic->zip=$obj->zip; - $contactstatic->town=$obj->town; - - // Name - if (! empty($arrayfields['p.lastname']['checked'])) - { - print ''; - } - // Firstname - if (! empty($arrayfields['p.firstname']['checked'])) - { - print ''; - } - // Zip - if (! empty($arrayfields['p.zip']['checked'])) - { - print ''; - } - // Town - if (! empty($arrayfields['p.town']['checked'])) - { - print ''; - } - // Function - if (! empty($arrayfields['p.poste']['checked'])) - { - print ''; - } - // Phone - if (! empty($arrayfields['p.phone']['checked'])) - { - print ''; - } - // Phone perso - if (! empty($arrayfields['p.phone_perso']['checked'])) - { - print ''; - } - // Phone mobile - if (! empty($arrayfields['p.phone_mobile']['checked'])) - { - print ''; - } - // Fax - if (! empty($arrayfields['p.fax']['checked'])) - { - print ''; - } - // EMail - if (! empty($arrayfields['p.email']['checked'])) - { - print ''; - } - // Skype - if (! empty($arrayfields['p.skype']['checked'])) - { - if (! empty($conf->skype->enabled)) { print ''; } - } - // Company - if (! empty($arrayfields['p.thirdparty']['checked'])) - { - print ''; - } - - // Private/Public - if (! empty($arrayfields['p.priv']['checked'])) - { - print ''; - } - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - } - // Status - if (! empty($arrayfields['p.statut']['checked'])) - { - print ''; - } - // Action column - Links Add action and Export vcard - print ''; - - print "\n"; - $i++; - } - - print "
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $selectarray=array('0'=>$langs->trans("ContactPublic"),'1'=>$langs->trans("ContactPrivate")); + print $form->selectarray('search_priv',$selectarray,$search_priv,1); + print ''; + print ''; + print ''; + print ''; + print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); + print ''; +print ''; +print ''; +print '
    '; - print ''; - print ''; + print $contactstatic->getNomUrl(1,'',0); + print ''; - print ''; - print ''; - print ''; - print ''.$obj->firstname.''; - print ''; - print ''.$obj->zip.''; - print ''; - print ''.$obj->town.''; - print ''; - print ''.dol_trunc($obj->poste,20).''; - print ''; - print ''.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''; - print ''; - print ''.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''; - print ''; - print ''.dol_print_phone($obj->fax,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''; - print ''; - print ''.dol_print_email($obj->email,$obj->cidp,$obj->socid,'AC_EMAIL',18).''; - print ''; - print ''.dol_print_skype($obj->skype,$obj->cidp,$obj->socid,'AC_SKYPE',18).''; - print ''; + print ''; + if ($obj->socid) + { + $objsoc = new Societe($db); + $objsoc->fetch($obj->socid); + print $objsoc->getNomUrl(1); + } + else + print ' '; print ''; - $selectarray=array('0'=>$langs->trans("ContactPublic"),'1'=>$langs->trans("ContactPrivate")); - print $form->selectarray('search_priv',$selectarray,$search_priv,1); - print ''.$contactstatic->LibPubPriv($obj->priv).''; + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); print ''; + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour'); print ''; - print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); - print ''.$contactstatic->getLibStatut(3).''; - print ''; - print ''; - print '
    '; + print ''.img_object($langs->trans("AddAction"),"action").''; + print '   '; + print ''; + print img_picto($langs->trans("VCard"),'vcard.png').' '; + print '
    '; - print $contactstatic->getNomUrl(1,'',0); - print ''.$obj->firstname.''.$obj->zip.''.$obj->town.''.dol_trunc($obj->poste,20).''.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->fax,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_email($obj->email,$obj->cidp,$obj->socid,'AC_EMAIL',18).''.dol_print_skype($obj->skype,$obj->cidp,$obj->socid,'AC_SKYPE',18).''; - if ($obj->socid) - { - print ''; - print img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,20).''; - } - else - { - print ' '; - } - print ''.$contactstatic->LibPubPriv($obj->priv).''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$contactstatic->getLibStatut(3).''; - print ''.img_object($langs->trans("AddAction"),"action").''; - print '   '; - print ''; - print img_picto($langs->trans("VCard"),'vcard.png').' '; - print '
    "; - - if ($num > $limit || $page) print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit, 1); - - print ''; - - $db->free($result); -} -else -{ - dol_print_error($db); + print "
    "; + +if ($num > $limit || $page) print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit, 1); + +print ''; + +$db->free($result); llxFooter(); diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index 761efcfa840..17c718cfb42 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -83,6 +83,10 @@ if ($id > 0) $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', ''); + $cssclass='titlefield'; + //if ($action == 'editnote_public') $cssclass='titlefieldcreate'; + //if ($action == 'editnote_private') $cssclass='titlefieldcreate'; + print '
    '; print '
    '; @@ -98,19 +102,19 @@ if ($id > 0) $objsoc = new Societe($db); $objsoc->fetch($object->socid); - print ''.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).''; + print ''.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).''; } else { - print ''.$langs->trans("ThirdParty").''; + print ''.$langs->trans("ThirdParty").''; print $langs->trans("ContactNotLinkedToCompany"); print ''; } } // Civility - print ''.$langs->trans("UserTitle").''; + print ''.$langs->trans("UserTitle").''; print $object->getCivilityLabel(); print ''; @@ -120,7 +124,7 @@ if ($id > 0) { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - print ''.$langs->trans("DateToBirth").''.dol_print_date($object->birthday,"day"); + print ''.$langs->trans("DateToBirth").''.dol_print_date($object->birthday,"day"); print '   '; //var_dump($birthdatearray); @@ -138,17 +142,16 @@ if ($id > 0) } else { - print ''.$langs->trans("DateToBirth").''.$langs->trans("Unknown").""; + print ''.$langs->trans("DateToBirth").''.$langs->trans("Unknown").""; } print ""; print ""; - print '
    '; + //print '
    '; - print '
    '; + //print '
    '; - $cssclass='titlefield'; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 8ed96d2ffab..22d60bb7a72 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -214,7 +214,7 @@ if (empty($reshook)) if ($socid<1) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors'); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); $action='create'; $error++; } @@ -655,8 +655,8 @@ if (empty($reshook)) $objectline->qty=GETPOST('elqty'); $objectline->remise_percent=GETPOST('elremise_percent'); $objectline->tva_tx=GETPOST('eltva_tx')?GETPOST('eltva_tx'):0; // Field may be disabled, so we use vat rate 0 - $objectline->localtax1_tx=$localtax1_tx; - $objectline->localtax2_tx=$localtax2_tx; + $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; @@ -796,7 +796,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_supplier',GETPOST('ref_supplier','alpha')); + $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'; @@ -821,7 +821,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref_customer',GETPOST('ref_customer','alpha')); + $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'; @@ -845,7 +845,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - $result = $object->setValueFrom('ref',GETPOST('ref','alpha')); + $result = $object->setValueFrom('ref', GETPOST('ref','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editref'; @@ -869,7 +869,7 @@ if (empty($reshook)) 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'); + $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'editdate_contrat'; @@ -967,6 +967,28 @@ if (empty($reshook)) } } } + + // Action clone object + if ($action == 'confirm_clone' && $confirm == 'yes') + { + if (! GETPOST('socid', 3)) + { + setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); + } + else + { + if ($object->id > 0) { + $result = $object->createFromClone($socid); + if ($result > 0) { + header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result); + exit(); + } else { + if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors'); + $action = ''; + } + } + } + } } /* @@ -1265,6 +1287,12 @@ else 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); + } + print ''; $linkback = ''.$langs->trans("BackToList").''; @@ -1427,7 +1455,7 @@ else { $total = 0; - print ''; + print ''; print ''; print ''; print ''; @@ -1542,7 +1570,11 @@ else { print dol_print_date($db->jdate($objp->date_debut)); // 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)) { print " ".img_warning($langs->trans("Late")); } + 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 '  -  '; @@ -1550,7 +1582,11 @@ else if ($objp->date_fin) { print dol_print_date($db->jdate($objp->date_fin)); - if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { print " ".img_warning($langs->trans("Late")); } + 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"); @@ -1956,6 +1992,11 @@ else if ($user->rights->facture->creer) print ''; else print ''; } + + // Clone + if ($user->rights->contrat->creer) { + print ''; + } if ($object->nbofservicesclosed < $nbofservices) { @@ -1997,7 +2038,7 @@ else $var = true; - $somethingshown = $formfile->show_documents('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 diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index ba2c60fc013..6b0dc8d7fdb 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -56,7 +56,7 @@ class Contrat extends CommonObject * @var string */ var $ref_customer; - + /** * Supplier reference of the contract * @var string @@ -354,7 +354,7 @@ class Contrat extends CommonObject * * @param User $user Objet User * @param string $force_number Reference to force on contract (not implemented yet) - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @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) @@ -536,7 +536,7 @@ class Contrat extends CommonObject return -1; } } - + /** * Load a contract from database * @@ -904,6 +904,7 @@ class Contrat extends CommonObject } if (! $paramsok) return -1; + $this->db->begin(); $now=dol_now(); @@ -968,7 +969,7 @@ class Contrat extends CommonObject } } } - + // Insert contacts commerciaux ('SALESREPSIGN','contrat') if (! $error) { @@ -995,8 +996,8 @@ class Contrat extends CommonObject { dol_print_error($this->db); $error++; - } - + } + if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) { $originforcontact = $origin; @@ -1017,10 +1018,10 @@ class Contrat extends CommonObject } } } - + $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$originforcontact."'"; - + $resqlcontact = $this->db->query($sqlcontact); if ($resqlcontact) { @@ -1033,11 +1034,11 @@ class Contrat extends CommonObject } } else dol_print_error($resqlcontact); - } + } } } } - + if (! $error) { // Call trigger @@ -1231,7 +1232,6 @@ class Contrat extends CommonObject $error=0; // Clean parameters - if (isset($this->ref)) $this->ref=trim($this->ref); if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer); if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier); @@ -1249,14 +1249,11 @@ class Contrat extends CommonObject if (isset($this->import_key)) $this->import_key=trim($this->import_key); //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams); - - // Check parameters // Put here code to add a control on parameters values // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET"; - + $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET"; $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").","; $sql.= " ref_customer=".(isset($this->ref_customer)?"'".$this->db->escape($this->ref_customer)."'":"null").","; $sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").","; @@ -1277,8 +1274,6 @@ class Contrat extends CommonObject $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null").""; //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null").""; - - $sql.= " WHERE rowid=".$this->id; $this->db->begin(); @@ -1352,19 +1347,20 @@ class Contrat extends CommonObject $this->db->begin(); // Clean parameters - $remise_percent=price2num($remise_percent); - $qty=price2num($qty); - if (! $qty) $qty=1; - if (! $info_bits) $info_bits=0; - if (! $pu_ht) $pu_ht=0; - if (! $pu_ttc) $pu_ttc=0; - $pu_ht=price2num($pu_ht); $pu_ttc=price2num($pu_ttc); $pa_ht=price2num($pa_ht); $txtva=price2num($txtva); $txlocaltax1=price2num($txlocaltax1); $txlocaltax2=price2num($txlocaltax2); + $remise_percent=price2num($remise_percent); + $qty=price2num($qty); + if (empty($qty)) $qty=1; + if (empty($info_bits)) $info_bits=0; + if (empty($pu_ht) || ! is_numeric($pu_ht)) $pu_ht=0; + if (empty($pu_ttc)) $pu_ttc=0; + if (empty($txlocaltax1) || ! is_numeric($txlocaltax1)) $txlocaltax1=0; + if (empty($txlocaltax2) || ! is_numeric($txlocaltax2)) $txlocaltax2=0; if ($price_base_type=='HT') { @@ -1385,7 +1381,7 @@ class Contrat extends CommonObject $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->societe, $mysoc); $txtva = preg_replace('/\s*\(.*\)/','',$txtva); // Remove code into vatrate. - + $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1,$mysoc, $localtaxes_type); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; @@ -1408,9 +1404,9 @@ class Contrat extends CommonObject if (empty($pa_ht)) $pa_ht=0; - + // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) + if ($this->pa_ht == 0) { if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) { @@ -1432,15 +1428,17 @@ class Contrat extends CommonObject if ($date_start > 0) { $sql.= ",date_ouverture_prevue"; } if ($date_end > 0) { $sql.= ",date_fin_validite"; } $sql.= ", fk_unit"; - $sql.= ") VALUES ($this->id, '', '" . $this->db->escape($desc) . "',"; + $sql.= ") VALUES ("; + $sql.= $this->id.", '', '" . $this->db->escape($desc) . "',"; $sql.= ($fk_product>0 ? $fk_product : "null").","; - $sql.= " '".$qty."',"; - $sql.= " '".$txtva."',"; - $sql.= " '".$txlocaltax1."',"; - $sql.= " '".$txlocaltax2."',"; + $sql.= " ".$qty.","; + $sql.= " ".$txtva.","; + $sql.= " ".$txlocaltax1.","; + $sql.= " ".$txlocaltax2.","; $sql.= " '".$localtax1_type."',"; $sql.= " '".$localtax2_type."',"; - $sql.= " ".price2num($remise_percent).",".price2num($pu_ht).","; + $sql.= " ".price2num($remise_percent).","; + $sql.= " ".price2num($pu_ht).","; $sql.= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).","; $sql.= " '".$info_bits."',"; $sql.= " ".price2num($price).",".price2num($remise).","; @@ -1567,7 +1565,7 @@ class Contrat extends CommonObject $localtaxes_type=getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc); $tvatx = preg_replace('/\s*\(.*\)/','',$tvatx); // Remove code into vatrate. - + $tabprice=calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type); $total_ht = $tabprice[0]; $total_tva = $tabprice[1]; @@ -1591,7 +1589,7 @@ class Contrat extends CommonObject if (empty($pa_ht)) $pa_ht=0; // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) + if ($this->pa_ht == 0) { if (($result = $this->defineBuyPrice($pu_ht, $remise_percent)) < 0) { @@ -2265,6 +2263,120 @@ class Contrat extends CommonObject return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables); } + + /** + * Load an object from its id and create a new one in database + * + * @param int $socid Id of thirdparty + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @return int New id of clone + */ + function createFromClone($socid = 0, $notrigger=0) { + global $db, $user, $langs, $conf, $hookmanager; + + dol_include_once('/projet/class/project.class.php'); + + $this->context['createfromclone'] = 'createfromclone'; + + $error = 0; + $now = dol_now(); + + $this->fetch($this->id); + // Load dest object + $clonedObj = clone $this; + + $this->db->begin(); + + $objsoc = new Societe($this->db); + + $objsoc->fetch($clonedObj->socid); + + // $clonedObj->id=0; + $clonedObj->statut = 0; + + if (empty($conf->global->CONTRACT_ADDON) || ! is_readable(DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . ".php")) { + $this->error = 'ErrorSetupNotComplete'; + dol_syslog($this->error); + return - 1; + } + + // Set ref + require_once DOL_DOCUMENT_ROOT . "/core/modules/contract/" . $conf->global->CONTRACT_ADDON . '.php'; + $obj = $conf->global->CONTRACT_ADDON; + $modContract = new $obj(); + $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj); + + // get extrafields so they will be clone + foreach ( $this->lines as $line ) { + $line->fetch_optionals($line->rowid); + } + + // Create clone + $result = $clonedObj->create($user); + if ($result < 0) { + $error ++; + $this->error = $clonedObj->error; + $this->errors[] = $clonedObj->error; + } else { + // copy internal contacts + if ($clonedObj->copy_linked_contact($this, 'internal') < 0) + $error ++; + + // copy external contacts if same company + elseif ($this->socid == $clonedObj->socid) { + if ($clonedObj->copy_linked_contact($this, 'external') < 0) + $error ++; + } + } + + if (! $error) { + foreach ( $this->lines as $line ) { + $result = $clonedObj->addline($line->desc, $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_ouverture, $line->date_cloture, 'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit); + if ($result < 0) { + $error ++; + $this->error = $clonedObj->error; + $this->errors[] = $clonedObj->error; + } + } + } + + if (! $error) { + // Hook of thirdparty module + if (is_object($hookmanager)) { + $parameters = array ( + 'objFrom' => $this, + 'clonedObj' => $clonedObj + ); + $action = ''; + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) + $error ++; + } + + } + + if (! $notrigger && empty($error)) + { + // Call trigger + $clonedObj->old_copy=$this; + $result = $clonedObj->call_trigger('CONTRACT_CLONE', $user); + if ($result < 0) { + $error ++; + } + // End call triggers + } + + unset($this->context['createfromclone']); + + // End + if (! $error) { + $this->db->commit(); + return $clonedObj->id; + } else { + $this->db->rollback(); + return - 1; + } + } } @@ -2275,7 +2387,7 @@ class ContratLigne extends CommonObjectLine { public $element='contratdet'; public $table_element='contratdet'; - + var $id; var $ref; var $tms; @@ -2293,10 +2405,10 @@ class ContratLigne extends CommonObjectLine public $libelle; var $description; - + var $product_ref; var $product_label; - + var $date_commande; var $date_ouverture_prevue; // date start planned var $date_ouverture; // date start real @@ -2437,7 +2549,7 @@ class ContratLigne extends CommonObjectLine $result=''; $label=$langs->trans("ShowContractOfService").': '.$this->label; if (empty($label)) $label=$this->description; - + $link = ''; $linkend=''; @@ -2633,7 +2745,7 @@ class ContratLigne extends CommonObjectLine if (empty($this->pa_ht)) $this->pa_ht=0; // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) + if ($this->pa_ht == 0) { if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index 024cf561fb5..ef7e73ad4c8 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -124,6 +124,7 @@ if ($object->id) $modulepart = 'contract'; $permission = $user->rights->contrat->creer; + $permtoedit = $user->rights->contrat->creer; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 72c852b10fc..c003b638748 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -6,6 +6,7 @@ * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Claudio Aschieri * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2016 Ferran Marcet * * 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 @@ -307,12 +308,13 @@ if ($resql) $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($search_contract) $param.='&search_contract='.$search_contract; - if ($search_name) $param.='&search_name='.$search_name; - if ($search_ref_supplier) $param.='&search_ref_supplier='.$search_ref_supplier; - if ($search_sale) $param.='&search_sale=' .$search_sale; - if ($show_files) $param.='&show_files=' .$show_files; - if ($optioncss != '') $param.='&optioncss='.$optioncss; + if ($sall != '') $param.='&sall='.$sall; + if ($search_contract != '') $param.='&search_contract='.$search_contract; + if ($search_name != '') $param.='&search_name='.$search_name; + if ($search_ref_supplier != '') $param.='&search_ref_supplier='.$search_ref_supplier; + if ($search_sale != '') $param.='&search_sale=' .$search_sale; + if ($show_files) $param.='&show_files=' .$show_files; + if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) { @@ -330,9 +332,6 @@ if ($resql) if ($massaction == 'presend') $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - - - print '
    '; if ($optioncss != '') print ''; print ''; diff --git a/htdocs/contrat/services.php b/htdocs/contrat/services.php index d2de41391de..8e37e392603 100644 --- a/htdocs/contrat/services.php +++ b/htdocs/contrat/services.php @@ -361,7 +361,12 @@ if ($resql) if (($mode == "" || $mode == -1) || $mode < 5) { print '
    '; - $formconfirm.= ''; + $formconfirm.= ''; $formconfirm.= ''."\n"; $formconfirm.= '
    '.$langs->trans("ServiceNb",$cursorline).''.$langs->trans("VAT").''.$langs->trans("PriceUHT").''.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); - if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) print img_warning($langs->trans("Late")); + if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) + { + $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 '    '; } if (($mode == "" || $mode == -1) || $mode >= 5) print ''.dol_print_date($db->jdate($obj->date_cloture)); diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index 2e5d7d71252..5984283b996 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -24,10 +24,10 @@ // $action must be defined // $id must be defined -// $object must be defined and must have a method generateDocument. +// $object must be defined and must have a method generateDocument(). // $permissioncreate must be defined // $upload_dir must be defined (example $conf->projet->dir_output . "/";) -// $hidedetails, $hidedesc and $hideref may have been set or not. +// $hidedetails, $hidedesc, $hideref and $moreparams may have been set or not. // Build doc @@ -49,7 +49,10 @@ if ($action == 'builddoc' && $permissioncreate) }*/ // Save last template used to generate document - if (GETPOST('model')) $object->setDocModel($user, GETPOST('model','alpha')); + if (GETPOST('model')) + { + $object->setDocModel($user, GETPOST('model','alpha')); + } // Special case to force bank account //if (property_exists($object, 'fk_bank')) @@ -63,6 +66,7 @@ if ($action == 'builddoc' && $permissioncreate) $outputlangs = $langs; $newlang=''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id'); if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) $newlang=$object->thirdparty->default_lang; // for proposal, order, invoice, ... if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) $newlang=$object->default_lang; // for thirdparty @@ -76,13 +80,18 @@ if ($action == 'builddoc' && $permissioncreate) if (empty($hidedetails)) $hidedetails=0; if (empty($hidedesc)) $hidedesc=0; if (empty($hideref)) $hideref=0; + if (empty($moreparams)) $moreparams=null; - $result= $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result= $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $action=''; } + else + { + setEventMessages($langs->trans("FileGenerated"), null); + } } } diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index 6a162123ce0..afcf929589b 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -313,6 +313,7 @@ if ($action == 'update') $params['options'][$key] = $value; } } + $result=$extrafields->update( GETPOST('attrname'), GETPOST('label'), diff --git a/htdocs/core/actions_linkedfiles.inc.php b/htdocs/core/actions_linkedfiles.inc.php index 8977938eb4a..672da011a79 100644 --- a/htdocs/core/actions_linkedfiles.inc.php +++ b/htdocs/core/actions_linkedfiles.inc.php @@ -40,7 +40,7 @@ elseif (GETPOST('linkit') && ! empty($conf->global->MAIN_UPLOAD_DOC)) $link = GETPOST('link', 'alpha'); if ($link) { - if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://') { + if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://') { $link = 'http://' . $link; } dol_add_file_process($upload_dir, 0, 1, 'userfile', null, $link); @@ -124,7 +124,7 @@ elseif ($action == 'confirm_updateline' && GETPOST('save') && GETPOST('link', 'a if ($f) { $link->url = GETPOST('link', 'alpha'); - if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://') + if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') { $link->url = 'http://' . $link->url; } @@ -140,4 +140,33 @@ elseif ($action == 'confirm_updateline' && GETPOST('save') && GETPOST('link', 'a //error fetching } } - +elseif ($action == 'renamefile' && GETPOST('renamefilesave')) +{ + if ($object->id) + { + // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. + //var_dump($upload_dir);exit; + if (! empty($upload_dir)) + { + $filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom')); + $filenameto=dol_sanitizeFileName(GETPOST('renamefileto')); + if ($filenamefrom && $filenameto) + { + $srcpath = $upload_dir.'/'.$filenamefrom; + $destpath = $upload_dir.'/'.$filenameto; + + $result = dol_move($srcpath, $destpath); + if ($result) + { + $object->addThumbs($destpath); + + // TODO Add revert function of addThumbs + //$object->delThumbs($srcpath); + + setEventMessages($langs->trans("FileRenamed"), null); + } + else setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors'); + } + } + } +} diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 085f98b0218..42a73f0bbde 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -49,7 +49,10 @@ if (! $error && count($toselect) > $maxformassaction) $error++; } - +if (! $error && $massaction == 'confirm_presend' && GETPOST('modelselected')) // If we change the template, we must not send email, but keep on send email form +{ + $massaction='presend'; +} if (! $error && $massaction == 'confirm_presend') { $resaction = ''; diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index a5e6a29b50a..9ec3bfcb3b7 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -21,11 +21,13 @@ * \brief Code for actions on sending mails from object page */ - +// $mysoc must be defined // $id must be defined // $actiontypecode must be defined // $paramname must be defined // $mode must be defined +// $object and $uobject may be defined. + /* * Add file in email form @@ -86,11 +88,11 @@ if (GETPOST('removAll')) { $pathtodelete = $value; $filetodelete = $listofnames[$key]; - $result = dol_delete_file($pathtodelete,1); // Delete uploded Files - + $result = dol_delete_file($pathtodelete,1); // Delete uploded Files + $langs->load("other"); setEventMessages($langs->trans("FileWasRemoved",$filetodelete), null, 'mesgs'); - + $formmail->remove_attached_files($key); // Update Session } } @@ -101,57 +103,60 @@ if (GETPOST('removAll')) if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_POST['removAll'] && ! $_POST['removedfile'] && ! $_POST['cancel'] && !$_POST['modelselected']) { $trackid = GETPOST('trackid','aZ09'); - + $subject='';$actionmsg='';$actionmsg2=''; + if (! empty($conf->dolimail->enabled)) $langs->load("dolimail@dolimail"); $langs->load('mails'); - $subject='';$actionmsg='';$actionmsg2=''; - - $result=$object->fetch($id); - - $sendtosocid=0; - if (method_exists($object,"fetch_thirdparty") && $object->element != 'societe') + if (is_object($object)) { - $result=$object->fetch_thirdparty(); - $thirdparty=$object->thirdparty; - $sendtosocid=$thirdparty->id; + $result=$object->fetch($id); + + $sendtosocid=0; + if (method_exists($object,"fetch_thirdparty") && $object->element != 'societe') + { + $result=$object->fetch_thirdparty(); + $thirdparty=$object->thirdparty; + $sendtosocid=$thirdparty->id; + } + else if ($object->element == 'societe') + { + $thirdparty=$object; + if ($thirdparty->id > 0) $sendtosocid=$thirdparty->id; + elseif($conf->dolimail->enabled) + { + $dolimail = new Dolimail($db); + $possibleaccounts=$dolimail->get_societe_by_email($_POST['sendto'],"1"); + $possibleuser=$dolimail->get_from_user_by_mail($_POST['sendto'],"1"); // suche in llx_societe and socpeople + if (!$possibleaccounts && !$possibleuser) + { + setEventMessages($langs->trans('ErrorFailedToFindSocieteRecord',$_POST['sendto']), null, 'errors'); + } + elseif (count($possibleaccounts)>1) + { + $sendtosocid=$possibleaccounts[1]['id']; + $result=$object->fetch($sendtosocid); + + setEventMessages($langs->trans('ErrorFoundMoreThanOneRecordWithEmail',$_POST['sendto'],$object->name), null, 'mesgs'); + } + else + { + if($possibleaccounts){ + $sendtosocid=$possibleaccounts[1]['id']; + $result=$object->fetch($sendtosocid); + }elseif($possibleuser){ + $sendtosocid=$possibleuser[0]['id']; + + $result=$uobject->fetch($sendtosocid); + $object=$uobject; + } + + } + } + } + else dol_print_error('','Use actions_sendmails.in.php for a type that is not supported'); } - else if ($object->element == 'societe') - { - $thirdparty=$object; - if ($thirdparty->id > 0) $sendtosocid=$thirdparty->id; - elseif($conf->dolimail->enabled) - { - $dolimail = new Dolimail($db); - $possibleaccounts=$dolimail->get_societe_by_email($_POST['sendto'],"1"); - $possibleuser=$dolimail->get_from_user_by_mail($_POST['sendto'],"1"); // suche in llx_societe and socpeople - if (!$possibleaccounts && !$possibleuser) - { - setEventMessages($langs->trans('ErrorFailedToFindSocieteRecord',$_POST['sendto']), null, 'errors'); - } - elseif (count($possibleaccounts)>1) - { - $sendtosocid=$possibleaccounts[1]['id']; - $result=$object->fetch($sendtosocid); - - setEventMessages($langs->trans('ErrorFoundMoreThanOneRecordWithEmail',$_POST['sendto'],$object->name), null, 'mesgs'); - } - else - { - if($possibleaccounts){ - $sendtosocid=$possibleaccounts[1]['id']; - $result=$object->fetch($sendtosocid); - }elseif($possibleuser){ - $sendtosocid=$possibleuser[0]['id']; - - $result=$uobject->fetch($sendtosocid); - $object=$uobject; - } - - } - } - } - else dol_print_error('','Use actions_sendmails.in.php for a type that is not supported'); + else $thirdparty = $mysoc; if ($result > 0) { @@ -166,7 +171,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // Recipient was provided from combo list if ($_POST['receiver'] == 'thirdparty') // Id of third party { - $sendto = $thirdparty->email; + $sendto = $thirdparty->name.' <'.$thirdparty->email.'>'; $sendtoid = 0; } else // Id du contact @@ -184,7 +189,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // Recipient was provided from combo list if ($_POST['receivercc'] == 'thirdparty') // Id of third party { - $sendtocc = $thirdparty->email; + $sendtocc = $thirdparty->name.' <'.$thirdparty->email.'>'; } else // Id du contact { @@ -194,10 +199,30 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if (dol_strlen($sendto)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; + $langs->load("commercial"); - $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; - $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; + $fromtype = GETPOST('fromtype'); + if ($fromtype === 'user') { + $from = $user->getFullName($langs) .' <'.$user->email.'>'; + } + elseif ($fromtype === 'company') { + $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + } + elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $user->email_aliases); + $from = trim($tmp[($reg[1] - 1)]); + } + elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { + $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + $from = trim($tmp[($reg[1] - 1)]); + } + else { + $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; + } + + $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; $message = $_POST['message']; $sendtobcc= GETPOST('sendtoccc'); if ($mode == 'emailfromproposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); @@ -212,11 +237,12 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if ($action == 'send' || $action == 'relance') { if (dol_strlen($_POST['subject'])) $subject = $_POST['subject']; - $actionmsg2=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; + $actionmsg2=$langs->transnoentities('MailSentBy').' '.CMailFile::getValidAddress($from,4,0,1).' '.$langs->transnoentities('To').' '.CMailFile::getValidAddress($sendto,4,0,1); if ($message) { - $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg=$langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from); + $actionmsg=dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto)); + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . dol_escape_htmltag($sendtocc)); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); $actionmsg = dol_concatdesc($actionmsg, $message); @@ -247,37 +273,36 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $mailboxconfig = new IMAP($db); $mailboxconfig->fetch($mbid); if ($mailboxconfig->mailbox_imap_host) $ref=$mailboxconfig->get_ref(); - + $mailboxconfig->folder_id=$mailboxconfig->mailbox_imap_outbox; $mailboxconfig->userfolder_fetch(); - + if ($mailboxconfig->mailbox_save_sent_mails == 1) { - + $folder=str_replace($ref, '', $mailboxconfig->folder_cache_key); if (!$folder) $folder = "Sent"; // Default Sent folder - + $mailboxconfig->mbox = imap_open($mailboxconfig->get_connector_url().$folder, $mailboxconfig->mailbox_imap_login, $mailboxconfig->mailbox_imap_password); - if (FALSE === $mailboxconfig->mbox) + if (FALSE === $mailboxconfig->mbox) { $info = FALSE; $err = $langs->trans('Error3_Imap_Connection_Error'); setEventMessages($err,$mailboxconfig->element, null, 'errors'); - } - else + } + else { $mailboxconfig->mailboxid=$_POST['frommail']; $mailboxconfig->foldername=$folder; $from = $mailfromid[0] . $mailfromid[2]; $imap=1; } - - } + + } } } - + // Send mail - require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid); if ($mailfile->error) { @@ -290,7 +315,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if ($result) { $error=0; - + // FIXME This must be moved into a trigger for action $trigger_name if (! empty($conf->dolimail->enabled)) { @@ -301,13 +326,13 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $dolimail=new DoliMail($db); $dolimail->id = $mid; $res=$dolimail->set_prop($user, 'answered',1); - } + } if ($imap==1) { // write mail to IMAP Server - $movemail = $mailboxconfig->putMail($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$folder,$deliveryreceipt,$mailfile); + $movemail = $mailboxconfig->putMail($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$folder,$deliveryreceipt,$mailfile); if ($movemail) setEventMessages($langs->trans("MailMovedToImapFolder",$folder), null, 'mesgs'); - else setEventMessages($langs->trans("MailMovedToImapFolder_Warning",$folder), null, 'warnings'); + else setEventMessages($langs->trans("MailMovedToImapFolder_Warning",$folder), null, 'warnings'); } } @@ -317,6 +342,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $object->actiontypecode = $actiontypecode; $object->actionmsg = $actionmsg; // Long text $object->actionmsg2 = $actionmsg2; // Short text + $object->trackid = $trackid; $object->fk_element = $object->id; $object->elementtype = $object->element; @@ -325,7 +351,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $interface=new Interfaces($db); $result=$interface->run_triggers($trigger_name,$object,$user,$langs,$conf); if ($result < 0) { - $error++; $this->errors=$interface->errors; + $error++; $errors=$interface->errors; } // End call of triggers @@ -339,8 +365,8 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // This avoid sending mail twice if going out and then back to page $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)); setEventMessages($mesg, null, 'mesgs'); - if($conf->dolimail->enabled) header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.$object->id.'&'.($paramname2?$paramname2:'mid').'='.$parm2val); - else header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.$object->id); + if ($conf->dolimail->enabled) header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.$object->id.'&'.($paramname2?$paramname2:'mid').'='.$parm2val); + else header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.$object->id); exit; } } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index 5827b846be9..4ff36a1e88b 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -154,7 +154,7 @@ if ($type == 'directory') $sorting = (strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC); // Right area. If module is defined, we are in automatic ecm. - $automodules = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'product', 'tax', 'project', 'fichinter', 'user'); + $automodules = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'product', 'tax', 'project', 'fichinter', 'user', 'expensereport'); // TODO change for multicompany sharing // Auto area for suppliers invoices @@ -189,6 +189,8 @@ if ($type == 'directory') else if ($module == 'fichinter') $upload_dir = $conf->ficheinter->dir_output; // Auto area for users else if ($module == 'user') $upload_dir = $conf->user->dir_output; + // Auto area for expense report + else if ($module == 'expensereport') $upload_dir = $conf->expensereport->dir_output; if (in_array($module, $automodules)) { diff --git a/htdocs/core/ajax/selectsearchbox.php b/htdocs/core/ajax/selectsearchbox.php index f9200810bdd..2e837fcbaae 100644 --- a/htdocs/core/ajax/selectsearchbox.php +++ b/htdocs/core/ajax/selectsearchbox.php @@ -22,16 +22,19 @@ */ -// This script is called with a POST method. -// Directory to scan (full path) is inside POST['dir']. +// This script is called with a POST method or as an include. -if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); -if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); -if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); +if (! isset($usedbyinclude) || empty($usedbyinclude)) +{ + if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal + //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); + if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); + if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); + if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); + + $res=@include '../../main.inc.php'; +} -$res=@include '../../main.inc.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; //global $hookmanager; @@ -44,85 +47,85 @@ $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('text'=>img_picto('','object_company').' '.$langs->trans("SearchIntoThirdparties", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/societe/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintothirdparty']=array('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('text'=>img_picto('','object_contact').' '.$langs->trans("SearchIntoContacts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contact/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintocontact']=array('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->product->enabled) && $user->rights->produit->lire) || (! empty($conf->service->enabled) && $user->rights->service->lire)) && empty($conf->global->MAIN_SEARCHFORM_PRODUITSERVICE_DISABLED)) { - $arrayresult['searchintoproduct']=array('text'=>img_picto('','object_product').' '.$langs->trans("SearchIntoProductsOrServices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/product/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoproduct']=array('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('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('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) { - $arrayresult['searchintotasks']=array('text'=>img_picto('','object_task').' '.$langs->trans("SearchIntoTasks", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/tasks/list.php?search_all='.urlencode($search_boxvalue)); + $arrayresult['searchintotasks']=array('img'=>'object_task', 'label'=>$langs->trans("SearchIntoTasks", $search_boxvalue), 'text'=>img_picto('','object_task').' '.$langs->trans("SearchIntoTasks", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/projet/tasks/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->adherent->enabled) && empty($conf->global->MAIN_SEARCHFORM_ADHERENT_DISABLED) && $user->rights->adherent->lire) { - $arrayresult['searchintomember']=array('text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoMembers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/adherents/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintomember']=array('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->user->enabled) && empty($conf->global->MAIN_SEARCHFORM_USER_DISABLED) && $user->rights->user->user->lire) { - $arrayresult['searchintouser']=array('text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintouser']=array('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->propal->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_PROPAL_DISABLED) && $user->rights->propal->lire) { - $arrayresult['searchintopropal']=array('text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/comm/propal/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintopropal']=array('img'=>'object_propal', 'label'=>$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoCustomerProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/comm/propal/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->commande->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_ORDER_DISABLED) && $user->rights->commande->lire) { - $arrayresult['searchintoorder']=array('text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/commande/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoorder']=array('img'=>'object_order', 'label'=>$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoCustomerOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/commande/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->facture->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_INVOICE_DISABLED) && $user->rights->facture->lire) { - $arrayresult['searchintoinvoice']=array('text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/compta/facture/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoinvoice']=array('img'=>'object_bill', 'label'=>$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoCustomerInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/compta/facture/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->expedition->enabled) && empty($conf->global->MAIN_SEARCHFORM_CUSTOMER_SHIPMENT_DISABLED) && $user->rights->expedition->lire) { - $arrayresult['searchintoshipment']=array('text'=>img_picto('','object_sending').' '.$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expedition/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoshipment']=array('img'=>'object_sending', 'label'=>$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'text'=>img_picto('','object_sending').' '.$langs->trans("SearchIntoCustomerShipments", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expedition/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->supplier_proposal->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_PROPAL_DISABLED) && $user->rights->supplier_proposal->lire) { - $arrayresult['searchintosupplierpropal']=array('text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/supplier_proposal/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierpropal']=array('img'=>'object_propal', 'label'=>$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'text'=>img_picto('','object_propal').' '.$langs->trans("SearchIntoSupplierProposals", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/supplier_proposal/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_ORDER_DISABLED) && $user->rights->fournisseur->commande->lire) { - $arrayresult['searchintosupplierorder']=array('text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/commande/list.php?search_all='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierorder']=array('img'=>'object_order', 'label'=>$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'text'=>img_picto('','object_order').' '.$langs->trans("SearchIntoSupplierOrders", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/commande/list.php?search_all='.urlencode($search_boxvalue)); } if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_SEARCHFORM_SUPPLIER_INVOICE_DISABLED) && $user->rights->fournisseur->facture->lire) { - $arrayresult['searchintosupplierinvoice']=array('text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/facture/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintosupplierinvoice']=array('img'=>'object_bill', 'label'=>$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'text'=>img_picto('','object_bill').' '.$langs->trans("SearchIntoSupplierInvoices", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fourn/facture/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->contrat->enabled) && empty($conf->global->MAIN_SEARCHFORM_CONTRACT_DISABLED) && $user->rights->contrat->lire) { - $arrayresult['searchintocontract']=array('text'=>img_picto('','object_contract').' '.$langs->trans("SearchIntoContracts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contrat/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintocontract']=array('img'=>'object_contract', 'label'=>$langs->trans("SearchIntoContracts", $search_boxvalue), 'text'=>img_picto('','object_contract').' '.$langs->trans("SearchIntoContracts", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/contrat/list.php?sall='.urlencode($search_boxvalue)); } if (! empty($conf->ficheinter->enabled) && empty($conf->global->MAIN_SEARCHFORM_FICHINTER_DISABLED) && $user->rights->ficheinter->lire) { - $arrayresult['searchintointervention']=array('text'=>img_picto('','object_intervention').' '.$langs->trans("SearchIntoInterventions", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fichinter/list.php?sall='.urlencode($search_boxvalue)); + $arrayresult['searchintointervention']=array('img'=>'object_intervention', 'label'=>$langs->trans("SearchIntoInterventions", $search_boxvalue), 'text'=>img_picto('','object_intervention').' '.$langs->trans("SearchIntoInterventions", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/fichinter/list.php?sall='.urlencode($search_boxvalue)); } // HR if (! empty($conf->expensereport->enabled) && empty($conf->global->MAIN_SEARCHFORM_EXPENSEREPORT_DISABLED) && $user->rights->expensereport->lire) { - $arrayresult['searchintoexpensereport']=array('text'=>img_picto('','object_trip').' '.$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoexpensereport']=array('img'=>'object_trip', 'label'=>$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'text'=>img_picto('','object_trip').' '.$langs->trans("SearchIntoExpenseReports", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/expensereport/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); } if (! empty($conf->holiday->enabled) && empty($conf->global->MAIN_SEARCHFORM_HOLIDAY_DISABLED) && $user->rights->holiday->read) { - $arrayresult['searchintoleaves']=array('text'=>img_picto('','object_holiday').' '.$langs->trans("SearchIntoLeaves", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/holiday/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); + $arrayresult['searchintoleaves']=array('img'=>'object_holiday', 'label'=>$langs->trans("SearchIntoLeaves", $search_boxvalue), 'text'=>img_picto('','object_holiday').' '.$langs->trans("SearchIntoLeaves", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/holiday/list.php?mainmenu=hrm&sall='.urlencode($search_boxvalue)); } @@ -144,6 +147,10 @@ if (empty($reshook)) else $arrayresult=$hookmanager->resArray; -print json_encode($arrayresult); +// Print output if called by ajax or do nothing (var $arrayresult will be used) if called by an include +if (! isset($usedbyinclude) || empty($usedbyinclude)) +{ + print json_encode($arrayresult); + if (is_object($db)) $db->close(); +} -if (is_object($db)) $db->close(); diff --git a/htdocs/core/boxes/box_factures_fourn_imp.php b/htdocs/core/boxes/box_factures_fourn_imp.php index b3ca0fec031..0d6bc28f077 100644 --- a/htdocs/core/boxes/box_factures_fourn_imp.php +++ b/htdocs/core/boxes/box_factures_fourn_imp.php @@ -117,18 +117,12 @@ class box_factures_fourn_imp extends ModeleBoxes } $tooltip = $langs->trans('SupplierInvoice') . ': ' . ($objp->ref?$objp->ref:$objp->facid) . '
    ' . $langs->trans('RefSupplier') . ': ' . $objp->ref_supplier; - $this->info_box_contents[$line][] = array( - 'td' => 'align="left" width="16"', - 'logo' => $this->boximg, - 'tooltip' => $tooltip, - 'url' => DOL_URL_ROOT."/fourn/facture/card.php?facid=".$objp->facid, - ); $this->info_box_contents[$line][] = array( 'td' => 'align="left"', 'text' => $facturestatic->getNomUrl(1), 'text2'=> $late, - 'asisi' => 1 + 'asis' => 1 ); $this->info_box_contents[$line][] = array( diff --git a/htdocs/core/boxes/box_members.php b/htdocs/core/boxes/box_members.php index d5d8f1243f5..afcbe8e68a6 100644 --- a/htdocs/core/boxes/box_members.php +++ b/htdocs/core/boxes/box_members.php @@ -84,7 +84,7 @@ class box_members extends ModeleBoxes { $sql = "SELECT a.rowid, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; $sql.= " a.datec, a.tms, a.statut as status, a.datefin as date_end_subscription,"; - $sql.= " t.cotisation"; + $sql.= " t.subscription"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a, ".MAIN_DB_PREFIX."adherent_type as t"; $sql.= " WHERE a.entity = ".$conf->entity; $sql.= " AND a.fk_adherent_type = t.rowid"; @@ -135,7 +135,7 @@ class box_members extends ModeleBoxes $this->info_box_contents[$line][] = array( 'td' => 'align="right" width="18"', - 'text' => $memberstatic->LibStatut($objp->status,$objp->cotisation,$db->jdate($objp->date_end_subscription),3), + 'text' => $memberstatic->LibStatut($objp->status,$objp->subscription,$db->jdate($objp->date_end_subscription),3), ); $line++; diff --git a/htdocs/core/boxes/box_produits_alerte_stock.php b/htdocs/core/boxes/box_produits_alerte_stock.php index 4d79abd156b..3ec0fc7070c 100644 --- a/htdocs/core/boxes/box_produits_alerte_stock.php +++ b/htdocs/core/boxes/box_produits_alerte_stock.php @@ -66,7 +66,7 @@ class box_produits_alerte_stock extends ModeleBoxes if ($user->rights->produit->lire || $user->rights->service->lire) { - $sql = "SELECT p.rowid, p.label, p.price, p.ref, p.price_base_type, p.price_ttc, p.fk_product_type, p.tms, p.tosell, p.tobuy, p.seuil_stock_alerte,p.entity,"; + $sql = "SELECT p.rowid, p.label, p.price, p.ref, p.price_base_type, p.price_ttc, p.fk_product_type, p.tms, p.tosell, p.tobuy, p.seuil_stock_alerte, p.entity,"; $sql.= " SUM(".$db->ifsql("s.reel IS NULL","0","s.reel").") as total_stock"; $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as s on p.rowid = s.fk_product"; @@ -74,7 +74,7 @@ class box_produits_alerte_stock extends ModeleBoxes $sql.= " AND p.tosell = 1 AND p.seuil_stock_alerte > 0"; if (empty($user->rights->produit->lire)) $sql.=' AND p.fk_product_type != 0'; if (empty($user->rights->service->lire)) $sql.=' AND p.fk_product_type != 1'; - $sql.= " GROUP BY p.rowid, p.ref, p.label, p.price, p.price_base_type, p.price_ttc, p.fk_product_type, p.tms, p.tosell, p.tobuy, p.seuil_stock_alerte"; + $sql.= " GROUP BY p.rowid, p.ref, p.label, p.price, p.price_base_type, p.price_ttc, p.fk_product_type, p.tms, p.tosell, p.tobuy, p.seuil_stock_alerte, p.entity"; $sql.= " HAVING SUM(".$db->ifsql("s.reel IS NULL","0","s.reel").") < p.seuil_stock_alerte"; $sql.= $db->order('p.seuil_stock_alerte', 'DESC'); $sql.= $db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_project.php b/htdocs/core/boxes/box_project.php index 8733f3ed8ce..4c0689cd282 100644 --- a/htdocs/core/boxes/box_project.php +++ b/htdocs/core/boxes/box_project.php @@ -2,6 +2,7 @@ /* Copyright (C) 2012-2014 Charles-François BENKE * Copyright (C) 2014 Marcos García * Copyright (C) 2015 Frederic France + * Copyright (C) 2016 Juan José Menent * * 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 @@ -79,8 +80,10 @@ class box_project extends ModeleBoxes $sql = "SELECT p.rowid, p.ref, p.title, p.fk_statut "; $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; + if($user->socid) $sql.= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=p.fk_soc"; $sql.= " WHERE p.entity = ".$conf->entity; - $sql.= " AND p.fk_statut = 1"; // Seulement les projets ouverts + if($user->socid) $sql.= " AND s.rowid = ".$user->socid; + $sql.= " AND p.fk_statut = 1"; // Seulement les projets ouverts $sql.= " ORDER BY p.datec DESC"; $sql.= $db->plimit($max, 0); diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 563ec168d29..317b84e0b29 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -690,7 +690,7 @@ class CMailFile * @param string $stringtoencode String to encode * @return string string encoded */ - function encodetorfc2822($stringtoencode) + static function encodetorfc2822($stringtoencode) { global $conf; return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?='; @@ -1105,12 +1105,12 @@ class CMailFile $_retVal = true; // Indicates if Object was created or not $server_response = ''; - while ( substr($server_response,3,1) != ' ' ) + while (substr($server_response,3,1) != ' ') { - if( !( $server_response = fgets($socket, 256) ) ) + if (! ($server_response = fgets($socket, 256)) ) { $this->error="Couldn't get mail server response codes"; - $_retVal = false; + return false; } } @@ -1220,15 +1220,17 @@ class CMailFile /** * Return a formatted address string for SMTP protocol * - * @param string $address Example: 'John Doe , Alan Smith ' or 'john@doe.com, alan@smith.com' - * @param int $format 0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between " - * @param int $encode 1=Encode name to RFC2822 - * @return string If format 0: '' or 'John Doe ' or '=?UTF-8?B?Sm9obiBEb2U=?= ' - * If format 1: '' - * If format 2: 'john@doe.com' - * If format 3: '' or '"John Doe" ' or '"=?UTF-8?B?Sm9obiBEb2U=?=" ' + * @param string $address Example: 'John Doe , Alan Smith ' or 'john@doe.com, alan@smith.com' + * @param int $format 0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between " + * @param int $encode 0=No encode name, 1=Encode name to RFC2822 + * @param int $maxnumberofemail 0=No limit. Otherwise, maximum number of emails returned ($address may contains several email separated with ','). Add '...' if there is more. + * @return string If format 0: '' or 'John Doe ' or '=?UTF-8?B?Sm9obiBEb2U=?= ' + * If format 1: '' + * If format 2: 'john@doe.com' + * If format 3: '' or '"John Doe" ' or '"=?UTF-8?B?Sm9obiBEb2U=?=" ' + * If format 4: 'John Doe' or 'john@doe.com' if no label exists */ - function getValidAddress($address,$format,$encode='') + static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0) { global $conf; @@ -1237,6 +1239,7 @@ class CMailFile $arrayaddress=explode(',',$address); // Boucle sur chaque composant de l'adresse + $i=0; foreach($arrayaddress as $val) { if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs)) @@ -1252,7 +1255,13 @@ class CMailFile if ($email) { + $i++; + $newemail=''; + if ($format == 4) + { + $newemail = $name?$name:$email; + } if ($format == 2) { $newemail=$email; @@ -1265,10 +1274,17 @@ class CMailFile { if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>'; elseif (! $name) $newemail='<'.$email.'>'; - else $newemail=($format==3?'"':'').($encode?$this->encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>'; + else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>'; } $ret=($ret ? $ret.',' : '').$newemail; + + // Stop if we have too much records + if ($maxnumberofemail && $i >= $maxnumberofemail) + { + if (count($arrayaddress) > $maxnumberofemail) $ret.='...'; + break; + } } } diff --git a/htdocs/core/class/ccountry.class.php b/htdocs/core/class/ccountry.class.php index 59980cea7a9..d0e6dfe190a 100644 --- a/htdocs/core/class/ccountry.class.php +++ b/htdocs/core/class/ccountry.class.php @@ -143,7 +143,7 @@ class Ccountry // extends CommonObject * * @param int $id Id object * @param string $code Code - * @return int <0 if KO, >0 if OK + * @return int >0 if OK, 0 if not found, <0 if KO */ function fetch($id,$code='') { @@ -171,10 +171,13 @@ class Ccountry // extends CommonObject $this->code_iso = $obj->code_iso; $this->label = $obj->label; $this->active = $obj->active; - } - $this->db->free($resql); - return 1; + $this->db->free($resql); + return 1; + } + else { + return 0; + } } else { diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 019c3102074..3ed34cfd801 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -35,8 +35,8 @@ abstract class CommonDocGenerator { var $error=''; protected $db; - - + + /** * Constructor * @@ -59,6 +59,8 @@ abstract class CommonDocGenerator { global $conf; + $logotouse=$conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; + return array( 'myuser_lastname'=>$user->lastname, 'myuser_firstname'=>$user->firstname, @@ -75,7 +77,7 @@ abstract class CommonDocGenerator 'myuser_fax'=>$user->office_fax, 'myuser_mobile'=>$user->user_mobile, 'myuser_email'=>$user->email, - 'myuser_logo'=>$user->photo, + 'myuser_logo'=>$logotouse, 'myuser_job'=>$user->job, 'myuser_web'=>'' // url not exist in $user object ); @@ -209,7 +211,7 @@ abstract class CommonDocGenerator { $object->array_options['options_'.$key] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency); } - else if($extrafields->attribute_type[$key] == 'select') + else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox') { $object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]]; } @@ -280,7 +282,7 @@ abstract class CommonDocGenerator { $object->array_options['options_' . $key] = price($object->array_options ['options_' . $key], 0, $outputlangs, 0, 0, - 1, $conf->currency); } - elseif($extrafields->attribute_type[$key] == 'select') + elseif($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox') { $object->array_options['options_' . $key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_' . $key]]; } @@ -389,7 +391,7 @@ abstract class CommonDocGenerator // Add vat by rates foreach ($object->lines as $line) { - // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward comaptibility + // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward comaptibility if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx]=0; $resarray[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva; $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx]=price($resarray[$array_key.'_total_vat_'.$line->tva_tx]); @@ -576,12 +578,12 @@ abstract class CommonDocGenerator //Add value to store price with currency $array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency'])); } - else if($extrafields->attribute_type[$key] == 'select') + else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox') { $object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]]; } else if($extrafields->attribute_type[$key] == 'date') - { + { if (strlen($object->array_options['options_'.$key])>0) { $object->array_options['options_'.$key] = dol_print_date($object->array_options['options_'.$key],'day'); // using company output language diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 7c68a5ff978..b3b0cc4042b 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -198,9 +198,9 @@ abstract class CommonInvoice extends CommonObject } /** - * Retourne le libelle du type de facture + * Return label of type of invoice * - * @return string Libelle + * @return string Label of type of invoice */ function getLibType() { @@ -209,7 +209,7 @@ abstract class CommonInvoice extends CommonObject if ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement"); if ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir"); if ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit"); - if ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma"); + if ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma"); // Not used. if ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation"); return $langs->trans("Unknown"); } @@ -217,7 +217,7 @@ abstract class CommonInvoice extends CommonObject /** * Return label of object status * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto * @param integer $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise) * @return string Label */ @@ -364,9 +364,9 @@ abstract class CommonInvoice extends CommonObject if (! $cond_reglement) $cond_reglement=$this->cond_reglement_code; if (! $cond_reglement) $cond_reglement=$this->cond_reglement_id; - $cdr_nbjour=0; $cdr_fdm=0; $cdr_decalage=0; + $cdr_nbjour=0; $cdr_type=0; $cdr_decalage=0; - $sqltemp = 'SELECT c.fdm,c.nbjour,c.decalage'; + $sqltemp = 'SELECT c.type_cdr,c.nbjour,c.decalage'; $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement; else $sqltemp.= " WHERE c.code='".$this->db->escape($cond_reglement)."'"; @@ -379,7 +379,7 @@ abstract class CommonInvoice extends CommonObject { $obj = $this->db->fetch_object($resqltemp); $cdr_nbjour = $obj->nbjour; - $cdr_fdm = $obj->fdm; + $cdr_type = $obj->type_cdr; $cdr_decalage = $obj->decalage; } } @@ -396,7 +396,7 @@ abstract class CommonInvoice extends CommonObject $datelim = $this->date + ($cdr_nbjour * 3600 * 24); // 2 : application de la regle "fin de mois" - if ($cdr_fdm) + if ($cdr_type == 1) { $mois=date('m', $datelim); $annee=date('Y', $datelim); @@ -413,6 +413,19 @@ abstract class CommonInvoice extends CommonObject $datelim=dol_mktime(12,0,0,$mois,1,$annee); $datelim -= (3600 * 24); } + elseif($cdr_type == 2 && !empty($cdr_nbjour)) // Application de la règle, le N du mois courant ou suivant + { + + $date_piece = dol_mktime(0,0,0,date('m', $this->date),date('d', $this->date),date('Y', $this->date)); // Sans les heures minutes et secondes + $date_lim_current = dol_mktime(0,0,0,date('m', $this->date),$cdr_nbjour,date('Y', $this->date)); // Sans les heures minutes et secondes + $date_lim_next = strtotime(date('Y-m-d', $date_lim_current).' +1month'); + + $diff = $date_piece - $date_lim_current; + + if($diff < 0) $datelim = $date_lim_current; + else $datelim = $date_lim_next; + + } // 3 : application du decalage $datelim += ($cdr_decalage * 3600 * 24); diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 07195cf0d50..cdd8b89a1ad 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -433,7 +433,7 @@ abstract class CommonObject /** - * Return full address of contact + * Return full address for banner * * @param string $htmlkey HTML id to make banner content unique * @param Object $object Object (thirdparty, thirdparty of contact for contact, null for a member) @@ -476,7 +476,7 @@ abstract class CommonObject $out.=img_picto($langs->trans("Address"), 'object_address.png'); $out.=' '; } - $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1); $outdone++; + $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++; $outdone++; } @@ -522,7 +522,7 @@ abstract class CommonObject } if (! empty($this->url)) { - $out.=dol_print_url($this->url,'',0,1); + $out.=dol_print_url($this->url,'_goout',0,1); $outdone++; } if (! empty($conf->skype->enabled)) @@ -1148,7 +1148,6 @@ abstract class CommonObject */ function fetch_origin() { - // TODO uniformise code if ($this->origin == 'shipping') $this->origin = 'expedition'; if ($this->origin == 'delivery') $this->origin = 'livraison'; @@ -1215,24 +1214,30 @@ abstract class CommonObject } /** - * Setter generic. Update a specific field into database + * Setter generic. Update a specific field into database. + * Warning: Trigger is run only if param trigkey is provided. * * @param string $field Field to update * @param mixed $value New value * @param string $table To force other table element or element line (should not be used) * @param int $id To force other object id (should not be used) * @param string $format Data format ('text', 'date'). 'text' is used if not defined - * @param string $id_field To force rowid field name. 'rowid' is used it not defined + * @param string $id_field To force rowid field name. 'rowid' is used if not defined * @param User|string $user Update last update fields also if user object provided + * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') * @return int <0 if KO, >0 if OK */ - function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $user='') + function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $user='', $trigkey='') { - if (empty($table)) $table=$this->table_element; - if (empty($id)) $id=$this->id; - if (empty($format)) $format='text'; - if (empty($id_field)) $id_field='rowid'; + global $user,$langs,$conf; + + if (empty($table)) $table=$this->table_element; + if (empty($id)) $id=$this->id; + if (empty($format)) $format='text'; + if (empty($id_field)) $id_field='rowid'; + $error=0; + $this->db->begin(); // Special case @@ -1240,7 +1245,8 @@ abstract class CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; - else if ($format == 'date') $sql.= $field." = '".$this->db->idate($value)."'"; + else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value); + else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); if (is_object($user)) $sql.=", fk_user_modif = ".$user->id; $sql.= " WHERE ".$id_field." = ".$id; @@ -1248,8 +1254,23 @@ abstract class CommonObject $resql = $this->db->query($sql); if ($resql) { - $this->db->commit(); - return 1; + if ($trigkey) + { + $result=$this->call_trigger($trigkey, $user); // This may set this->errors + if ($result < 0) $error++; + } + + if (! $error) + { + if (property_exists($this, $field)) $this->$field = $value; + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -2; + } } else { @@ -1267,7 +1288,7 @@ abstract class CommonObject * @param int $nodbprefix Do not include DB prefix to forge table name * @return int <0 if KO, >0 if OK */ - function load_previous_next_ref($filter,$fieldid,$nodbprefix=0) + function load_previous_next_ref($filter, $fieldid, $nodbprefix=0) { global $user; @@ -2584,7 +2605,7 @@ abstract class CommonObject $classfile = 'facture-rec'; $classname = 'FactureRec'; } else if ($objecttype == 'subscription') { - $classfile = 'cotisation'; $classname = 'Cotisation'; + $classfile = 'subscription'; $classname = 'Subscription'; } // Here $module, $classfile and $classname are set @@ -2758,6 +2779,7 @@ abstract class CommonObject $trigkey=''; if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; + if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; @@ -2776,7 +2798,11 @@ abstract class CommonObject if (! $error) { $this->db->commit(); - $this->statut = $status; + if (empty($elementId)) // If the element we update was $this (so $elementId is null) + { + $this->statut = $status; + $this->status = $status; + } return 1; } else @@ -3057,6 +3083,7 @@ abstract class CommonObject /** * Return incoterms informations + * TODO Use a cache for label get * * @return string incoterms info */ @@ -3075,7 +3102,7 @@ abstract class CommonObject } } - $out .= ' - '.$this->location_incoterms; + $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms; return $out; } @@ -3729,30 +3756,30 @@ abstract class CommonObject { global $user; - $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; $sql.= " WHERE rowid=".$rowid; dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); - $resql=$this->db->query($sql); - if (! $resql) + + $resql=$this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + if (! $notrigger) { - $this->error=$this->db->lasterror(); - $this->db->rollback(); - return -1; - } - else - { - if (! $notrigger) - { - $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); - if ($result < 0) { $this->db->rollback(); return -1; } - } - $this->db->commit(); - return 1; + $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); + if ($result < 0) { $this->db->rollback(); return -1; } } + $this->db->commit(); + return 1; + } } @@ -3783,9 +3810,10 @@ abstract class CommonObject * @param int $hidedetails 1 to hide details. 0 by default * @param int $hidedesc 1 to hide product description. 0 by default * @param int $hideref 1 to hide product reference. 0 by default + * @param null|array $moreparams Array to provide more information * @return int >0 if OK, <0 if KO */ - protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref) + protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null) { global $conf, $langs; @@ -3813,7 +3841,8 @@ abstract class CommonObject { foreach(array('doc','pdf') as $prefix) { - $file = $prefix."_".$modele.".modules.php"; + if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php + else $file = $prefix."_".$modele.".modules.php"; // On verifie l'emplacement du modele $file=dol_buildpath($reldir.$modelspath.$file,0); @@ -3830,6 +3859,8 @@ abstract class CommonObject // If generator was found if ($filefound) { + global $db; // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db + require_once $file; $obj = new $classname($this->db); @@ -3887,7 +3918,15 @@ abstract class CommonObject // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. $sav_charset_output=$outputlangs->charset_output; - if ($obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref) > 0) + + if (in_array(get_class($this), array('Adherent'))) + { + $arrayofrecords = array(); // The write_file of templates of adherent class need this + $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams); + } + else $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams); + + if ($resultwritefile > 0) { $outputlangs->charset_output=$sav_charset_output; @@ -4188,7 +4227,9 @@ abstract class CommonObject $object = new $InfoFieldList[0]($this->db); if ($value) { - $res=$object->fetch(0,$value); + if (is_numeric($value)) $res=$object->fetch($value); + else $res=$object->fetch('',$value); + if ($res > 0) $this->array_options[$key]=$object->id; else { diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 4b7e2a3d79b..abe672dee68 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -1,7 +1,7 @@ * Copyright (C) 2003 Xavier Dutoit - * Copyright (C) 2004-2012 Laurent Destailleur + * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2006 Jean Heimburger * @@ -386,6 +386,8 @@ class Conf if (empty($this->global->SOCIETE_CODECLIENT_ADDON)) $this->global->SOCIETE_CODECLIENT_ADDON="mod_codeclient_leopard"; if (empty($this->global->SOCIETE_CODECOMPTA_ADDON)) $this->global->SOCIETE_CODECOMPTA_ADDON="mod_codecompta_panicum"; + if (empty($this->global->CHEQUERECEIPTS_ADDON)) $this->global->CHEQUERECEIPTS_ADDON='mod_chequereceipt_mint'; + // Security if (empty($this->global->USER_PASSWORD_GENERATED)) $this->global->USER_PASSWORD_GENERATED='standard'; // Default password generator if (empty($this->global->MAIN_UMASK)) $this->global->MAIN_UMASK='0664'; // Default mask @@ -489,8 +491,8 @@ class Conf // By default, we use the zip town autofill if (! isset($this->global->MAIN_USE_ZIPTOWN_DICTIONNARY)) $this->global->MAIN_USE_ZIPTOWN_DICTIONNARY=1; - // Define list of limited modules - if (! isset($this->global->MAIN_MODULES_FOR_EXTERNAL)) $this->global->MAIN_MODULES_FOR_EXTERNAL='user,supplier_proposal,facture,categorie,commande,fournisseur,contact,propal,projet,contrat,societe,ficheinter,expedition,agenda,adherent'; // '' means 'all'. Note that contact is added here as it should be a module later. + // Define list of limited modules (value must be key found for "name" property of module, so for example 'supplierproposal' for Module "Supplier Proposal" + if (! isset($this->global->MAIN_MODULES_FOR_EXTERNAL)) $this->global->MAIN_MODULES_FOR_EXTERNAL='user,societe,propal,commande,facture,categorie,supplierproposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,adherent'; // '' means 'all'. Note that contact is added here as it should be a module later. // Enable select2 if (empty($this->global->MAIN_USE_JQUERY_MULTISELECT) || $this->global->MAIN_USE_JQUERY_MULTISELECT == '1') $this->global->MAIN_USE_JQUERY_MULTISELECT='select2'; @@ -508,8 +510,8 @@ class Conf // Delay before warnings // Avoid strict errors. TODO: Replace xxx->warning_delay with a property ->warning_delay_xxx if (isset($this->agenda)) { - $this->adherent->cotisation = new stdClass(); - $this->adherent->cotisation->warning_delay=(isset($this->global->MAIN_DELAY_MEMBERS)?$this->global->MAIN_DELAY_MEMBERS:0)*24*60*60; + $this->adherent->subscription = new stdClass(); + $this->adherent->subscription->warning_delay=(isset($this->global->MAIN_DELAY_MEMBERS)?$this->global->MAIN_DELAY_MEMBERS:0)*24*60*60; } if (isset($this->agenda)) $this->agenda->warning_delay=(isset($this->global->MAIN_DELAY_ACTIONS_TODO)?$this->global->MAIN_DELAY_ACTIONS_TODO:7)*24*60*60; if (isset($this->projet)) diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index 3bfcf9b781e..ef750e70253 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -81,7 +81,7 @@ class DolEditor // Check if extended editor is ok. If not we force textarea if (empty($conf->fckeditor->enabled) || ! $okforextendededitor) $this->tool = 'textarea'; - //if ($conf->browser->phone) $this->tool = 'textarea'; + if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // TODO ckeditor ko with jmobile // Define content and some properties if ($this->tool == 'ckeditor') @@ -140,21 +140,25 @@ class DolEditor * Output edit area inside the HTML stream. * Output depends on this->tool (fckeditor, ckeditor, textarea, ...) * - * @param int $noprint 1=Return HTML string instead of printing it to output - * @param string $morejs Add more js. For example: ".on( \'saveSnapshot\', function(e) { alert(\'ee\'); });" + * @param int $noprint 1=Return HTML string instead of printing it to output + * @param string $morejs Add more js. For example: ".on( \'saveSnapshot\', function(e) { alert(\'ee\'); });" + * @param boolean $disallowAnyContent Disallow to use any content. true=restrict to a predefined list of allowed elements. * @return void|string */ - function Create($noprint=0,$morejs='') + function Create($noprint=0,$morejs='',$disallowAnyContent=true) { global $conf,$langs; $fullpage=False; - $disallowAnyContent=empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed - + if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) + { + $disallowAnyContent=empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed + } + $found=0; $out=''; - if ($this->tool == 'fckeditor') + if ($this->tool == 'fckeditor') // not used anymore { $found=1; $this->editor->Create(); @@ -179,6 +183,7 @@ class DolEditor $htmlencode_force=preg_match('/_encoded$/',$this->toolbarname)?'true':'false'; + $out.= ''."\n"; $out.= ''; $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter); - $out.=' '; + $out.=' '; } $assignedtouser=array(); if (!empty($_SESSION['assignedtouser'])) @@ -1574,6 +1581,7 @@ class Form $nbassignetouser=count($assignedtouser); if ($nbassignetouser && $action != 'view') $out.='
    '; + if ($nbassignetouser) $out.='
    '; $i=0; $ownerid=0; foreach($assignedtouser as $key => $value) { @@ -1587,6 +1595,7 @@ class Form $out.='
    '; $i++; } + if ($nbassignetouser) $out.='
    '; //$out.=''; return $out; @@ -1607,10 +1616,14 @@ class Form * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) * @param array $ajaxoptions Options for ajax_autocompleter * @param int $socid Thirdparty Id (to get also price dedicated to this customer) + * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param int $forcecombo Force to use combo box + * @param string $morecss Add more css on select + * @param int $hidepriceinlabel 1=Hide prices in label * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) * @return void */ - function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $selected_combinations = array()) + function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $selected_combinations = array()) { global $langs,$conf; @@ -1717,33 +1730,37 @@ class Form print img_picto($langs->trans("Search"), 'search'); } } - print 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; + print 'global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />'; if ($hidelabel == 3) { print img_picto($langs->trans("Search"), 'search'); } } else { - print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid); + print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel); } } /** * Return list of products for a customer * - * @param int $selected Preselected product - * @param string $htmlname Name of select html - * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) - * @param int $limit Limit on number of returned lines - * @param int $price_level Level of price to show - * @param string $filterkey Filter on product - * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell - * @param int $finished Filter on finished field: 2=No filter - * @param int $outputmode 0=HTML select string, 1=Array - * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @return array Array of keys for json + * @param int $selected Preselected product + * @param string $htmlname Name of select html + * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service) + * @param int $limit Limit on number of returned lines + * @param int $price_level Level of price to show + * @param string $filterkey Filter on product + * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell + * @param int $finished Filter on finished field: 2=No filter + * @param int $outputmode 0=HTML select string, 1=Array + * @param int $socid Thirdparty Id (to get also price dedicated to this customer) + * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param int $forcecombo Force to use combo box + * @param string $morecss Add more css on select + * @param int $hidepriceinlabel 1=Hide prices in label + * @return array Array of keys for json */ - function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0) + function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0) { global $langs,$conf,$user,$db; @@ -1844,8 +1861,27 @@ class Form require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php'; $num = $this->db->num_rows($result); - $out.=''; + + $textifempty=''; + // Do not use textifempty = ' ' or ' ' here, or search on key will search on ' key'. + //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty=''; + if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) + { + if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); + else $textifempty.=$langs->trans("All"); + } + if ($showempty) $out.=''; $i = 0; while ($num && $i < $num) @@ -1877,7 +1913,7 @@ class Form $objp->remise = $objp2->remise; $objp->price_by_qty_rowid = $objp2->rowid; - $this->constructProductListOption($objp, $opt, $optJson, 0, $selected); + $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel); $j++; @@ -1904,7 +1940,7 @@ class Form $objp->price_ttc = price2num($objp->price_ttc,'MU'); } } - $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected); + $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel); // Add new entry // "key" value of json key array is used by jQuery automatically as selected value // "label" value of json key array is used by jQuery automatically as text for combo box @@ -1984,13 +2020,13 @@ class Form $opt.= '>'; $opt.= $objp->ref; if ($outbarcode) $opt.=' ('.$outbarcode.')'; - $opt.=' - '.dol_trunc($label,$maxlengtharticle).' - '; + $opt.=' - '.dol_trunc($label,$maxlengtharticle); $objRef = $objp->ref; if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','$1',$objRef,1); $outval.=$objRef; if ($outbarcode) $outval.=' ('.$outbarcode.')'; - $outval.=' - '.dol_trunc($label,$maxlengtharticle).' - '; + $outval.=' - '.dol_trunc($label,$maxlengtharticle); $found=0; @@ -2015,13 +2051,13 @@ class Form $found=1; if ($objp2->price_base_type == 'HT') { - $opt.= price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT"); - $outval.= price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT"); + $opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT"); + $outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT"); } else { - $opt.= price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC"); - $outval.= price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC"); + $opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC"); + $outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC"); } $outprice_ht=price($objp2->price); $outprice_ttc=price($objp2->price_ttc); @@ -2043,15 +2079,15 @@ class Form $outdiscount=$objp->remise_percent; if ($objp->quantity == 1) { - $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/"; - $outval.= price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/"; + $opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/"; + $outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/"; $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding $outval.=$langs->transnoentities("Unit"); } else { - $opt.= price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity; - $outval.= price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity; + $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity; + $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity; $opt.= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding $outval.=$langs->transnoentities("Units"); } @@ -2081,13 +2117,13 @@ class Form if ($objp->custprice_base_type == 'HT') { - $opt.= price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT"); - $outval.= price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT"); + $opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT"); + $outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT"); } else { - $opt.= price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC"); - $outval.= price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC"); + $opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC"); + $outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC"); } $outprice_ht=price($objp->custprice); @@ -2102,13 +2138,13 @@ class Form { if ($objp->price_base_type == 'HT') { - $opt.= price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT"); - $outval.= price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT"); + $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT"); + $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT"); } else { - $opt.= price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC"); - $outval.= price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC"); + $opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC"); + $outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC"); } $outprice_ht=price($objp->price); $outprice_ttc=price($objp->price_ttc); @@ -2152,9 +2188,10 @@ class Form * @param string $filtre For a SQL filter * @param array $ajaxoptions Options for ajax_autocompleter * @param int $hidelabel Hide label (0=no, 1=yes) + * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices * @return void */ - function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0) + function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0) { global $langs,$conf; global $price_level, $status, $finished; @@ -2176,7 +2213,7 @@ class Form print ''; } // mode=2 means suppliers products - $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished; + $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice; print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions); print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').''; } @@ -2187,7 +2224,7 @@ class Form print ''; print ''; } - print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0); + print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice); } } @@ -2203,9 +2240,10 @@ class Form * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request) * @param int $outputmode 0=HTML select string, 1=Array * @param int $limit Limit of line number + * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices * @return array Array of keys for json */ - function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100) + function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0) { global $langs,$conf,$db; @@ -2259,7 +2297,7 @@ class Form $num = $this->db->num_rows($result); //$out.=''; + $out.=''; if ($addempty) print ''; foreach($this->cache_conditions_paiements as $id => $arrayconditions) @@ -2876,9 +2927,10 @@ class Form * @param int $noadmininfo 0=Add admin info, 1=Disable admin info * @param int $maxlength Max length of label * @param int $active Active or not, -1 = all + * @param string $morecss Add more css * @return void */ - function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1) + function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='') { global $langs,$user; @@ -2891,7 +2943,7 @@ class Form $this->load_cache_types_paiements(); - print ''; if ($empty) print ''; foreach($this->cache_types_paiements as $id => $arraytypes) { @@ -3032,12 +3084,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; $this->selectShippingMethod($selected, $htmlname, '', $addempty); - print '
    '; + print ''; + print ''; } else { if ($selected) { $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); @@ -3224,12 +3273,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; $this->select_comptes($selected, $htmlname, 0, '', $addempty); - print '
    '; + print ''; + print ''; } else { if ($selected) { require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; @@ -3341,10 +3387,10 @@ class Form * @param string $selectedchoice "" or "no" or "yes" * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx * @param int $height Force height of box - * @param int $width Force width of bow + * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form */ - function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500) + function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=200, $width=500) { global $langs,$conf; global $useglobalvars; @@ -3356,6 +3402,7 @@ class Form // Clean parameters $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice; + if ($conf->browser->layout == 'phone') $width='95%'; if (is_array($formquestion) && ! empty($formquestion)) { @@ -3586,7 +3633,7 @@ class Form $formconfirm.= '
    '; $formconfirm.= $this->selectyesno("confirm",$newselectedchoice); $formconfirm.= '
    '."\n"; @@ -3611,30 +3658,30 @@ class Form * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable) * @param int $maxlength Max length * @param int $forcefocus Force focus on field (works with javascript only) - * @return void + * @param int $nooutput No print is done. String is returned. + * @return string Return html content */ - function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0) + function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0) { global $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; + $out=''; + $formproject=new FormProjets($this->db); $langs->load("project"); if ($htmlname != "none") { - print "\n"; - print '
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
    '; - $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus); - print '
    '; + $out.="\n"; + $out.='
    '; + $out.=''; + $out.=''; + $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1); + $out.=''; + $out.='
    '; } else { @@ -3643,13 +3690,20 @@ class Form $projet = new Project($this->db); $projet->fetch($selected); //print ''.$projet->title.''; - print $projet->getNomUrl(0,'',1); + $out.=$projet->getNomUrl(0,'',1); } else { - print " "; + $out.=" "; } } + + if (empty($nooutput)) + { + print $out; + return ''; + } + return $out; } /** @@ -3669,12 +3723,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; $this->select_conditions_paiements($selected,$htmlname,-1,$addempty); - print '
    '; + print ''; + print ''; } else { @@ -3705,12 +3756,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty); - print '
    '; + print ''; + print ''; } else { @@ -3742,12 +3790,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; $this->selectInputReason($selected,$htmlname,-1,$addempty); - print '
    '; + print ''; + print ''; } else { @@ -3828,12 +3873,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include); - print '
    '; + print ''; + print ''; } else { @@ -3868,12 +3910,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active); - print '
    '; + print ''; + print ''; } else { @@ -3903,12 +3942,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; print $this->selectMultiCurrency($selected, $htmlname, 0); - print '
    '; + print ''; + print ''; } else { @@ -3935,12 +3971,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; print ''; - print '
    '; + print ''; + print ''; } else { @@ -3978,8 +4011,7 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; + print '
    '; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)).': '; // If we want deposit to be substracted to payments only and not to total of final invoice @@ -3990,20 +4022,24 @@ class Form if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)).': '; else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)).': '; } + print '
    '; $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles if ($filter) $newfilter.=' AND ('.$filter.')'; $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue); - print '
    '; if ($nbqualifiedlines > 0) { print '   '; } - if ($more) print $more; - print '
    '; + print '
    '; + if ($more) + { + print '
    '; + print $more; + print '
    '; + } + print ''; } else { @@ -4043,7 +4079,6 @@ class Form if ($num==0) { $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); - print 'Cette societe n\'a pas de contact, veuillez en cr�er un avant de faire votre proposition commerciale
    '; print ''.$addcontact.''; } print ''; @@ -4086,12 +4121,9 @@ class Form print '
    '; print ''; print ''; - print ''; - print ''; - print ''; - print '
    '; print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events); - print '
    '; + print ''; + print ''; } else { @@ -4185,6 +4217,11 @@ class Form $out=''; $out.= ''; + $selectedfound=false; foreach ($this->cache_vatrates as $rate) { // Keep only 0 if seller is not subject to VAT @@ -4394,13 +4432,21 @@ class Form $return.= $rate['nprtva'] ? '*': ''; if ($addcode && $rate['code']) $return.=' ('.$rate['code'].')'; $return.= '"'; - if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag + if (! $selectedfound) { - if ($defaultcode == $rate['code']) $return.= ' selected'; - } - elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) - { - $return.= ' selected'; + if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag + { + if ($defaultcode == $rate['code']) + { + $return.= ' selected'; + $selectedfound=true; + } + } + elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) + { + $return.= ' selected'; + $selectedfound=true; + } } $return.= '>'.vatrate($rate['libtva']); //$return.=($rate['code']?' '.$rate['code']:''); @@ -4594,7 +4640,7 @@ class Form } } - if ($d && $h) $retstring.=' '; + if ($d && $h) $retstring.=($h==2?'
    ':' '); if ($h) { @@ -4761,7 +4807,7 @@ class Form } elseif ($typehour=='text') { - $retstring.=''; + $retstring.=''; } else return 'BadValueForParameterTypeHour'; @@ -4784,7 +4830,7 @@ class Form } elseif ($typehour=='text') { - $retstring.=''; + $retstring.=''; } $retstring.=' '.$langs->trans('MinuteShort'); $retstring.=" "; @@ -5359,11 +5405,12 @@ class Form global $bc; $linktoelem=''; + $linktoelemlist=''; if (! is_object($object->thirdparty)) $object->fetch_thirdparty(); $possiblelinks=array( - 'propal'=>array('enabled'=>$conf->propale->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc = ".$object->thirdparty->id), + 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc = ".$object->thirdparty->id), 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc = ".$object->thirdparty->id), 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.facnumber as ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc = ".$object->thirdparty->id), 'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc = ".$object->thirdparty->id), @@ -5378,6 +5425,8 @@ class Form { $num = 0; + if (empty($possiblelink['enabled'])) continue; + if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto))) { print '
    global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>'; @@ -5417,7 +5466,7 @@ class Form $i++; } print ''; - print '
         
    '; + print '
         
    '; print ''; $this->db->free($resqllist); @@ -5430,22 +5479,29 @@ class Form } //$linktoelem.=($linktoelem?'   ':''); - if ($num > 0) $linktoelem.='
  • ' . $langs->trans($possiblelink['label']) .' ('.$num.')
  • '; + if ($num > 0) $linktoelemlist.='
  • ' . $langs->trans($possiblelink['label']) .' ('.$num.')
  • '; //else $linktoelem.=$langs->trans($possiblelink['label']); - else $linktoelem.='
  • ' . $langs->trans($possiblelink['label']) . ' (0)
  • '; + else $linktoelemlist.='
  • ' . $langs->trans($possiblelink['label']) . ' (0)
  • '; } } - $linktoelem=' - '; + if ($linktoelemlist) + { + $linktoelem=' + '; + } + else + { + $linktoelem=''; + } print ' '; + } + + $titletoshow=$langs->trans("Documents"); + if (! empty($title)) $titletoshow=$title; + // Show table if ($genallowed) { @@ -460,6 +486,15 @@ class FormFile $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; @@ -469,6 +504,15 @@ class FormFile $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=''; @@ -499,6 +543,7 @@ class FormFile } } + // Set headershown to avoit to have table opened a second time later $headershown=1; $buttonlabeltoshow=$buttonlabel; @@ -507,7 +552,7 @@ class FormFile if (empty($noform)) $out.= '
    '; $out.= ''; $out.= ''; - + $out.= load_fiche_titre($titletoshow, '', ''); $out.= ''; @@ -581,19 +626,29 @@ class FormFile } } + // 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); + } + $out.= ''."\n"; // Show title of array if not already shown - if ((! empty($file_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown) + if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart)) && ! $headershown) { $headershown=1; $out.= '
    '.$titletoshow.'
    '."\n"; - $out.= '
    '."\n"; + $out.= '
    '."\n"; } // Loop on each file found @@ -621,7 +676,6 @@ class FormFile $out.= ' target="_blank">'; $out.= img_mime($file["name"],$langs->trans("File").': '.$file["name"]).' '.dol_trunc($file["name"],$maxfilenamelength); $out.= ''."\n"; - $out.= $this->showPreview($file,$modulepart,$relativepath); $out.= ''; @@ -673,13 +727,37 @@ class FormFile } } - if (count($file_list) == 0 && $headershown) - { - $out.=''; - } - $this->numoffiles++; } + // Loop on each file found + if (is_array($link_list)) + { + $colspan=2; + + foreach($link_list as $file) + { + $var=!$var; + + $out.= ""; + $out.=''; + $out.=''; + if ($delallowed || $printer || $morepicto) $out.=''; + $out.=''; + } + $this->numoffiles++; + } + + if (count($file_list) == 0 && count($link_list) == 0 && $headershown) + { + $out.=''; + } + } if ($headershown) @@ -697,7 +775,7 @@ class FormFile } /** - * Show only Document icon with link + * Show a Document icon with link(s) * * @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. @@ -714,6 +792,8 @@ class FormFile $out=''; $this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array()); + if (! empty($conf->dol_use_jmobile)) return ''; + $file_list=dol_dir_list($filedir, 'files', 0, preg_quote(basename($modulesubdir),'/').'[^\-]+', '\.meta$|\.png$'); // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files) // For ajax treatment @@ -721,7 +801,7 @@ class FormFile if (! empty($file_list)) { $out='
    '.$langs->trans("None").'
    '; + $out.=''; + $out.=$file->label; + $out.=''; + $out.=''; + $out.=dol_print_date($file->datea,'dayhour'); + $out.='
    '.$langs->trans("None").'
    '; print ''; print_liste_field_titre($langs->trans("Documents2"),$url,"name","",$param,'align="left"',$sortfield,$sortorder); @@ -851,7 +957,6 @@ class FormFile { $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 == 'member') $relativepath=get_exdir($object->id,2,0,0,$object,'member').$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 @@ -860,6 +965,9 @@ class FormFile $relativepath=preg_replace('/^.*\/produit\//','',$file['path']).'/'; } $var=!$var; + + $editline=0; + print ''; print '\n"; print ''; @@ -907,55 +1025,61 @@ class FormFile else print ' '; print ''; } - // Delete or view link - // ($param must start with &) - print '"; + } else { - if (image_format_supported($file['name']) > 0) - { - $permtoedit=0; - $newmodulepart=$modulepart; - if ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service') - { - if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoedit=1; - if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoedit=1; - $newmodulepart='produit|service'; - } - /* TODO Not yet working - if ($modulepart == 'holiday') - { - if ($user->rights->holiday->write_all) $permtoedit=1; - } - */ - - if (empty($conf->global->MAIN_UPLOAD_DOC)) $permtoedit=0; - - if ($permtoedit) - { - // Link to resize - print ''.img_picto($langs->trans("Resize"),DOL_URL_ROOT.'/theme/common/transform-crop-and-resize','',1).'   '; - } - } + print ''; } - if ($permtodelete) - { - /* - 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; - - print ''.img_delete().''; - } - else print ' '; - print ""; print "\n"; } } @@ -967,7 +1091,11 @@ class FormFile print ''; } print "
    '; @@ -880,10 +988,20 @@ class FormFile print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' '; if ($showrelpart == 1) print $relativepath; //print dol_trunc($file['name'],$maxlength,'middle'); - print $file['name']; - print ''; + if (GETPOST('action') == 'editfile' && $file['name'] == basename(GETPOST('urlfile'))) + { + print ''; + print ''; + print ''; + $editline=1; + } + else + { + print $file['name']; + print ''; + } - print $this->showPreview($file,$modulepart,$filepath); + if (! $editline) print $this->showPreview($file,$modulepart,$filepath); print "'.dol_print_size($file['size'],1,1).''; - if ($useinecm) print ''.img_view().'   '; + 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'; + + $disablecrop=1; + if (in_array($modulepart, array('product','produit','service','holiday','project'))) $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 ($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; + + print ''.img_delete().''; + } + print "'; + print ''; + print ''; + print '
    "; - + if (GETPOST('action') == 'editfile' && $permtoeditline) + { + print '
    '; + } + return $nboffiles; } } @@ -1077,6 +1205,11 @@ class FormFile 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) @@ -1107,6 +1240,7 @@ class FormFile 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; @@ -1361,13 +1495,16 @@ class FormFile global $langs, $conf; $out=''; - $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath); - if ($urladvancedpreview) + if ($conf->browser->layout != 'phone') { - $out.= ''; - if (empty($ruleforpicto)) $out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail'); - else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']); - $out.= ''; + $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath); // Return if a file is qualified for preview + if ($urladvancedpreview) + { + $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 c92229cf036..47cc7cd9d89 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -269,6 +269,7 @@ class FormMail extends Form $listofnames=array(); $listofmimes=array(); $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined + 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]); @@ -369,29 +370,52 @@ class FormMail extends Form $out.= ''; $out.= ''; $out.= ''.$langs->trans("MailFrom").''; - if ($this->fromtype == 'user' && $this->fromid > 0) - { - $langs->load("users"); - $fuser=new User($this->db); - $fuser->fetch($this->fromid); - $out.= $fuser->getNomUrl(1); - } - else - { - $out.= $this->fromname; - } - if ($this->frommail) - { - $out.= " <".$this->frommail.">"; - } - else - { - if ($this->fromtype) - { - $langs->load("errors"); - $out.= ' <'.$langs->trans("ErrorNoMailDefinedForThisUser").'> '; - } - } + + if (! ($this->fromtype === 'user' && $this->fromid > 0) + && ! ($this->fromtype === 'company') + && ! preg_match('/user_aliases/', $this->fromtype) + && ! preg_match('/global_aliases/', $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(); + $liste['user'] = $user->getFullName($langs) .' <'.$user->email.'>'; + $liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + // Add also email aliases if there is one + $listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + 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); + } + $out.= "\n"; $out.= "\n"; } @@ -642,7 +666,7 @@ class FormMail extends Form if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) $out.= ''; else $out.= ''; $out.= ' '; - $out.= ''; + $out.= ''; } } else diff --git a/htdocs/core/class/html.formmargin.class.php b/htdocs/core/class/html.formmargin.class.php index 6678d87ca60..0ac6012f271 100644 --- a/htdocs/core/class/html.formmargin.class.php +++ b/htdocs/core/class/html.formmargin.class.php @@ -209,7 +209,7 @@ class FormMargin if (!empty($hidemargininfos)) print ''; } - print ''; + print '
    '; print ''; print ''; print ''; diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index 26ddd33f0a2..4ac3eb99c50 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -409,7 +409,7 @@ class FormOther $sql_usr.= " WHERE u2.entity IN (0,".$conf->entity.")"; $sql_usr.= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->societe_id; } - $sql_usr.= " ORDER BY lastname ASC"; + $sql_usr.= " ORDER BY u.statut DESC, lastname ASC"; //print $sql_usr;exit; $resql_usr = $this->db->query($sql_usr); @@ -948,14 +948,11 @@ class FormOther print ''; print ''; print ''; - print '
    '.$langs->trans('Margins').''.$langs->trans('SellingPrice').'
    '; - print ''; - print '
    '; $form->select_address($selected, $socid, $htmlname, 1); - print ''; + print ''; $langs->load("companies"); print '   '.$langs->trans("AddAddress").''; - print '
    '; + print ''; } else { @@ -1025,7 +1022,7 @@ class FormOther //var_dump($boxidactivatedforuser); // Class Form must have been already loaded - $selectboxlist.='
    '; + $selectboxlist.=''; $selectboxlist.=''; $selectboxlist.=''; $selectboxlist.=''; @@ -1033,6 +1030,7 @@ class FormOther $selectboxlist.=Form::selectarray('boxcombo', $arrayboxtoactivatelabel, '', $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, ' disabled hidden selected'); if (empty($conf->use_javascript_ajax)) $selectboxlist.=' '; $selectboxlist.='
    '; + //$selectboxlist.=ajax_combobox("boxcombo"); } // Javascript code for dynamic actions diff --git a/htdocs/core/class/html.formprojet.class.php b/htdocs/core/class/html.formprojet.class.php index 4c4c1486d51..742bc1a0231 100644 --- a/htdocs/core/class/html.formprojet.class.php +++ b/htdocs/core/class/html.formprojet.class.php @@ -44,11 +44,11 @@ class FormProjets } /** - * Output a combo list with projects qualified for a third party + * Output a combo list with projects qualified for a third party / user * * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id) * @param int $selected Id project preselected - * @param string $htmlname Nom de la zone html + * @param string $htmlname Name of HTML field * @param int $maxlength Maximum length of label * @param int $option_only Return only html options lines without the select tag * @param int $show_empty Add an empty line @@ -57,12 +57,16 @@ class FormProjets * @param int $disabled Disabled * @param int $mode 0 for HTML mode and 1 for JSON mode * @param string $filterkey Key to filter - * @return int Nber of project if OK, <0 if KO + * @param int $nooutput No print output. Return it only. + * @param int $forceaddid Force to add project id in list, event if not qualified + * @return string Return html content */ - function select_projects($socid=-1, $selected='', $htmlname='projectid', $maxlength=16, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode = 0, $filterkey = '') + function select_projects($socid=-1, $selected='', $htmlname='projectid', $maxlength=16, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode = 0, $filterkey = '', $nooutput=0, $forceaddid=0) { global $langs,$conf,$form; + $out=''; + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) { $placeholder=''; @@ -75,26 +79,33 @@ class FormProjets $selected_input_value=$project->ref; } $urloption='socid='.$socid.'&htmlname='.$htmlname; - print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array( + $out.=ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array( // 'update' => array( // 'projectid' => 'id' // ) )); - print ''; + $out.=''; } else { - print $this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey); + $out.=$this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1); if ($discard_closed) { if (class_exists('Form')) { if (empty($form)) $form=new Form($this->db); - print $form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden")); + $out.=$form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden")); } } } + + if (empty($nooutput)) + { + print $out; + return ''; + } + else return $out; } /** @@ -111,9 +122,11 @@ class FormProjets * @param int $disabled Disabled * @param int $mode 0 for HTML mode and 1 for array return (to be used by json_encode for example) * @param string $filterkey Key to filter + * @param int $nooutput No print output. Return it only. + * @param int $forceaddid Force to add project id in list, event if not qualified * @return int Nb of project if OK, <0 if KO */ - function select_projects_list($socid=-1, $selected='', $htmlname='projectid', $maxlength=24, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode=0, $filterkey = '') + function select_projects_list($socid=-1, $selected='', $htmlname='projectid', $maxlength=24, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode=0, $filterkey = '', $nooutput=0, $forceaddid=0) { global $user,$conf,$langs; @@ -132,6 +145,7 @@ class FormProjets $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1); } + // Search all projects $sql = 'SELECT p.rowid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public'; $sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p'; @@ -250,10 +264,13 @@ class FormProjets $this->db->free($resql); if (!$mode) { - if (empty($option_only)) { - $out.= ''; + if (empty($option_only)) $out.= ''; + if (empty($nooutput)) + { + print $out; + return ''; } - print $out; + else return $out; } else { return $outarray; } diff --git a/htdocs/core/class/html.formpropal.class.php b/htdocs/core/class/html.formpropal.class.php index 57dd6336a43..2cfeaadd368 100644 --- a/htdocs/core/class/html.formpropal.class.php +++ b/htdocs/core/class/html.formpropal.class.php @@ -50,9 +50,10 @@ class FormPropal * @param int $excludedraft 0=All status, 1=Exclude draft status * @param int $showempty 1=Add empty line * @param string $mode 'customer', 'supplier' + * @param string $htmlname Name of select field * @return void */ - function selectProposalStatus($selected='',$short=0, $excludedraft=0, $showempty=1, $mode='customer') + function selectProposalStatus($selected='',$short=0, $excludedraft=0, $showempty=1, $mode='customer',$htmlname='propal_statut') { global $langs; @@ -63,7 +64,13 @@ class FormPropal $prefix='SupplierProposalStatus'; $langs->load("supplier_proposal"); - $listofstatus=array(0=>array('code'=>'PR_DRAFT'), 1=>array('code'=>'PR_OPEN'), 2=>array('code'=>'PR_SIGNED'), 3=>array('code'=>'PR_NOTSIGNED'), 4=>array('code'=>'PR_CLOSED')); + $listofstatus=array( + 0=>array('id'=>0, 'code'=>'PR_DRAFT'), + 1=>array('id'=>1, 'code'=>'PR_OPEN'), + 2=>array('id'=>2, 'code'=>'PR_SIGNED'), + 3=>array('id'=>3, 'code'=>'PR_NOTSIGNED'), + 4=>array('id'=>4, 'code'=>'PR_CLOSED') + ); } else { @@ -93,7 +100,7 @@ class FormPropal } } - print ''; if ($showempty) print ''; foreach($listofstatus as $key => $obj) @@ -115,15 +122,16 @@ class FormPropal print ''; $i++; diff --git a/htdocs/core/class/html.formsms.class.php b/htdocs/core/class/html.formsms.class.php index 35736b56228..b2802f91c09 100644 --- a/htdocs/core/class/html.formsms.class.php +++ b/htdocs/core/class/html.formsms.class.php @@ -85,10 +85,11 @@ class FormSms /** * Show the form to input an sms. * - * @param string $width Width of form + * @param string $morecss Class on first column td + * @param int $showform Show form tags and submit button (recommanded is to use with value 0) * @return void */ - function show_form($width='180px') + function show_form($morecss='titlefield', $showform=1) { global $conf, $langs, $user, $form; @@ -119,13 +120,14 @@ function limitChars(textarea, limit, infodiv) } '; - print "
    param["returnurl"]."\">\n"; + if ($showform) print "param["returnurl"]."\">\n"; + print ''; foreach ($this->param as $key=>$value) { print "\n"; } - print "\n"; + print "
    \n"; // Substitution array if ($this->withsubstit) @@ -145,8 +147,9 @@ function limitChars(textarea, limit, infodiv) { if ($this->withfromreadonly) { + print '
    '.$langs->trans("SmsFrom"); print ''; - print "
    ".$langs->trans("SmsFrom").""; + print ""; if ($this->fromtype == 'user') { $langs->load("users"); @@ -172,7 +175,7 @@ function limitChars(textarea, limit, infodiv) } else { - print "
    ".$langs->trans("SmsFrom").""; + print '
    '.$langs->trans("SmsFrom").""; //print ''; if ($conf->global->MAIN_SMS_SENDMODE == 'ovh') // For backward compatibility @deprecated { @@ -320,16 +323,21 @@ function limitChars(textarea, limit, infodiv) print "
    \n"; - print '
    '; - print ''; - if ($this->withcancel) + + if ($showform) { - print '     '; - print ''; + print '
    '; + print ''; + if ($this->withcancel) + { + print '     '; + print ''; + } + print '
    '; + + print "\n"; } - print '
    '; - - print "\n"; + print "\n"; } diff --git a/htdocs/core/class/html.formsupplier_proposal.class.php b/htdocs/core/class/html.formsupplier_proposal.class.php deleted file mode 100644 index ed8781731a0..00000000000 --- a/htdocs/core/class/html.formsupplier_proposal.class.php +++ /dev/null @@ -1,104 +0,0 @@ - - * - * 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/class/html.formpropal.class.php - * \ingroup core - * \brief File of class with all html predefined components - */ - - -/** - * Class to manage generation of HTML components for proposal management - */ -class FormSupplierProposal -{ - var $db; - var $error; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } - - /** - * Return combo list of differents status of a proposal - * Values are id of table c_propalst - * - * @param string $selected Preselected value - * @param int $short Use short labels - * @return void - */ - function selectSupplierProposalStatus($selected='',$short=0) - { - global $langs; - - $sql = "SELECT id, code, label, active FROM ".MAIN_DB_PREFIX."c_propalst"; - $sql .= " WHERE active = 1"; - - dol_syslog(get_class($this)."::selectSupplierProposalStatus", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - print ''; - } - else - { - dol_print_error($this->db); - } - } - -} - diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php index 9021a5d5846..95eeb1cdc5b 100644 --- a/htdocs/core/class/notify.class.php +++ b/htdocs/core/class/notify.class.php @@ -44,6 +44,21 @@ class Notify // Les codes actions sont definis dans la table llx_notify_def + // codes actions supported are + public $arrayofnotifsupported = array( + 'BILL_VALIDATE', + 'BILL_PAYED', + 'ORDER_VALIDATE', + 'PROPAL_VALIDATE', + 'FICHINTER_VALIDATE', + 'FICHINTER_ADD_CONTACT', + 'ORDER_SUPPLIER_VALIDATE', + 'ORDER_SUPPLIER_APPROVE', + 'ORDER_SUPPLIER_REFUSE', + 'SHIPPING_VALIDATE' + ); + + /** * Constructor * @@ -265,9 +280,11 @@ class Notify { global $user,$conf,$langs,$mysoc,$dolibarr_main_url_root; - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + if (! in_array($notifcode, $this->arrayofnotifsupported)) return 0; - dol_syslog(get_class($this)."::send notifcode=".$notifcode.", object=".$object->id); + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + + dol_syslog(get_class($this)."::send notifcode=".$notifcode.", object=".$object->id); $langs->load("other"); @@ -286,26 +303,6 @@ class Notify $link = ''; $num = 0; - if (! in_array( - $notifcode, - array( - 'BILL_VALIDATE', - 'BILL_PAYED', - 'ORDER_VALIDATE', - 'PROPAL_VALIDATE', - 'FICHINTER_VALIDATE', - 'FICHINTER_ADD_CONTACT', - 'ORDER_SUPPLIER_VALIDATE', - 'ORDER_SUPPLIER_APPROVE', - 'ORDER_SUPPLIER_REFUSE', - 'SHIPPING_VALIDATE' - ) - ) - ) - { - return 0; - } - $oldref=(empty($object->oldref)?$object->ref:$object->oldref); $newref=(empty($object->newref)?$object->ref:$object->newref); diff --git a/htdocs/core/class/smtps.class.php b/htdocs/core/class/smtps.class.php index 83e30a05413..39a45ad783b 100644 --- a/htdocs/core/class/smtps.class.php +++ b/htdocs/core/class/smtps.class.php @@ -396,6 +396,11 @@ class SMTPs $host=$this->getHost(); $host=preg_replace('@tcp://@i','',$host); // Remove prefix $host=preg_replace('@ssl://@i','',$host); // Remove prefix + if (!empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS)) + { + $host=preg_replace('@tls://@i','',$host); // Remove prefix + $host='tls://'.$host; + } if ( $_retVal = $this->socket_send_str('EHLO ' . $host, '250') ) { if (!empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS)) diff --git a/htdocs/core/class/utils.class.php b/htdocs/core/class/utils.class.php index dd4096c5257..6f01a4c1406 100644 --- a/htdocs/core/class/utils.class.php +++ b/htdocs/core/class/utils.class.php @@ -168,7 +168,7 @@ class Utils // Check type parameter if ($type == 'auto') $type = $db->type; - if (! in_array($type, array('pgsql', 'mysql', 'mysqli'))) + if (! in_array($type, array('pgsql', 'mysql', 'mysqli','mysqlnobin'))) { $langs->load("errors"); $this->error=$langs->transnoentitiesnoconv("ErrorBadValueForParameter", $type, "Basetype"); @@ -268,7 +268,8 @@ class Utils { $i++; // output line number $read = fgets($handlein); - if ($i == 1 && preg_match('/'.preg_quote('Warning: Using a password').'/i', $read)) continue; + // Exclude warning line we don't want + if ($i == 1 && preg_match('/Warning.*Using a password/i', $read)) continue; fwrite($handle,$read); if (preg_match('/'.preg_quote('-- Dump completed').'/i',$read)) $ok=1; elseif (preg_match('/'.preg_quote('SET SQL_NOTES=@OLD_SQL_NOTES').'/i',$read)) $ok=1; diff --git a/htdocs/core/db/sqlite.class.php b/htdocs/core/db/sqlite.class.php deleted file mode 100644 index ef638b0e9fe..00000000000 --- a/htdocs/core/db/sqlite.class.php +++ /dev/null @@ -1,1144 +0,0 @@ - - * Copyright (C) 2002-2005 Rodolphe Quiedeville - * Copyright (C) 2004-2011 Laurent Destailleur - * Copyright (C) 2006 Andre Cianfarani - * Copyright (C) 2005-2009 Regis Houssin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * 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/db/sqlite.class.php - * \brief Class file to manage Dolibarr database access for a Sqlite database - */ - -require_once DOL_DOCUMENT_ROOT .'/core/db/DoliDB.class.php'; - -/** - * Class to manage Dolibarr database access for a Sqlite database - */ -class DoliDBSqlite extends DoliDB -{ - //! Database type - public $type='sqlite'; - //! Database label - const LABEL='PDO Sqlite'; - //! Version min database - const VERSIONMIN='3.0.0'; - /** @var PDOStatement Resultset of last query */ - private $_results; - - /** - * Constructor. - * This create an opened connexion to a database server and eventually to a database - * - * @param string $type Type of database (mysql, pgsql...) - * @param string $host Address of database server - * @param string $user Nom de l'utilisateur autorise - * @param string $pass Mot de passe - * @param string $name Nom de la database - * @param int $port Port of database server - * @return int 1 if OK, 0 if not - */ - function __construct($type, $host, $user, $pass, $name='', $port=0) - { - global $conf; - - // Note that having "static" property for "$forcecharset" and "$forcecollate" will make error here in strict mode, so they are not static - if (! empty($conf->db->character_set)) $this->forcecharset=$conf->db->character_set; - if (! empty($conf->db->dolibarr_main_db_collation)) $this->forcecollate=$conf->db->dolibarr_main_db_collation; - - $this->database_user=$user; - $this->database_host=$host; - $this->database_port=$port; - - $this->transaction_opened=0; - - //print "Name DB: $host,$user,$pass,$name
    "; - - /*if (! function_exists("sqlite_query")) - { - $this->connected = false; - $this->ok = false; - $this->error="Sqlite PHP functions for using Sqlite driver are not available in this version of PHP. Try to use another driver."; - dol_syslog(get_class($this)."::DoliDBSqlite : Sqlite PHP functions for using Sqlite driver are not available in this version of PHP. Try to use another driver.",LOG_ERR); - return $this->ok; - }*/ - - /*if (! $host) - { - $this->connected = false; - $this->ok = false; - $this->error=$langs->trans("ErrorWrongHostParameter"); - dol_syslog(get_class($this)."::DoliDBSqlite : Erreur Connect, wrong host parameters",LOG_ERR); - return $this->ok; - }*/ - - // Essai connexion serveur - // We do not try to connect to database, only to server. Connect to database is done later in constrcutor - $this->db = $this->connect($host, $user, $pass, $name, $port); - - if ($this->db) - { - $this->connected = true; - $this->ok = true; - $this->database_selected = true; - $this->database_name = $name; - - $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - else - { - // host, login ou password incorrect - $this->connected = false; - $this->ok = false; - $this->database_selected = false; - $this->database_name = ''; - //$this->error=sqlite_connect_error(); - dol_syslog(get_class($this)."::DoliDBSqlite : Erreur Connect ".$this->error,LOG_ERR); - } - - return (int) $this->ok; - } - - - /** - * Convert a SQL request in Mysql syntax to native syntax - * - * @param string $line SQL request line to convert - * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...) - * @return string SQL request line converted - */ - static function convertSQLFromMysql($line,$type='ddl') - { - // Removed empty line if this is a comment line for SVN tagging - if (preg_match('/^--\s\$Id/i',$line)) { - return ''; - } - // Return line if this is a comment - if (preg_match('/^#/i',$line) || preg_match('/^$/i',$line) || preg_match('/^--/i',$line)) - { - return $line; - } - if ($line != "") - { - if ($type == 'auto') - { - if (preg_match('/ALTER TABLE/i',$line)) $type='dml'; - else if (preg_match('/CREATE TABLE/i',$line)) $type='dml'; - else if (preg_match('/DROP TABLE/i',$line)) $type='dml'; - } - - if ($type == 'dml') - { - $line=preg_replace('/\s/',' ',$line); // Replace tabulation with space - - // we are inside create table statement so lets process datatypes - if (preg_match('/(ISAM|innodb)/i',$line)) { // end of create table sequence - $line=preg_replace('/\)[\s\t]*type[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line); - $line=preg_replace('/\)[\s\t]*engine[\s\t]*=[\s\t]*(MyISAM|innodb);/i',');',$line); - $line=preg_replace('/,$/','',$line); - } - - // Process case: "CREATE TABLE llx_mytable(rowid integer NOT NULL AUTO_INCREMENT PRIMARY KEY,code..." - if (preg_match('/[\s\t\(]*(\w*)[\s\t]+int.*auto_increment/i',$line,$reg)) { - $newline=preg_replace('/([\s\t\(]*)([a-zA-Z_0-9]*)[\s\t]+int.*auto_increment[^,]*/i','\\1 \\2 SERIAL PRIMARY KEY',$line); - //$line = "-- ".$line." replaced by --\n".$newline; - $line=$newline; - } - - // tinyint type conversion - $line=str_replace('tinyint','smallint',$line); - - // nuke unsigned - $line=preg_replace('/(int\w+|smallint)\s+unsigned/i','\\1',$line); - - // blob -> text - $line=preg_replace('/\w*blob/i','text',$line); - - // tinytext/mediumtext -> text - $line=preg_replace('/tinytext/i','text',$line); - $line=preg_replace('/mediumtext/i','text',$line); - - // change not null datetime field to null valid ones - // (to support remapping of "zero time" to null - $line=preg_replace('/datetime not null/i','datetime',$line); - $line=preg_replace('/datetime/i','timestamp',$line); - - // double -> numeric - $line=preg_replace('/^double/i','numeric',$line); - $line=preg_replace('/(\s*)double/i','\\1numeric',$line); - // float -> numeric - $line=preg_replace('/^float/i','numeric',$line); - $line=preg_replace('/(\s*)float/i','\\1numeric',$line); - - // unique index(field1,field2) - if (preg_match('/unique index\s*\((\w+\s*,\s*\w+)\)/i',$line)) - { - $line=preg_replace('/unique index\s*\((\w+\s*,\s*\w+)\)/i','UNIQUE\(\\1\)',$line); - } - - // We remove end of requests "AFTER fieldxxx" - $line=preg_replace('/AFTER [a-z0-9_]+/i','',$line); - - // We remove start of requests "ALTER TABLE tablexxx" if this is a DROP INDEX - $line=preg_replace('/ALTER TABLE [a-z0-9_]+ DROP INDEX/i','DROP INDEX',$line); - - // Translate order to rename fields - if (preg_match('/ALTER TABLE ([a-z0-9_]+) CHANGE(?: COLUMN)? ([a-z0-9_]+) ([a-z0-9_]+)(.*)$/i',$line,$reg)) - { - $line = "-- ".$line." replaced by --\n"; - $line.= "ALTER TABLE ".$reg[1]." RENAME COLUMN ".$reg[2]." TO ".$reg[3]; - } - - // Translate order to modify field format - if (preg_match('/ALTER TABLE ([a-z0-9_]+) MODIFY(?: COLUMN)? ([a-z0-9_]+) (.*)$/i',$line,$reg)) - { - $line = "-- ".$line." replaced by --\n"; - $newreg3=$reg[3]; - $newreg3=preg_replace('/ DEFAULT NULL/i','',$newreg3); - $newreg3=preg_replace('/ NOT NULL/i','',$newreg3); - $newreg3=preg_replace('/ NULL/i','',$newreg3); - $newreg3=preg_replace('/ DEFAULT 0/i','',$newreg3); - $newreg3=preg_replace('/ DEFAULT \'[0-9a-zA-Z_@]*\'/i','',$newreg3); - $line.= "ALTER TABLE ".$reg[1]." ALTER COLUMN ".$reg[2]." TYPE ".$newreg3; - // TODO Add alter to set default value or null/not null if there is this in $reg[3] - } - - // alter table add primary key (field1, field2 ...) -> We create a unique index instead as dynamic creation of primary key is not supported - // ALTER TABLE llx_dolibarr_modules ADD PRIMARY KEY pk_dolibarr_modules (numero, entity); - if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+PRIMARY\s+KEY\s*(.*)\s*\((.*)$/i',$line,$reg)) - { - $line = "-- ".$line." replaced by --\n"; - $line.= "CREATE UNIQUE INDEX ".$reg[2]." ON ".$reg[1]."(".$reg[3]; - } - - // 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)) - { - $line = "-- ".$line." replaced by --\n"; - $line.= "ALTER TABLE ".$reg[1]." DROP CONSTRAINT ".$reg[2]; - } - - // alter table add [unique] [index] (field1, field2 ...) - // ALTER TABLE llx_accountingaccount ADD INDEX idx_accountingaccount_fk_pcg_version (fk_pcg_version) - if (preg_match('/ALTER\s+TABLE\s*(.*)\s*ADD\s+(UNIQUE INDEX|INDEX|UNIQUE)\s+(.*)\s*\(([\w,\s]+)\)/i',$line,$reg)) - { - $fieldlist=$reg[4]; - $idxname=$reg[3]; - $tablename=$reg[1]; - $line = "-- ".$line." replaced by --\n"; - $line.= "CREATE ".(preg_match('/UNIQUE/',$reg[2])?'UNIQUE ':'')."INDEX ".$idxname." ON ".$tablename." (".$fieldlist.")"; - } - } - - // To have postgresql case sensitive - $line=str_replace(' LIKE \'',' ILIKE \'',$line); - - // Delete using criteria on other table must not declare twice the deleted table - // DELETE FROM tabletodelete USING tabletodelete, othertable -> DELETE FROM tabletodelete USING othertable - if (preg_match('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i',$line,$reg)) - { - if ($reg[1] == $reg[2]) // If same table, we remove second one - { - $line=preg_replace('/DELETE FROM ([a-z_]+) USING ([a-z_]+), ([a-z_]+)/i','DELETE FROM \\1 USING \\3', $line); - } - } - - // Remove () in the tables in FROM if one table - $line=preg_replace('/FROM\s*\((([a-z_]+)\s+as\s+([a-z_]+)\s*)\)/i','FROM \\1',$line); - //print $line."\n"; - - // Remove () in the tables in FROM if two table - $line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2',$line); - //print $line."\n"; - - // Remove () in the tables in FROM if two table - $line=preg_replace('/FROM\s*\(([a-z_]+\s+as\s+[a-z_]+)\s*,\s*([a-z_]+\s+as\s+[a-z_]+\s*),\s*([a-z_]+\s+as\s+[a-z_]+\s*)\)/i','FROM \\1, \\2, \\3',$line); - //print $line."\n"; - - //print "type=".$type." newline=".$line."
    \n"; - } - - return $line; - } - - /** - * Select a database - * - * @param string $database Name of database - * @return boolean true if OK, false if KO - */ - function select_db($database) - { - dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG); - // FIXME: sqlite_select_db() does not exist - return sqlite_select_db($this->db,$database); - } - - - /** - * Connexion to server - * - * @param string $host database server host - * @param string $login login - * @param string $passwd password - * @param string $name name of database (not used for mysql, used for pgsql) - * @param integer $port Port of database server - * @return PDO Database access handler - * @see close - */ - function connect($host, $login, $passwd, $name, $port=0) - { - global $main_data_dir; - - dol_syslog(get_class($this)."::connect name=".$name,LOG_DEBUG); - - $dir=$main_data_dir; - if (empty($dir)) $dir=DOL_DATA_ROOT; - // With sqlite, port must be in connect parameters - //if (! $newport) $newport=3306; - try { - /*** connect to SQLite database ***/ - $this->db = new PDO("sqlite:".$dir.'/database_'.$name.'.sdb'); - $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - catch(PDOException $e) - { - $this->error='PDO SQLITE '.$e->getMessage().' current dir='.$dir.'/database_'.$name.'.sdb'; - return ''; - } - - //print "Resultat fonction connect: ".$this->db; - return $this->db; - } - - - /** - * Return version of database server - * - * @return string Version string - */ - function getVersion() - { - $resql=$this->query('SELECT sqlite_version() as sqliteversion'); - $row=$this->fetch_row($resql); - return $row[0]; - } - - /** - * Return version of database client driver - * - * @return string Version string - */ - function getDriverInfo() - { - return 'sqlite php driver'; - } - - - /** - * Close database connexion - * - * @return bool True if disconnect successfull, false otherwise - * @see connect - */ - function close() - { - if ($this->db) - { - if ($this->transaction_opened > 0) dol_syslog(get_class($this)."::close Closing a connection with an opened transaction depth=".$this->transaction_opened,LOG_ERR); - $this->connected=false; - $this->db=null; // Clean this->db - return true; - } - return false; - } - - /** - * Execute a SQL request and return the resultset - * - * @param string $query SQL query string - * @param int $usesavepoint 0=Default mode, 1=Run a savepoint before and a rollbock to savepoint if error (this allow to have some request with errors inside global transactions). - * Note that with Mysql, this parameter is not used as Myssql can already commit a transaction even if one request is in error, without using savepoints. - * @param string $type Type of SQL order ('ddl' for insert, update, select, delete or 'dml' for create, alter...) - * @return PDOStatement Resultset of answer - */ - function query($query,$usesavepoint=0,$type='auto') - { - $ret=null; - $query = trim($query); - $this->error = 0; - - // Convert MySQL syntax to SQLite syntax - $query=$this->convertSQLFromMysql($query,$type); - //print "After convertSQLFromMysql:\n".$query."
    \n"; - - dol_syslog('sql='.$query, LOG_DEBUG); - - // Ordre SQL ne necessitant pas de connexion a une base (exemple: CREATE DATABASE) - try { - //$ret = $this->db->exec($query); - $ret = $this->db->query($query); // $ret is a PDO object - } - catch(PDOException $e) - { - $this->error=$e->getMessage(); - } - - if (! preg_match("/^COMMIT/i",$query) && ! preg_match("/^ROLLBACK/i",$query)) - { - // Si requete utilisateur, on la sauvegarde ainsi que son resultset - if (! is_object($ret) || $this->error) - { - $this->lastqueryerror = $query; - $this->lasterror = $this->error(); - $this->lasterrno = $this->errno(); - - dol_syslog(get_class($this)."::query SQL Error query: ".$query, LOG_ERR); - - $errormsg = get_class($this)."::query SQL Error message: ".$this->lasterror; - - if (preg_match('/[0-9]/',$this->lasterrno)) { - $errormsg .= ' ('.$this->lasterrno.')'; - } - - dol_syslog($errormsg, LOG_ERR); - } - $this->lastquery=$query; - $this->_results = $ret; - } - - return $ret; - } - - /** - * Renvoie la ligne courante (comme un objet) pour le curseur resultset - * - * @param PDOStatement $resultset Curseur de la requete voulue - * @return false|object Object result line or false if KO or end of cursor - */ - function fetch_object($resultset) - { - // Si le resultset n'est pas fourni, on prend le dernier utilise sur cette connexion - if (! is_object($resultset)) { $resultset=$this->_results; } - return $resultset->fetch(PDO::FETCH_OBJ); - } - - - /** - * Return datas as an array - * - * @param PDOStatement $resultset Resultset of request - * @return false|array Array or false if KO or end of cursor - */ - function fetch_array($resultset) - { - // If resultset not provided, we take the last used by connexion - if (! is_object($resultset)) { $resultset=$this->_results; } - return $resultset->fetch(PDO::FETCH_ASSOC); - } - - /** - * Return datas as an array - * - * @param PDOStatement $resultset Resultset of request - * @return false|array Array or false if KO or end of cursor - */ - function fetch_row($resultset) - { - // If resultset not provided, we take the last used by connexion - if (! is_bool($resultset)) - { - if (! is_object($resultset)) { $resultset=$this->_results; } - return $resultset->fetch(PDO::FETCH_NUM); - } - else - { - // si le curseur est un booleen on retourne la valeur 0 - return 0; - } - } - - /** - * Return number of lines for result of a SELECT - * - * @param PDOStatement $resultset Resulset of requests - * @return int Nb of lines - * @see affected_rows - */ - function num_rows($resultset) - { - // If resultset not provided, we take the last used by connexion - if (! is_object($resultset)) { $resultset=$this->_results; } - return $resultset->rowCount(); - } - - /** - * Return number of lines for result of a SELECT - * - * @param PDOStatement $resultset Resulset of requests - * @return int Nb of lines - * @see affected_rows - */ - function affected_rows($resultset) - { - // If resultset not provided, we take the last used by connexion - if (! is_object($resultset)) { $resultset=$this->_results; } - // mysql necessite un link de base pour cette fonction contrairement - // a pqsql qui prend un resultset - return $resultset->rowCount(); - } - - - /** - * Free last resultset used. - * - * @param PDOStatement $resultset Curseur de la requete voulue - * @return void - */ - function free($resultset=null) - { - // If resultset not provided, we take the last used by connexion - if (! is_object($resultset)) { $resultset=$this->_results; } - // Si resultset en est un, on libere la memoire - if (is_object($resultset)) $resultset->closeCursor(); - } - - /** - * Escape a string to insert data - * - * @param string $stringtoencode String to escape - * @return string String escaped - */ - function escape($stringtoencode) - { - return $this->db->quote($stringtoencode); - } - - /** - * Renvoie le code erreur generique de l'operation precedente. - * - * @return string Error code (Exemples: DB_ERROR_TABLE_ALREADY_EXISTS, DB_ERROR_RECORD_ALREADY_EXISTS...) - */ - function errno() - { - if (! $this->connected) { - // Si il y a eu echec de connexion, $this->db n'est pas valide. - return 'DB_ERROR_FAILED_TO_CONNECT'; - } - else { - // Constants to convert error code to a generic Dolibarr error code - /*$errorcode_map = array( - 1004 => 'DB_ERROR_CANNOT_CREATE', - 1005 => 'DB_ERROR_CANNOT_CREATE', - 1006 => 'DB_ERROR_CANNOT_CREATE', - 1007 => 'DB_ERROR_ALREADY_EXISTS', - 1008 => 'DB_ERROR_CANNOT_DROP', - 1025 => 'DB_ERROR_NO_FOREIGN_KEY_TO_DROP', - 1044 => 'DB_ERROR_ACCESSDENIED', - 1046 => 'DB_ERROR_NODBSELECTED', - 1048 => 'DB_ERROR_CONSTRAINT', - 'HY000' => 'DB_ERROR_TABLE_ALREADY_EXISTS', - 1051 => 'DB_ERROR_NOSUCHTABLE', - 1054 => 'DB_ERROR_NOSUCHFIELD', - 1060 => 'DB_ERROR_COLUMN_ALREADY_EXISTS', - 1061 => 'DB_ERROR_KEY_NAME_ALREADY_EXISTS', - 1062 => 'DB_ERROR_RECORD_ALREADY_EXISTS', - 1064 => 'DB_ERROR_SYNTAX', - 1068 => 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS', - 1075 => 'DB_ERROR_CANT_DROP_PRIMARY_KEY', - 1091 => 'DB_ERROR_NOSUCHFIELD', - 1100 => 'DB_ERROR_NOT_LOCKED', - 1136 => 'DB_ERROR_VALUE_COUNT_ON_ROW', - 1146 => 'DB_ERROR_NOSUCHTABLE', - 1216 => 'DB_ERROR_NO_PARENT', - 1217 => 'DB_ERROR_CHILD_EXISTS', - 1451 => 'DB_ERROR_CHILD_EXISTS' - ); - - if (isset($errorcode_map[$this->db->errorCode()])) - { - return $errorcode_map[$this->db->errorCode()]; - }*/ - $errno=$this->db->errorCode(); - if ($errno=='HY000') - { - if (preg_match('/table.*already exists/i',$this->error)) return 'DB_ERROR_TABLE_ALREADY_EXISTS'; - elseif (preg_match('/index.*already exists/i',$this->error)) return 'DB_ERROR_KEY_NAME_ALREADY_EXISTS'; - elseif (preg_match('/syntax error/i',$this->error)) return 'DB_ERROR_SYNTAX'; - } - if ($errno=='23000') - { - if (preg_match('/column.* not unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS'; - elseif (preg_match('/PRIMARY KEY must be unique/i',$this->error)) return 'DB_ERROR_RECORD_ALREADY_EXISTS'; - } - - return ($errno?'DB_ERROR_'.$errno:'0'); - } - } - - /** - * Renvoie le texte de l'erreur mysql de l'operation precedente. - * - * @return string Error text - */ - function error() - { - if (! $this->connected) { - // Si il y a eu echec de connexion, $this->db n'est pas valide pour sqlite_error. - return 'Not connected. Check setup parameters in conf/conf.php file and your sqlite version'; - } - else { - return $this->error; - } - } - - /** - * Get last ID after an insert INSERT - * - * @param string $tab Table name concerned by insert. Ne sert pas sous MySql mais requis pour compatibilite avec Postgresql - * @param string $fieldid Field name - * @return int Id of row - */ - function last_insert_id($tab,$fieldid='rowid') - { - return $this->db->lastInsertId(); - } - - /** - * Encrypt sensitive data in database - * Warning: This function includes the escape, so it must use direct value - * - * @param string $fieldorvalue Field name or value to encrypt - * @param int $withQuotes Return string with quotes - * @return string XXX(field) or XXX('value') or field or 'value' - */ - function encrypt($fieldorvalue, $withQuotes=0) - { - global $conf; - - // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption) - $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0); - - //Encryption key - $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:''); - - $return = ($withQuotes?"'":"").$this->escape($fieldorvalue).($withQuotes?"'":""); - - if ($cryptType && !empty($cryptKey)) - { - if ($cryptType == 2) - { - $return = 'AES_ENCRYPT('.$return.',\''.$cryptKey.'\')'; - } - else if ($cryptType == 1) - { - $return = 'DES_ENCRYPT('.$return.',\''.$cryptKey.'\')'; - } - } - - return $return; - } - - /** - * Decrypt sensitive data in database - * - * @param string $value Value to decrypt - * @return string Decrypted value if used - */ - function decrypt($value) - { - global $conf; - - // Type of encryption (2: AES (recommended), 1: DES , 0: no encryption) - $cryptType = ($conf->db->dolibarr_main_db_encryption?$conf->db->dolibarr_main_db_encryption:0); - - //Encryption key - $cryptKey = (!empty($conf->db->dolibarr_main_db_cryptkey)?$conf->db->dolibarr_main_db_cryptkey:''); - - $return = $value; - - if ($cryptType && !empty($cryptKey)) - { - if ($cryptType == 2) - { - $return = 'AES_DECRYPT('.$value.',\''.$cryptKey.'\')'; - } - else if ($cryptType == 1) - { - $return = 'DES_DECRYPT('.$value.',\''.$cryptKey.'\')'; - } - } - - return $return; - } - - - /** - * Return connexion ID - * - * @return string Id connexion - */ - function DDLGetConnectId() - { - return '?'; - } - - - /** - * Create a new database - * Do not use function xxx_create_db (xxx=mysql, ...) as they are deprecated - * We force to create database with charset this->forcecharset and collate this->forcecollate - * - * @param string $database Database name to create - * @param string $charset Charset used to store data - * @param string $collation Charset used to sort data - * @param string $owner Username of database owner - * @return PDOStatement resource defined if OK, null if KO - */ - function DDLCreateDb($database,$charset='',$collation='',$owner='') - { - if (empty($charset)) $charset=$this->forcecharset; - if (empty($collation)) $collation=$this->forcecollate; - - // ALTER DATABASE dolibarr_db DEFAULT CHARACTER SET latin DEFAULT COLLATE latin1_swedish_ci - $sql = 'CREATE DATABASE '.$database; - $sql.= ' DEFAULT CHARACTER SET '.$charset.' DEFAULT COLLATE '.$collation; - - dol_syslog($sql,LOG_DEBUG); - $ret=$this->query($sql); - if (! $ret) - { - // We try again for compatibility with Mysql < 4.1.1 - $sql = 'CREATE DATABASE '.$database; - $ret=$this->query($sql); - dol_syslog($sql,LOG_DEBUG); - } - return $ret; - } - - /** - * List tables into a database - * - * @param string $database Name of database - * @param string $table Name of table filter ('xxx%') - * @return array List of tables in an array - */ - function DDLListTables($database, $table='') - { - $listtables=array(); - - $like = ''; - if ($table) $like = "LIKE '".$table."'"; - $sql="SHOW TABLES FROM ".$database." ".$like.";"; - //print $sql; - $result = $this->query($sql); - if ($result) - { - while($row = $this->fetch_row($result)) - { - $listtables[] = $row[0]; - } - } - return $listtables; - } - - /** - * List information of columns into a table. - * - * @param string $table Name of table - * @return array Tableau des informations des champs de la table - * TODO modify for sqlite - */ - function DDLInfoTable($table) - { - $infotables=array(); - - $sql="SHOW FULL COLUMNS FROM ".$table.";"; - - dol_syslog($sql,LOG_DEBUG); - $result = $this->query($sql); - if ($result) - { - while($row = $this->fetch_row($result)) - { - $infotables[] = $row; - } - } - return $infotables; - } - - /** - * Create a table into database - * - * @param string $table Nom de la table - * @param array $fields Tableau associatif [nom champ][tableau des descriptions] - * @param string $primary_key Nom du champ qui sera la clef primaire - * @param string $type Type de la table - * @param array $unique_keys Tableau associatifs Nom de champs qui seront clef unique => valeur - * @param array $fulltext_keys Tableau des Nom de champs qui seront indexes en fulltext - * @param array $keys Tableau des champs cles noms => valeur - * @return int <0 if KO, >=0 if OK - */ - function DDLCreateTable($table,$fields,$primary_key,$type,$unique_keys=null,$fulltext_keys=null,$keys=null) - { - // FIXME: $fulltext_keys parameter is unused - - // cles recherchees dans le tableau des descriptions (fields) : type,value,attribute,null,default,extra - // ex. : $fields['rowid'] = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment'); - $sql = "create table ".$table."("; - $i=0; - foreach($fields as $field_name => $field_desc) - { - $sqlfields[$i] = $field_name." "; - $sqlfields[$i] .= $field_desc['type']; - if( preg_match("/^[^\s]/i",$field_desc['value'])) - $sqlfields[$i] .= "(".$field_desc['value'].")"; - else if( preg_match("/^[^\s]/i",$field_desc['attribute'])) - $sqlfields[$i] .= " ".$field_desc['attribute']; - else if( preg_match("/^[^\s]/i",$field_desc['default'])) - { - if(preg_match("/null/i",$field_desc['default'])) - $sqlfields[$i] .= " default ".$field_desc['default']; - else - $sqlfields[$i] .= " default '".$field_desc['default']."'"; - } - else if( preg_match("/^[^\s]/i",$field_desc['null'])) - $sqlfields[$i] .= " ".$field_desc['null']; - - else if( preg_match("/^[^\s]/i",$field_desc['extra'])) - $sqlfields[$i] .= " ".$field_desc['extra']; - $i++; - } - if($primary_key != "") - $pk = "primary key(".$primary_key.")"; - - if(is_array($unique_keys)) - { - $i = 0; - foreach($unique_keys as $key => $value) - { - $sqluq[$i] = "UNIQUE KEY '".$key."' ('".$value."')"; - $i++; - } - } - if(is_array($keys)) - { - $i = 0; - foreach($keys as $key => $value) - { - $sqlk[$i] = "KEY ".$key." (".$value.")"; - $i++; - } - } - $sql .= implode(',',$sqlfields); - if($primary_key != "") - $sql .= ",".$pk; - if(is_array($unique_keys)) - $sql .= ",".implode(',',$sqluq); - if(is_array($keys)) - $sql .= ",".implode(',',$sqlk); - $sql .=") type=".$type; - - dol_syslog($sql,LOG_DEBUG); - if(! $this -> query($sql)) - return -1; - else - return 1; - } - - /** - * Return a pointer of line with description of a table or field - * - * @param string $table Name of table - * @param string $field Optionnel : Name of field if we want description of field - * @return resource Resource - */ - function DDLDescTable($table,$field="") - { - $sql="DESC ".$table." ".$field; - - dol_syslog(get_class($this)."::DDLDescTable ".$sql,LOG_DEBUG); - $this->_results = $this->query($sql); - return $this->_results; - } - - /** - * Create a new field into table - * - * @param string $table Name of table - * @param string $field_name Name of field to add - * @param string $field_desc Tableau associatif de description du champ a inserer[nom du parametre][valeur du parametre] - * @param string $field_position Optionnel ex.: "after champtruc" - * @return int <0 if KO, >0 if OK - */ - function DDLAddField($table,$field_name,$field_desc,$field_position="") - { - // cles recherchees dans le tableau des descriptions (field_desc) : type,value,attribute,null,default,extra - // ex. : $field_desc = array('type'=>'int','value'=>'11','null'=>'not null','extra'=> 'auto_increment'); - $sql= "ALTER TABLE ".$table." ADD ".$field_name." "; - $sql.= $field_desc['type']; - if(preg_match("/^[^\s]/i",$field_desc['value'])) - if (! in_array($field_desc['type'],array('date','datetime'))) - { - $sql.= "(".$field_desc['value'].")"; - } - if(preg_match("/^[^\s]/i",$field_desc['attribute'])) - $sql.= " ".$field_desc['attribute']; - if(preg_match("/^[^\s]/i",$field_desc['null'])) - $sql.= " ".$field_desc['null']; - if(preg_match("/^[^\s]/i",$field_desc['default'])) - { - if(preg_match("/null/i",$field_desc['default'])) - $sql.= " default ".$field_desc['default']; - else - $sql.= " default '".$field_desc['default']."'"; - } - if(preg_match("/^[^\s]/i",$field_desc['extra'])) - $sql.= " ".$field_desc['extra']; - $sql.= " ".$field_position; - - dol_syslog(get_class($this)."::DDLAddField ".$sql,LOG_DEBUG); - if(! $this->query($sql)) - { - return -1; - } - else - { - return 1; - } - } - - /** - * Update format of a field into a table - * - * @param string $table Name of table - * @param string $field_name Name of field to modify - * @param string $field_desc Array with description of field format - * @return int <0 if KO, >0 if OK - */ - function DDLUpdateField($table,$field_name,$field_desc) - { - $sql = "ALTER TABLE ".$table; - $sql .= " MODIFY COLUMN ".$field_name." ".$field_desc['type']; - if ($field_desc['type'] == 'tinyint' || $field_desc['type'] == 'int' || $field_desc['type'] == 'varchar') { - $sql.="(".$field_desc['value'].")"; - } - - dol_syslog(get_class($this)."::DDLUpdateField ".$sql,LOG_DEBUG); - if (! $this->query($sql)) - return -1; - else - return 1; - } - - /** - * Drop a field from table - * - * @param string $table Name of table - * @param string $field_name Name of field to drop - * @return int <0 if KO, >0 if OK - */ - function DDLDropField($table,$field_name) - { - $sql= "ALTER TABLE ".$table." DROP COLUMN `".$field_name."`"; - dol_syslog(get_class($this)."::DDLDropField ".$sql,LOG_DEBUG); - if (! $this->query($sql)) - { - $this->error=$this->lasterror(); - return -1; - } - else return 1; - } - - - /** - * Create a user and privileges to connect to database (even if database does not exists yet) - * - * @param string $dolibarr_main_db_host Ip serveur - * @param string $dolibarr_main_db_user Nom user a creer - * @param string $dolibarr_main_db_pass Mot de passe user a creer - * @param string $dolibarr_main_db_name Database name where user must be granted - * @return int <0 if KO, >=0 if OK - */ - function DDLCreateUser($dolibarr_main_db_host,$dolibarr_main_db_user,$dolibarr_main_db_pass,$dolibarr_main_db_name) - { - $sql = "INSERT INTO user "; - $sql.= "(Host,User,password,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)"; - $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_user)."',password('".addslashes($dolibarr_main_db_pass)."')"; - $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')"; - - dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); // No sql to avoid password in log - $resql=$this->query($sql); - if (! $resql) - { - return -1; - } - - $sql = "INSERT INTO db "; - $sql.= "(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv,Index_Priv,Alter_priv,Lock_tables_priv)"; - $sql.= " VALUES ('".$this->escape($dolibarr_main_db_host)."','".$this->escape($dolibarr_main_db_name)."','".addslashes($dolibarr_main_db_user)."'"; - $sql.= ",'Y','Y','Y','Y','Y','Y','Y','Y','Y')"; - - dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); - $resql=$this->query($sql); - if (! $resql) - { - return -1; - } - - $sql="FLUSH Privileges"; - - dol_syslog(get_class($this)."::DDLCreateUser", LOG_DEBUG); - $resql=$this->query($sql); - if (! $resql) - { - return -1; - } - - return 1; - } - - /** - * Return charset used to store data in database - * - * @return string Charset - */ - function getDefaultCharacterSetDatabase() - { - return 'UTF-8'; - } - - /** - * Return list of available charset that can be used to store data in database - * - * @return array List of Charset - */ - function getListOfCharacterSet() - { - $liste = array(); - $i=0; - $liste[$i]['charset'] = 'UTF-8'; - $liste[$i]['description'] = 'UTF-8'; - return $liste; - } - - /** - * Return collation used in database - * - * @return string Collation value - */ - function getDefaultCollationDatabase() - { - return 'UTF-8'; - } - - /** - * Return list of available collation that can be used for database - * - * @return array List of Collation - */ - function getListOfCollation() - { - $liste = array(); - $i=0; - $liste[$i]['charset'] = 'UTF-8'; - $liste[$i]['description'] = 'UTF-8'; - return $liste; - } - - /** - * Return full path of dump program - * - * @return string Full path of dump program - */ - function getPathOfDump() - { - $fullpathofdump='/pathtomysqldump/mysqldump'; - - $resql=$this->query('SHOW VARIABLES LIKE \'basedir\''); - if ($resql) - { - $liste=$this->fetch_array($resql); - $basedir=$liste['Value']; - $fullpathofdump=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysqldump'; - } - return $fullpathofdump; - } - - /** - * Return full path of restore program - * - * @return string Full path of restore program - */ - function getPathOfRestore() - { - $fullpathofimport='/pathtomysql/mysql'; - - $resql=$this->query('SHOW VARIABLES LIKE \'basedir\''); - if ($resql) - { - $liste=$this->fetch_array($resql); - $basedir=$liste['Value']; - $fullpathofimport=$basedir.(preg_match('/\/$/',$basedir)?'':'/').'bin/mysql'; - } - return $fullpathofimport; - } - - /** - * Return value of server parameters - * - * @param string $filter Filter list on a particular value - * @return array Array of key-values (key=>value) - */ - function getServerParametersValues($filter='') - { - $result=array(); - - $sql='SHOW VARIABLES'; - if ($filter) $sql.=" LIKE '".$this->escape($filter)."'"; - $resql=$this->query($sql); - if ($resql) - { - while ($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value; - } - - return $result; - } - - /** - * Return value of server status - * - * @param string $filter Filter list on a particular value - * @return array Array of key-values (key=>value) - */ - function getServerStatusValues($filter='') - { - $result=array(); - - $sql='SHOW STATUS'; - if ($filter) $sql.=" LIKE '".$this->escape($filter)."'"; - $resql=$this->query($sql); - if ($resql) - { - while ($obj=$this->fetch_object($resql)) $result[$obj->Variable_name]=$obj->Value; - } - - return $result; - } -} - diff --git a/htdocs/core/db/sqlite3.class.php b/htdocs/core/db/sqlite3.class.php index 97ba05a32ba..2c52092b9c9 100644 --- a/htdocs/core/db/sqlite3.class.php +++ b/htdocs/core/db/sqlite3.class.php @@ -305,8 +305,9 @@ class DoliDBSqlite3 extends DoliDB function select_db($database) { dol_syslog(get_class($this)."::select_db database=".$database, LOG_DEBUG); - // FIXME: sqlite_select_db() does not exist - return sqlite_select_db($this->db,$database); + // sqlite_select_db() does not exist + //return sqlite_select_db($this->db,$database); + return true; } diff --git a/htdocs/core/get_menudiv.php b/htdocs/core/get_menudiv.php index b8eae83d4eb..655e10afd67 100644 --- a/htdocs/core/get_menudiv.php +++ b/htdocs/core/get_menudiv.php @@ -85,7 +85,7 @@ if (! class_exists('MenuManager')) } $menumanager = new MenuManager($db, empty($user->societe_id)?0:1); $menumanager->loadMenu('all','all'); - +//var_dump($menumanager->tabMenu);exit; $menumanager->showmenu('jmobile'); print ''; diff --git a/htdocs/core/lib/accounting.lib.php b/htdocs/core/lib/accounting.lib.php index 773e68913f9..bb704ba5c2e 100644 --- a/htdocs/core/lib/accounting.lib.php +++ b/htdocs/core/lib/accounting.lib.php @@ -105,7 +105,7 @@ function clean_account($account) } /** - * Return general accounting account with defined length + * Return General accounting account with defined length (used for product and miscellaneous) * * @param string $account General accounting account * @return string String with defined length @@ -114,6 +114,8 @@ function length_accountg($account) { global $conf; + if ($account < 0 || empty($account)) return ''; + $g = $conf->global->ACCOUNTING_LENGTH_GACCOUNT; if (! empty($g)) { @@ -137,15 +139,17 @@ function length_accountg($account) } /** - * Return auxiliary accounting account with defined length + * Return Auxiliary accounting account of thirdparties with defined length * * @param string $accounta Auxiliary accounting account * @return string String with defined length */ function length_accounta($accounta) { - global $conf; + global $conf, $langs; + if ($accounta < 0 || empty($accounta)) return ''; + $a = $conf->global->ACCOUNTING_LENGTH_AACCOUNT; if (! empty($a)) { diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index 4bcd34baa8a..321a21a9637 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -708,16 +708,19 @@ function purgeSessions($mysessionid) * * @param string $value Name of module to activate * @param int $withdeps Activate/Disable also all dependencies - * @return string Error message or ''; + * @return array array('nbmodules'=>nb modules activated with success, 'errors=>array of error messages, 'nbperms'=>Nb permission added); */ function activateModule($value,$withdeps=1) { global $db, $modules, $langs, $conf; - // Check parameters - if (empty($value)) return 'ErrorBadParameter'; + // Check parameters + if (empty($value)) { + $ret['errors'][] = 'ErrorBadParameter'; + return $ret; + } - $ret=''; + $ret=array('nbmodules'=>0, 'errors'=>array(), 'nbperms'=>0); $modName = $value; $modFile = $modName . ".class.php"; @@ -740,71 +743,88 @@ function activateModule($value,$withdeps=1) // Test if PHP version ok $verphp=versionphparray(); $vermin=isset($objMod->phpmin)?$objMod->phpmin:0; - if (is_array($vermin) && versioncompare($verphp,$vermin) < 0) - { - return $langs->trans("ErrorModuleRequirePHPVersion",versiontostring($vermin)); - } + if (is_array($vermin) && versioncompare($verphp, $vermin) < 0) { + $ret['errors'][] = $langs->trans("ErrorModuleRequirePHPVersion", versiontostring($vermin)); + return $ret; + } // Test if Dolibarr version ok $verdol=versiondolibarrarray(); $vermin=isset($objMod->need_dolibarr_version)?$objMod->need_dolibarr_version:0; //print 'eee '.versioncompare($verdol,$vermin).' - '.join(',',$verdol).' - '.join(',',$vermin);exit; - if (is_array($vermin) && versioncompare($verdol,$vermin) < 0) - { - return $langs->trans("ErrorModuleRequireDolibarrVersion",versiontostring($vermin)); - } + if (is_array($vermin) && versioncompare($verdol, $vermin) < 0) { + $ret['errors'][] = $langs->trans("ErrorModuleRequireDolibarrVersion", versiontostring($vermin)); + return $ret; + } - // Test if javascript requirement ok - if (! empty($objMod->need_javascript_ajax) && empty($conf->use_javascript_ajax)) - { - return $langs->trans("ErrorModuleRequireJavascript"); - } + // Test if javascript requirement ok + if (!empty($objMod->need_javascript_ajax) && empty($conf->use_javascript_ajax)) { + $ret['errors'][] = $langs->trans("ErrorModuleRequireJavascript"); + return $ret; + } $result=$objMod->init(); - if ($result <= 0) $ret=$objMod->error; - - if (! $ret && $withdeps) + if ($result <= 0) { - if (isset($objMod->depends) && is_array($objMod->depends) && ! empty($objMod->depends)) + $ret['errors'][]=$objMod->error; + } + else + { + if ($withdeps) { - // Activation des modules dont le module depend - $TError=array(); - $num = count($objMod->depends); - for ($i = 0; $i < $num; $i++) + if (isset($objMod->depends) && is_array($objMod->depends) && ! empty($objMod->depends)) { - $activate = false; - foreach ($modulesdir as $dir) - { - if (file_exists($dir.$objMod->depends[$i].".class.php")) - { - activateModule($objMod->depends[$i]); - $activate = true; - } - } - - if (!$activate) $TError[] = $langs->trans('activateModuleDependNotSatisfied', $objMod->name, $objMod->depends[$i]); + // Activation des modules dont le module depend + $num = count($objMod->depends); + for ($i = 0; $i < $num; $i++) + { + $activate = false; + foreach ($modulesdir as $dir) + { + if (file_exists($dir.$objMod->depends[$i].".class.php")) + { + $resarray = activateModule($objMod->depends[$i]); + if (empty($resarray['errors'])) $activate = true; + break; + } + } + + if ($activate) + { + $ret['nbmodules']+=$resarray['nbmodules']; + $ret['nbperms']+=$resarray['nbperms']; + } + else + { + $ret['errors'][] = $langs->trans('activateModuleDependNotSatisfied', $objMod->name, $objMod->depends[$i]); + } + } } - - setEventMessages('', $TError, 'errors'); - } - - if (isset($objMod->conflictwith) && is_array($objMod->conflictwith) && ! empty($objMod->conflictwith)) - { - // Desactivation des modules qui entrent en conflit - $num = count($objMod->conflictwith); - for ($i = 0; $i < $num; $i++) + + if (isset($objMod->conflictwith) && is_array($objMod->conflictwith) && ! empty($objMod->conflictwith)) { - foreach ($modulesdir as $dir) - { - if (file_exists($dir.$objMod->conflictwith[$i].".class.php")) - { - unActivateModule($objMod->conflictwith[$i],0); - } - } + // Desactivation des modules qui entrent en conflit + $num = count($objMod->conflictwith); + for ($i = 0; $i < $num; $i++) + { + foreach ($modulesdir as $dir) + { + if (file_exists($dir.$objMod->conflictwith[$i].".class.php")) + { + unActivateModule($objMod->conflictwith[$i],0); + } + } + } } } } + if (! count($ret['errors'])) + { + $ret['nbmodules']++; + $ret['nbperms']+=count($objMod->rights); + } + return $ret; } @@ -1275,7 +1295,8 @@ function showModulesExludedForExternal($modules) //if (empty($conf->global->$moduleconst)) continue; if (! in_array($modulename,$listofmodules)) continue; - + //var_dump($modulename.'eee'.$langs->trans('Module'.$module->numero.'Name')); + if ($i > 0) $text.=', '; else $text.=' '; $i++; diff --git a/htdocs/core/lib/bank.lib.php b/htdocs/core/lib/bank.lib.php index b5371e6fa53..74078740080 100644 --- a/htdocs/core/lib/bank.lib.php +++ b/htdocs/core/lib/bank.lib.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2012 Regis Houssin * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2016 Juanjo Menent @@ -42,8 +42,8 @@ function bank_prepare_head(Account $object) $head[$h][2] = 'bankname'; $h++; - $head[$h][0] = DOL_URL_ROOT . "/compta/bank/account.php?id=" . $object->id; - $head[$h][1] = $langs->trans("Transactions"); + $head[$h][0] = DOL_URL_ROOT . "/compta/bank/bankentries.php?id=" . $object->id; + $head[$h][1] = $langs->trans("BankTransactions"); $head[$h][2] = 'journal'; $h++; diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index 0562edad6b5..8c738894998 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -123,7 +123,45 @@ function societe_prepare_head(Societe $object) $h++; } - // Show more tabs from modules + // Related items + if (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->fichinter->enabled) || ! empty($conf->fournisseur->enabled)) + { + $head[$h][0] = DOL_URL_ROOT.'/societe/consumption.php?socid='.$object->id; + $head[$h][1] = $langs->trans("Referers"); + $head[$h][2] = 'consumption'; + $h++; + } + + // Bank accounrs + if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) + { + $nbBankAccount=0; + $head[$h][0] = DOL_URL_ROOT .'/societe/rib.php?socid='.$object->id; + $head[$h][1] = $langs->trans("BankAccounts"); + $sql = "SELECT COUNT(n.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_rib as n"; + $sql.= " WHERE fk_soc = ".$object->id; + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $nbBankAccount=$obj->nb; + $i++; + } + } + else { + dol_print_error($db); + } + if ($nbBankAccount > 0) $head[$h][1].= ' '.$nbBankAccount.''; + $head[$h][2] = 'rib'; + $h++; + } + + // Show more tabs from modules // Entries must be declared in modules descriptor with line // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab @@ -131,14 +169,6 @@ function societe_prepare_head(Societe $object) if ($user->societe_id == 0) { - if (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->fichinter->enabled) || ! empty($conf->fournisseur->enabled)) - { - $head[$h][0] = DOL_URL_ROOT.'/societe/consumption.php?socid='.$object->id; - $head[$h][1] = $langs->trans("Referers"); - $head[$h][2] = 'consumption'; - $h++; - } - // Notifications if (! empty($conf->notification->enabled)) { @@ -194,12 +224,12 @@ function societe_prepare_head(Societe $object) } $head[$h][0] = DOL_URL_ROOT.'/societe/agenda.php?socid='.$object->id; + $head[$h][1].= $langs->trans("Events"); if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) { - $head[$h][1] = $langs->trans("Events"); $head[$h][1].= '/'; + $head[$h][1].= $langs->trans("Agenda"); } - $head[$h][1].= $langs->trans("Agenda"); $head[$h][2] = 'agenda'; $h++; @@ -232,14 +262,6 @@ function societe_prepare_head2($object) $head[$h][2] = 'company'; $h++; - if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) - { - $head[$h][0] = DOL_URL_ROOT .'/societe/rib.php?socid='.$object->id; - $head[$h][1] = $langs->trans("BankAccount"); - $head[$h][2] = 'rib'; - $h++; - } - $head[$h][0] = 'commerciaux.php?socid='.$object->id; $head[$h][1] = $langs->trans("SalesRepresentative"); $head[$h][2] = 'salesrepresentative'; @@ -908,198 +930,48 @@ function show_addresses($conf,$langs,$db,$object,$backtopage='') * @param Conf $conf Object conf * @param Translate $langs Object langs * @param DoliDB $db Object db - * @param Adherent|Societe $object Object third party or member + * @param Adherent|Societe $filterobj Object third party or member * @param Contact $objcon Object contact * @param int $noprint Return string but does not output it + * @param int $actioncode Filter on actioncode * @return mixed Return html part or void if noprint is 1 */ -function show_actions_todo($conf,$langs,$db,$object,$objcon='',$noprint=0) +function show_actions_todo($conf,$langs,$db,$filterobj,$objcon='',$noprint=0,$actioncode='') { global $bc,$user,$conf; - // Check parameters - if (! is_object($object)) dol_print_error('','BadParameter'); - - $now=dol_now('tzuser'); - $out=''; - - if (! empty($conf->agenda->enabled)) - { - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - $actionstatic=new ActionComm($db); - $userstatic=new User($db); - $contactstatic = new Contact($db); - - $out.="\n"; - $out.=''; - $out.=''; - if($conf->global->AGENDA_USE_EVENT_TYPE) $out.=''; - - if($conf->global->AGENDA_USE_EVENT_TYPE) { - $out.=''; - $out.=''; - $out.=''; - - $sql = "SELECT a.id, a.label,"; - $sql.= " a.datep as dp,"; - $sql.= " a.datep2 as dp2,"; - $sql.= " a.percent,"; - $sql.= " a.fk_user_author, a.fk_contact,"; - $sql.= " a.fk_element, a.elementtype,"; - $sql.= " c.code as acode, c.libelle,"; - $sql.= " u.login, u.rowid"; - if (get_class($object) == 'Societe') $sql.= ", sp.lastname, sp.firstname"; - if (get_class($object) == 'Adherent') $sql.= ", m.lastname, m.firstname"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."actioncomm as a"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; - if (get_class($object) == 'Societe') $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; - if (get_class($object) == 'Adherent') $sql.= ", ".MAIN_DB_PREFIX."adherent as m"; - $sql.= " WHERE u.rowid = a.fk_user_author"; - $sql.= " AND a.entity IN (".getEntity('agenda', 1).")"; - if (get_class($object) == 'Adherent') - { - $sql.= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; - if (! empty($object->id)) $sql.= " AND a.fk_element = ".$object->id; - } - if (get_class($object) == 'Societe' && $object->id) $sql.= " AND a.fk_soc = ".$object->id; - if (! empty($objcon->id)) $sql.= " AND a.fk_contact = ".$objcon->id; - $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - $sql.= " ORDER BY a.datep DESC, a.id DESC"; - - dol_syslog("company.lib::show_actions_todo", LOG_DEBUG); - $result=$db->query($sql); - if ($result) - { - $i = 0 ; - $num = $db->num_rows($result); - $var=true; - - if ($num) - { - while ($i < $num) - { - $var = !$var; - - $obj = $db->fetch_object($result); - $actionstatic->fetch($obj->id); - $datep=$db->jdate($obj->dp); - $datep2=$db->jdate($obj->dp2); - - $out.=""; - - // Date - $out.='\n"; - - // Picto warning - $out.=''; - - $actionstatic->type_code=$obj->acode; - $transcode=$langs->trans("Action".$obj->acode); - $libelle=($transcode!="Action".$obj->acode?$transcode:$obj->libelle); - //$actionstatic->libelle=$libelle; - $actionstatic->libelle=$obj->label; - $actionstatic->id=$obj->id; - //$out.=''; - - // Title of event - //$out.=''; - $out.=''; - - if($conf->global->AGENDA_USE_EVENT_TYPE) { - $out.= ''; - } - // Contact pour cette action - if (empty($objcon->id) && $obj->fk_contact > 0) - { - $contactstatic->lastname=$obj->lastname; - $contactstatic->firstname=$obj->firstname; - $contactstatic->id=$obj->fk_contact; - $out.=''; - } - else - { - $out.=''; - } - - $out.=''; - - // Statut - $out.=''; - - $out.="\n"; - $i++; - } - } - else - { - // Aucun action a faire - - } - $db->free($result); - } - else - { - dol_print_error($db); - } - $out.="
    '; - else $out.=''; - if (get_class($object) == 'Societe') $out.=''; - $out.=$langs->trans("ActionsToDoShort"); - if (get_class($object) == 'Societe') $out.=''; - $out.=''; - $out.=$langs->trans("Type"); - $out.=''; - } else { - $out.=''; - } - - $out.='
    '; - $out.=dol_print_date($datep,'dayhour'); - if ($datep2 && $datep2 != $datep) - { - $tmpa=dol_getdate($datep,true); - $tmpb=dol_getdate($datep2,true); - if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $out.='-'.dol_print_date($datep2,'hour'); - else $out.='-'.dol_print_date($datep2,'dayhour'); - } - $out.="'; - if ($obj->percent >= 0 && $datep && $datep < ($now - ($conf->global->MAIN_DELAY_ACTIONS_TODO *60*60*24)) ) $out.=' '.img_warning($langs->trans("Late")); - else $out.=' '; - $out.=''.$actionstatic->getNomUrl(1,16).''.dol_trunc($obj->label,40).''.$actionstatic->getNomUrl(1,120).''; - $out.=$actionstatic->type; - $out.=''.$contactstatic->getNomUrl(1,'',10).' '; - //$userstatic->id=$obj->fk_user_author; - //$userstatic->login=$obj->login; - //$out.=$userstatic->getLoginUrl(1); - $userstatic->fetch($obj->fk_user_author); - $out.=$userstatic->getNomUrl(1); - $out.=''.$actionstatic->LibStatut($obj->percent,3).'
    \n"; - - $out.="
    \n"; - } + $out = show_actions_done($conf,$langs,$db,$filterobj,$objcon,1,$actioncode, 'todo'); if ($noprint) return $out; else print $out; } /** - * Show html area with actions done + * Show html area with actions (done or not, ignore the name of function) * - * @param Conf $conf Object conf - * @param Translate $langs Object langs - * @param DoliDB $db Object db - * @param Adherent|Societe $object Object third party or member - * @param Contact $objcon Object contact - * @param int $noprint Return string but does not output it - * @return mixed Return html part or void if noprint is 1 - * TODO change function to be able to list event linked to an object. + * @param Conf $conf Object conf + * @param Translate $langs Object langs + * @param DoliDB $db Object db + * @param Adherent|Societe|Project $filterobj Object third party or member or project + * @param Contact $objcon Object contact + * @param int $noprint Return string but does not output it + * @param string $actioncode Filter on actioncode + * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter. + * @param array $filters Filter on other fields + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @return mixed Return html part or void if noprint is 1 + * TODO change function to be able to list event linked to an object. */ -function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) +function show_actions_done($conf, $langs, $db, $filterobj, $objcon='', $noprint=0, $actioncode='', $donetodo='done', $filters=array(), $sortfield='a.datep, a.id', $sortorder='DESC') { global $bc,$user,$conf; + global $form; + global $param; + // Check parameters - if (! is_object($object)) dol_print_error('','BadParameter'); + if (! is_object($filterobj)) dol_print_error('','BadParameter'); $out=''; $histo=array(); @@ -1115,22 +987,26 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) $sql.= " a.note, a.percent,"; $sql.= " a.fk_element, a.elementtype,"; $sql.= " a.fk_user_author, a.fk_contact,"; - $sql.= " c.code as acode, c.libelle,"; + $sql.= " c.code as acode, c.libelle as alabel, c.picto as apicto,"; $sql.= " u.login, u.rowid as user_id"; - if (get_class($object) == 'Societe') $sql.= ", sp.lastname, sp.firstname"; - if (get_class($object) == 'Adherent') $sql.= ", m.lastname, m.firstname"; + if (get_class($filterobj) == 'Societe') $sql.= ", sp.lastname, sp.firstname"; + if (get_class($filterobj) == 'Adherent') $sql.= ", m.lastname, m.firstname"; $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."actioncomm as a"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; - if (get_class($object) == 'Societe') $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; - if (get_class($object) == 'Adherent') $sql.= ", ".MAIN_DB_PREFIX."adherent as m"; + if (get_class($filterobj) == 'Societe') $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; + if (get_class($filterobj) == 'Adherent') $sql.= ", ".MAIN_DB_PREFIX."adherent as m"; $sql.= " WHERE u.rowid = a.fk_user_author"; $sql.= " AND a.entity IN (".getEntity('agenda', 1).")"; - if (get_class($object) == 'Societe' && $object->id) $sql.= " AND a.fk_soc = ".$object->id; - if (get_class($object) == 'Adherent') $sql.= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; - if (get_class($object) == 'Adherent' && $object->id) $sql.= " AND a.fk_element = ".$object->id; + if (get_class($filterobj) == 'Societe' && $filterobj->id) $sql.= " AND a.fk_soc = ".$filterobj->id; + if (get_class($filterobj) == 'Project' && $filterobj->id) $sql.= " AND a.fk_project = ".$filterobj->id; + if (get_class($filterobj) == 'Adherent') $sql.= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; + if (get_class($filterobj) == 'Adherent' && $filterobj->id) $sql.= " AND a.fk_element = ".$filterobj->id; if (is_object($objcon) && $objcon->id) $sql.= " AND a.fk_contact = ".$objcon->id; - $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - $sql.= " ORDER BY a.datep DESC, a.id DESC"; + if (!empty($actioncode)) $sql.= " AND c.code='".$actioncode."' "; + if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + if ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + if (is_array($filters) && $filters['search_agenda_label']) $sql.= natural_search('a.label', $filters['search_agenda_label']); + $sql.= $db->order($sortfield, $sortorder); dol_syslog("company.lib::show_actions_done", LOG_DEBUG); $resql=$db->query($sql); @@ -1142,23 +1018,34 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) while ($i < $num) { $obj = $db->fetch_object($resql); + + //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + //if ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + $tododone=''; + if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone='todo'; + $histo[$numaction]=array( - 'type'=>'action', - 'id'=>$obj->id, - 'datestart'=>$db->jdate($obj->dp), - 'dateend'=>$db->jdate($obj->dp2), - 'note'=>$obj->label, - 'percent'=>$obj->percent, - 'acode'=>$obj->acode, - 'libelle'=>$obj->libelle, - 'userid'=>$obj->user_id, - 'login'=>$obj->login, - 'contact_id'=>$obj->fk_contact, - 'lastname'=>$obj->lastname, - 'firstname'=>$obj->firstname, - 'fk_element'=>$obj->fk_element, - 'elementtype'=>$obj->elementtype + 'type'=>'action', + 'tododone'=>$tododone, + 'id'=>$obj->id, + 'datestart'=>$db->jdate($obj->dp), + 'dateend'=>$db->jdate($obj->dp2), + 'note'=>$obj->label, + 'percent'=>$obj->percent, + 'userid'=>$obj->user_id, + 'login'=>$obj->login, + 'contact_id'=>$obj->fk_contact, + 'lastname'=>$obj->lastname, + 'firstname'=>$obj->firstname, + 'fk_element'=>$obj->fk_element, + 'elementtype'=>$obj->elementtype, + // Type of event + 'acode'=>$obj->acode, + 'alabel'=>$obj->alabel, + 'libelle'=>$obj->alabel, // deprecated + 'apicto'=>$obj->apicto ); + $numaction++; $i++; } @@ -1169,11 +1056,11 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) } } + // Add also event from emailings. FIXME This should be replaced by an automatic event if (! empty($conf->mailing->enabled) && ! empty($objcon->email)) { $langs->load("mails"); - // Recherche histo sur mailing $sql = "SELECT m.rowid as id, mc.date_envoi as da, m.titre as note, '100' as percentage,"; $sql.= " 'AC_EMAILING' as acode,"; $sql.= " u.rowid as user_id, u.login"; // User that valid action @@ -1196,6 +1083,7 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) $obj = $db->fetch_object($resql); $histo[$numaction]=array( 'type'=>'mailing', + 'tododone'=>'done', 'id'=>$obj->id, 'datestart'=>$db->jdate($obj->da), 'dateend'=>$db->jdate($obj->da), @@ -1223,7 +1111,11 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $actionstatic=new ActionComm($db); + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + + $formactions=new FormActions($db); + + $actionstatic=new ActionComm($db); $userstatic=new User($db); $contactstatic = new Contact($db); @@ -1232,59 +1124,85 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) $orderstatic=new Commande($db); $facturestatic=new Facture($db); + $out.='
    '; + $out.=''; + if (get_class($filterobj) == 'Societe') $out.=''; + $out.="\n"; $out.=''; $out.=''; - if($conf->global->AGENDA_USE_EVENT_TYPE) $out.=''; - - if($conf->global->AGENDA_USE_EVENT_TYPE) { - $out.=''; - $out.=''; } - - $out.=''; - $out.=''; + $out.=getTitleFieldOfList($langs->trans("Ref"), 0, $_SERVER["PHP_SELF"], 'a.id', '', $param, '', $sortfield, $sortorder); + $out.=''; + $out.=getTitleFieldOfList($langs->trans("Date"), 0, $_SERVER["PHP_SELF"], 'a.datep, a.id', '', $param, '', $sortfield, $sortorder); + $out.=''; + $out.=''; + $out.=''; + $out.=''; + $out.=getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], 'a.percent', '', $param, 'align="center"', $sortfield, $sortorder); + $out.=''; + $out.=''; + + $out.=''; + if ($donetodo) + { + $out.=''; + } + $out.=''; + $out.=''; + $out.=''; + $out.=''; + $out.=''; + $out.=''; + $out.=''; + $out.=''; + // Action column + $out.=''; + $out.=''; + foreach ($histo as $key=>$value) { $var=!$var; + $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo + $out.=""; - $actionstatic->fetch($histo[$key]['id']); - // Champ date - $out.=''; } - $out.="\n"; - - // Picto - $out.=''; - - // Action + + // Ref + $out.=''; + + // Title $out.=''; - if($conf->global->AGENDA_USE_EVENT_TYPE) { - $out.=''; + // Date + $out.='\n"; + + // Type + $out.=''; + // Title of event //$out.=''; @@ -1370,8 +1309,11 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) $out.=''; // Statut - $out.=''; + $out.=''; + // Actions + $out.=''; + $out.="\n"; $i++; } @@ -1379,6 +1321,8 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) //$out.="
    \n"; } + $out.=''; + if ($noprint) return $out; else print $out; } diff --git a/htdocs/core/lib/cron.lib.php b/htdocs/core/lib/cron.lib.php index d7a0a57ac37..aade8149ce5 100644 --- a/htdocs/core/lib/cron.lib.php +++ b/htdocs/core/lib/cron.lib.php @@ -100,11 +100,13 @@ function dol_print_cron_urls() print img_picto('','object_globe.png').' '.$url."
    \n"; print '
    '; - + $logintouse = 'firstadmin'; + if ($user->admin) $logintouse = $user->login; + print ''.$langs->trans("FileToLaunchCronJobs").':
    '; - $file='/scripts/cron/cron_run_jobs.php'.' '.(empty($conf->global->CRON_KEY)?'securitykey':''.$conf->global->CRON_KEY.'').' '.$user->login.' [cronjobid]'; - print '
    \n"; + $file='/scripts/cron/cron_run_jobs.php'.' '.(empty($conf->global->CRON_KEY)?'securitykey':''.$conf->global->CRON_KEY.'').' '.$logintouse.' [cronjobid]'; + print '
    \n"; print '
    '; // Add note @@ -116,7 +118,7 @@ function dol_print_cron_urls() { print $langs->trans("CronExplainHowToRunUnix"); print '
    '; - print '
    '; + print '
    '; } else { diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index c1436e6d36e..3d43108e6a3 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -617,7 +617,7 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable // Security: // Disallow file with some extensions. We renamed them. // Car si on a mis le rep documents dans un rep de la racine web (pas bien), cela permet d'executer du code a la demande. - if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$dest_file)) + if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$dest_file) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) { $file_name.= '.noexe'; } @@ -1693,7 +1693,7 @@ function dol_check_secure_access_document($modulepart,$original_file,$entity,$fu // Wrapping for accounting exports else if ($modulepart == 'export_compta') { - if ($fuser->rights->accounting->ventilation->dispatch || preg_match('/^specimen/i',$original_file)) + if ($fuser->rights->accounting->bind->write || preg_match('/^specimen/i',$original_file)) { $accessallowed=1; } @@ -1779,7 +1779,7 @@ function dol_check_secure_access_document($modulepart,$original_file,$entity,$fu $accessallowed=1; } - $original_file=$conf->banque->dir_output.'/bordereau/'.$original_file; // original_file should contains relative path so include the get_exdir result + $original_file=$conf->bank->dir_output.'/checkdeposits/'.$original_file; // original_file should contains relative path so include the get_exdir result } // Wrapping for bank diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 4d6f05f4de8..b71c3ac0906 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -7,7 +7,7 @@ * Copyright (C) 2004 Christophe Combelles * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2008 Raphael Bertrand (Resultic) - * Copyright (C) 2010-2014 Juanjo Menent + * Copyright (C) 2010-2016 Juanjo Menent * Copyright (C) 2013 Cédric Salvador * Copyright (C) 2013 Alexandre Spangaro * Copyright (C) 2014 Cédric GROSS @@ -102,7 +102,7 @@ function getDoliDBInstance($type, $host, $user, $pass, $name, $port) /** * Get list of entity id to use * - * @param string $element Current element + * @param string $element Current element ('actioncomm', ...) * @param int $shared 0=Return id of entity, 1=Return id entity + shared entities * @return mixed Entity id(s) to use */ @@ -228,7 +228,7 @@ function dol_shutdown() * Return value of a param into GET or POST supervariable * * @param string $paramname Name of parameter to found - * @param string $check Type of check (''=no check, 'int'=check it's numeric, 'alpha'=check it's text and sign, 'aZ'=check it's a-z only, 'array'=check it's array, 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string), 'custom'= custom filter specify $filter and $options) + * @param string $check Type of check (''=no check, 'int'=check it's numeric, 'alpha'=check it's text and sign, 'aZ'=check it's a-z only, 'array'=check it's array, 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string), 'day', 'month', 'year', 'custom'= custom filter specify $filter and $options) * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get, 4 = post then get then cookie) * @param int $filter Filter to apply when $check is set to custom. (See http://php.net/manual/en/filter.filters.php for détails) * @param mixed $options Options to pass to filter_var when $check is set to custom @@ -245,6 +245,25 @@ function GETPOST($paramname,$check='',$method=0,$filter=NULL,$options=NULL) if (! empty($check)) { + if (! is_array($out) && preg_match('/^__([a-z0-9]+)__$/i', $out, $reg)) + { + if ($reg[1] == 'DAY') + { + $tmp=dol_getdate(dol_now(), true); + $out = $tmp['mday']; + } + elseif ($reg[1] == 'MONTH') + { + $tmp=dol_getdate(dol_now(), true); + $out = $tmp['mon']; + } + elseif ($reg[1] == 'YEAR') + { + $tmp=dol_getdate(dol_now(), true); + $out = $tmp['year']; + } + } + switch ($check) { case 'int': @@ -271,6 +290,9 @@ function GETPOST($paramname,$check='',$method=0,$filter=NULL,$options=NULL) case 'array': if (! is_array($out) || empty($out)) $out=array(); break; + case 'nohtml': + $out=dol_string_nohtmltag($out); + break; case 'custom': if (empty($filter)) return 'BadFourthParameterForGETPOST'; $out=filter_var($out, $filter, $options); @@ -368,7 +390,21 @@ function dol_buildpath($path, $type=0) foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...) { - if ($key == 'main') continue; + if ($key == 'main') + { + if ($type == 3) + { + global $dolibarr_main_url_root; + + // 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 + + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax + } + continue; + } preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?' if (! empty($regs[1])) { @@ -392,7 +428,7 @@ function dol_buildpath($path, $type=0) $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 - $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; + $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax } break; } @@ -443,10 +479,10 @@ function dol_size($size,$type='') * * @param string $str String to clean * @param string $newstr String to replace bad chars with - * @param int $unaccent 1=Remove also accent (default), 0 do not remove them + * @param int $unaccent 1=Remove also accent (default), 0 do not remove them * @return string String cleaned (a-zA-Z_) * - * @see dol_string_nospecial, dol_string_unaccent + * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizePathName */ function dol_sanitizeFileName($str,$newstr='_',$unaccent=1) { @@ -454,6 +490,22 @@ function dol_sanitizeFileName($str,$newstr='_',$unaccent=1) return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); } +/** + * Clean a string to use it as a path name + * + * @param string $str String to clean + * @param string $newstr String to replace bad chars with + * @param int $unaccent 1=Remove also accent (default), 0 do not remove them + * @return string String cleaned (a-zA-Z_) + * + * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizeFileName + */ +function dol_sanitizePathName($str,$newstr='_',$unaccent=1) +{ + $filesystem_forbidden_chars = array('<','>','?','*','|','"','°'); + return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars); +} + /** * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName * @@ -694,7 +746,7 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename=' /** * Show tab header of a card * - * @param array $links Array of tabs + * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head * @param string $active Active tab name (document', 'info', 'ldap', ....) * @param string $title Title * @param int $notab 0=Add tab header, 1=no tab header. If you set this to 1, using dol_fiche_end() to close tab is not required. @@ -888,9 +940,10 @@ function dol_get_fiche_end($notab=0) * @param int $nodbprefix Do not include DB prefix to forge table name * @param string $morehtmlleft More html code to show before ref * @param string $morehtmlright More html code to show before navigation arrows + * @param int $onlybanner Put this to 1, if the card will contains only a banner * @return void */ -function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlright='') +function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlright='', $onlybanner=0) { global $conf, $form, $user, $langs; @@ -901,25 +954,24 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r $modulepart='unknown'; if ($object->element == 'societe') $modulepart='societe'; if ($object->element == 'contact') $modulepart='contact'; - if ($object->element == 'member') $modulepart='memberphoto'; - if ($object->element == 'user') $modulepart='userphoto'; + if ($object->element == 'member') $modulepart='memberphoto'; + if ($object->element == 'user') $modulepart='userphoto'; if ($object->element == 'product') $modulepart='product'; - - print '
    '; + if ($object->element == 'product') { $width=80; $cssclass='photoref'; $showimage=$object->is_photo_available($conf->product->multidir_output[$object->entity]); $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5); if ($conf->browser->phone) $maxvisiblephotos=1; - if ($showimage) $morehtmlleft.='
    '.$object->show_photos($conf->product->multidir_output[$object->entity],'small',-$maxvisiblephotos,0,0,0,$width,0).'
    '; + if ($showimage) $morehtmlleft.='
    '.$object->show_photos($conf->product->multidir_output[$object->entity],'small',$maxvisiblephotos,0,0,0,$width,0).'
    '; else { if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) { $nophoto=''; $morehtmlleft.='
    '; } - else { + elseif ($conf->browser->layout != 'phone') { // Show no photo link $nophoto='/public/theme/common/nophoto.png'; $morehtmlleft.='
    No photo
    '; } @@ -928,7 +980,36 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r } else { - if ($showimage) $morehtmlleft.='
    '.$form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos).'
    '; + if ($showimage) + { + if ($modulepart != 'unknown') + { + $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos); + if ($phototoshow) + { + $morehtmlleft.='
    '; + $morehtmlleft.=$phototoshow; + $morehtmlleft.='
    '; + } + } + elseif ($conf->browser->layout != 'phone') // Show no photo link + { + $morehtmlleft.='
    '; + if ($object->element == 'action') + { + $cssclass='photorefcenter'; + $nophoto=img_picto('', 'title_agenda', '', false, 1); + $morehtmlleft.='
    No photo
    '; + } + else + { + $width=14; $cssclass='photorefcenter'; + $nophoto=img_picto('', 'object_'.$object->picto, '', false, 1); + $morehtmlleft.='
    No photo
    '; + } + $morehtmlleft.='
    '; + } + } } if ($showbarcode) $morehtmlleft.='
    '.$form->showbarcode($object).'
    '; if ($object->element == 'societe' && ! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { @@ -940,18 +1021,30 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { $morehtmlright.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell'); } else { - $morehtmlright.=$object->getLibStatut(2,0); + $morehtmlright.=$object->getLibStatut(5,0); } $morehtmlright.='   '; //$morehtmlright.=$langs->trans("Status").' ('.$langs->trans("Buy").') '; if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) { $morehtmlright.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy'); } else { - $morehtmlright.=$object->getLibStatut(2,1); + $morehtmlright.=$object->getLibStatut(5,1); } } + elseif ($object->element == 'facture' || $object->element == 'invoice' || $object->element == 'invoice_supplier') + { + $tmptxt=$object->getLibStatut(6, $object->totalpaye); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt=$object->getLibStatut(5, $object->totalpaye); + $morehtmlright.=$tmptxt; + } + elseif ($object->element == 'facturerec') + { + $morehtmlright.=''; + } else { - $morehtmlright.=$object->getLibStatut(2); + $tmptxt=$object->getLibStatut(6); + if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt=$object->getLibStatut(5); + $morehtmlright.=$tmptxt; } if (! empty($object->name_alias)) $morehtmlref.='
    '.$object->name_alias.'
    '; // For thirdparty if (! empty($object->label)) $morehtmlref.='
    '.$object->label.'
    '; // For product @@ -967,6 +1060,8 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r $morehtmlref.=$langs->trans("TechnicalID").': '.$object->id; $morehtmlref.='
    '; } + + print '
    '; print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlright); print '
    '; print '
    '; @@ -985,9 +1080,9 @@ function fieldLabel($langkey, $fieldkey, $fieldrequired=0) global $conf, $langs; $ret=''; if ($fieldrequired) $ret.=''; - if (empty($conf->dol_use_jmobile)) $ret.=''; if ($fieldrequired) $ret.=''; return $ret; } @@ -1096,7 +1191,7 @@ function dol_strftime($fmt, $ts=false, $is_gmt=false) * "%d %b %Y", * "%d/%m/%Y %H:%M", * "%d/%m/%Y %H:%M:%S", - * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc" + * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat" * @param string $tzoutput true or 'gmt' => string is for Greenwich location * false or 'tzserver' => output string is for local PHP server TZ usage * 'tzuser' => output string is for user TZ (current browser TZ with current dst) @@ -1774,10 +1869,11 @@ function dol_user_country() * @param int $mode thirdparty|contact|member|other * @param int $id Id of object * @param int $noprint No output. Result is the function return + * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1 * @see dol_format_address */ -function dol_print_address($address, $htmlid, $mode, $id, $noprint=0) +function dol_print_address($address, $htmlid, $mode, $id, $noprint=0, $charfornl='') { global $conf, $user, $langs, $hookmanager; @@ -1792,7 +1888,9 @@ function dol_print_address($address, $htmlid, $mode, $id, $noprint=0) } if (empty($reshook)) { - $out.=nl2br($address); + if (empty($charfornl)) $out.=nl2br($address); + else $out.=preg_replace('/[\r\n]+/', $charfornl, $address); + $showgmap=$showomap=0; // TODO Add a hook here @@ -2199,7 +2297,7 @@ function img_picto($titlealt, $picto, $options = '', $pictoisfullpath = false, $ else { $tmparray=array(0=>$titlealt); - if (preg_match('/:[^\s]/',$titlealt)) $tmparray=explode(':',$titlealt); // We explode if we have TextA:TextB. Not if we have TextA: TextB + if (preg_match('/:[^\s0-9]/',$titlealt)) $tmparray=explode(':',$titlealt); // We explode if we have TextA:TextB. Not if we have TextA: TextB $title=$tmparray[0]; $alt=empty($tmparray[1])?'':$tmparray[1]; return ''.dol_escape_htmltag($alt).''; // Alt is used for accessibility, title for popup @@ -2214,12 +2312,14 @@ function img_picto($titlealt, $picto, $options = '', $pictoisfullpath = false, $ * For external modules use imagename@mymodule to search into directory "img" of module. * @param string $options Add more attribute on img tag (ie: class="datecallink") * @param int $pictoisfullpath If 1, image path is a full path + * @param int $srconly Return only content of the src attribute of img. + * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip. * @return string Return img tag * @see #img_picto, #img_picto_common */ -function img_object($titlealt, $picto, $options = '', $pictoisfullpath = false) +function img_object($titlealt, $picto, $options = '', $pictoisfullpath = false, $srconly=0, $notitle=0) { - return img_picto($titlealt, 'object_'.$picto, $options, $pictoisfullpath); + return img_picto($titlealt, 'object_'.$picto, $options, $pictoisfullpath, $srconly, $notitle); } /** @@ -2416,9 +2516,9 @@ function img_printer($titlealt = "default", $other='') /** * Show help logo with cursor "?" * - * @param string $usehelpcursor Use help cursor - * @param string $usealttitle Text to use as alt title - * @return string Retourne tag img + * @param int $usehelpcursor Use help cursor + * @param int|string $usealttitle Text to use as alt title + * @return string Return tag img */ function img_help($usehelpcursor = 1, $usealttitle = 1) { @@ -3076,19 +3176,21 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so print '
    '; - else $out.=''; - if (get_class($object) == 'Societe') $out.=''; - $out.=$langs->trans("ActionsDoneShort"); - if (get_class($object) == 'Societe') $out.=''; - $out.=''; - $out.=$langs->trans("Type"); - $out.=''; - } else { - $out.=''; + if ($donetodo) + { + $out.=''; + if (get_class($filterobj) == 'Societe') $out.=''; + $out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort"); + if (get_class($filterobj) == 'Societe') $out.=''; + $out.='
    '.$langs->trans("Label").''.$langs->trans("Type").''.$langs->trans("Owner").'
    '; + $out.=$formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:0, 0, 0, 1); + $out.=''; + $searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); + $out.=$searchpitco; + $out.='
    '; - $out.=dol_print_date($histo[$key]['datestart'],'dayhour'); - if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) + + // Done or todo + if ($donetodo) { - $tmpa=dol_getdate($histo[$key]['datestart'],true); - $tmpb=dol_getdate($histo[$key]['dateend'],true); - if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $out.='-'.dol_print_date($histo[$key]['dateend'],'hour'); - else $out.='-'.dol_print_date($histo[$key]['dateend'],'dayhour'); + $out.=''; + $out.=' '; + $out.=$actionstatic->getNomUrl(1, -1); + $out.=''; if (isset($histo[$key]['type']) && $histo[$key]['type']=='action') { $actionstatic->type_code=$histo[$key]['acode']; $transcode=$langs->trans("Action".$histo[$key]['acode']); - $libelle=($transcode!="Action".$histo[$key]['acode']?$transcode:$histo[$key]['libelle']); + $libelle=($transcode!="Action".$histo[$key]['acode']?$transcode:$histo[$key]['alabel']); //$actionstatic->libelle=$libelle; - $actionstatic->libelle=$histo[$key]['note']; + $libelle=$histo[$key]['note']; $actionstatic->id=$histo[$key]['id']; - $out.=$actionstatic->getNomUrl(1,120); + $out.=dol_trunc($libelle,120); } if (isset($histo[$key]['type']) && $histo[$key]['type']=='mailing') { @@ -1295,11 +1213,32 @@ function show_actions_done($conf,$langs,$db,$object,$objcon='',$noprint=0) } $out.=''; - $out.=$actionstatic->type; - $out.=''; + $out.=dol_print_date($histo[$key]['datestart'],'dayhour'); + if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) + { + $tmpa=dol_getdate($histo[$key]['datestart'],true); + $tmpb=dol_getdate($histo[$key]['dateend'],true); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $out.='-'.dol_print_date($histo[$key]['dateend'],'hour'); + else $out.='-'.dol_print_date($histo[$key]['dateend'],'dayhour'); + } + $out.="'; + if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + { + if ($histo[$key]['apicto']) $out.=img_picto('', $histo[$key]['apicto']); + else { + if ($histo[$key]['acode'] == 'AC_TEL') $out.=img_picto('', 'object_phoning').' '; + if ($histo[$key]['acode'] == 'AC_FAX') $out.=img_picto('', 'object_phoning_fax').' '; + if ($histo[$key]['acode'] == 'AC_EMAIL') $out.=img_picto('', 'object_email').' '; + } } + $out.=$actionstatic->type; + $out.=''.dol_trunc($histo[$key]['note'], 40).''.$actionstatic->LibStatut($histo[$key]['percent'],3).''.$actionstatic->LibStatut($histo[$key]['percent'],3,1,$histo[$key]['datestart']).'
    '; // Left - if ($picto && $titre) print ''; - print ''; + print ''; // Center if ($center) { - print ''; + print ''; } // Right - print '
    '.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'
    '.$titre; + //if ($picto && $titre) print '
    '.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).''; + if ($picto && $titre) print img_picto('', $picto, 'class="hideonsmartphone valignmiddle" id="pictotitle"', $pictoisfullpath); + print '
    '.$titre; if (!empty($titre) && $savtotalnboflines > 0) print ' ('.$totalnboflines.')'; print '
    '.$center.''.$center.''; + print ''; if ($sortfield) $options .= "&sortfield=".$sortfield; if ($sortorder) $options .= "&sortorder=".$sortorder; // Show navigation bar @@ -3097,7 +3199,7 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so { if ($totalnboflines) // If we know total nb of lines { - $maxnbofpage=(empty($conf->dol_optimize_smallscreen) ? 4 : 2); // page nb before and after selected page + ... + first or last + $maxnbofpage=(empty($conf->dol_optimize_smallscreen) ? 4 : 1); // page nb before and after selected page + ... + first or last if ($limit > 0) $nbpages=ceil($totalnboflines/$limit); else $nbpages=1; @@ -3106,20 +3208,20 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so if ($cpt>=1) { - $pagelist.= 'dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'':'data-role="button" ').'href="'.$file.'?page=0'.$options.'">1'; - if ($cpt > 2) $pagelist.='dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'class="inactive"':'data-role="button"').'>...'; - else if ($cpt == 2) $pagelist.='dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'':'data-role="button" ').'href="'.$file.'?page=1'.$options.'">2'; + $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'':'data-role="button" ').'href="'.$file.'?page=0'.$options.'">1'; + if ($cpt > 2) $pagelist.='dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'class="inactive"':'data-role="button"').'>...'; + else if ($cpt == 2) $pagelist.='dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'':'data-role="button" ').'href="'.$file.'?page=1'.$options.'">2'; } do { if ($cpt==$page) { - $pagelist.= 'dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'class="active"':'data-role="button"').'>'.($page+1).''; + $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'class="active"':'data-role="button"').'>'.($page+1).''; } else { - $pagelist.= 'dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'':'data-role="button" ').'href="'.$file.'?page='.$cpt.$options.'">'.($cpt+1).''; + $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'':'data-role="button" ').'href="'.$file.'?page='.$cpt.$options.'">'.($cpt+1).''; } $cpt++; } @@ -3127,14 +3229,14 @@ function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $so if ($cpt<$nbpages) { - if ($cpt<$nbpages-2) $pagelist.= 'dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'class="inactive"':'data-role="button"').'>...'; - else if ($cpt == $nbpages-2) $pagelist.= 'dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'':'data-role="button" ').'href="'.$file.'?page='.($nbpages-2).$options.'">'.($nbpages - 1).''; - $pagelist.= 'dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'':'data-role="button" ').'href="'.$file.'?page='.($nbpages-1).$options.'">'.$nbpages.''; + if ($cpt<$nbpages-2) $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'class="inactive"':'data-role="button"').'>...'; + else if ($cpt == $nbpages-2) $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'':'data-role="button" ').'href="'.$file.'?page='.($nbpages-2).$options.'">'.($nbpages - 1).''; + $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'':'data-role="button" ').'href="'.$file.'?page='.($nbpages-1).$options.'">'.$nbpages.''; } } else { - $pagelist.= 'dol_use_jmobile)?' class="pagination"':'').'>dol_use_jmobile)?'class="active"':'data-role="button"').'>'.($page+1).""; + $pagelist.= 'dol_use_jmobile != 4)?' class="pagination"':'').'>dol_use_jmobile != 4)?'class="active"':'data-role="button"').'>'.($page+1).""; } } print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtml, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist @@ -3213,7 +3315,7 @@ function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betwee } if ($page > 0) { - if (empty($conf->dol_use_jmobile)) print ''; + if (($conf->dol_use_jmobile != 4)) print ''; else print '
  • '.$langs->trans("Previous").'
  • '; } if ($betweenarrows) @@ -3222,7 +3324,7 @@ function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betwee } if ($nextpage > 0) { - if (empty($conf->dol_use_jmobile)) print ''; + if (($conf->dol_use_jmobile != 4)) print ''; else print '
  • '.$langs->trans("Next").'
  • '; } if ($afterarrows) @@ -3239,13 +3341,13 @@ function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betwee * Return a string with VAT rate label formated for view output * Used into pdf and HTML pages * - * @param float $rate Rate value to format (19.6 19,6 19.6% 19,6%,...) + * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...) * @param boolean $addpercent Add a percent % sign in output * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat) * @param int $usestarfornpr 1=Use '*' for NPR vat rate intead of MAIN_LABEL_MENTION_NPR - * @return string String with formated amounts (19,6 or 19,6% or 8.5% NPR or 8.5% *) + * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)') */ -function vatrate($rate,$addpercent=false,$info_bits=0,$usestarfornpr=0) +function vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0) { $morelabel=''; @@ -3257,7 +3359,7 @@ function vatrate($rate,$addpercent=false,$info_bits=0,$usestarfornpr=0) if (preg_match('/\((.*)\)/',$rate,$reg)) { $morelabel=' ('.$reg[1].')'; - $rate=preg_replace('/'.preg_quote($morelabel,'/').'/','',$rate); + $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate); } if (preg_match('/\*/',$rate) || preg_match('/'.constant('MAIN_LABEL_MENTION_NPR').'/i',$rate)) { @@ -3514,7 +3616,7 @@ function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller $vatratecleaned = $vatrate; if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)" { - $vatratecleaned = $reg[1]; + $vatratecleaned = trim($reg[1]); $vatratecode = $reg[2]; } @@ -3528,7 +3630,7 @@ function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller { if ($local == 1) { - if (! $mysoc->localtax1_assuj) return 0; + if (! $mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0; if ($thirdparty_seller->id == $mysoc->id) { if (! $thirdparty_buyer->localtax1_assuj) return 0; @@ -3541,7 +3643,7 @@ function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller if ($local == 2) { - if (! $mysoc->localtax2_assuj) return 0; + if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0; if ($thirdparty_seller->id == $mysoc->id) { if (! $thirdparty_buyer->localtax2_assuj) return 0; @@ -3813,7 +3915,7 @@ function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisi * @param int $idprod Id of product or 0 if not a predefined product * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...) * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" order/invoice) - * @return int <0 if KO, Vat rate if OK + * @return float Vat rate * @see get_product_localtax_for_country */ function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice=0) @@ -3963,7 +4065,7 @@ function get_product_localtax_for_country($idprod, $local, $thirdparty_seller) * @param Societe $thirdparty_buyer Objet societe acheteuse * @param int $idprod Id product * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice) - * @return float Taux de tva a appliquer, -1 si ne peut etre determine + * @return float Vat rate to use, -1 if we can't guess it * @see get_default_npr, get_default_localtax */ function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0) @@ -4167,13 +4269,13 @@ function yn($yesno, $case=1, $color=0) * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...') * @return string Dir to use ending. Example '' or '1/' or '1/2/' */ -function get_exdir($num,$level,$alpha,$withoutslash,$object,$modulepart) +function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart) { global $conf; $path = ''; - $arrayforoldpath=array('cheque','user','category','holiday','shipment', 'member','don','donation','supplier_invoice','invoice_supplier','mailing'); + $arrayforoldpath=array('cheque','user','category','holiday','shipment','supplier_invoice','invoice_supplier','mailing'); if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[]='product'; if (! empty($level) && in_array($modulepart, $arrayforoldpath)) { @@ -4190,7 +4292,7 @@ function get_exdir($num,$level,$alpha,$withoutslash,$object,$modulepart) // TODO // We will enhance here a common way of forging path for document storage // Here, object->id, object->ref and object->modulepart are required. - if (in_array($modulepart, array('thirdparty','contact'))) + if (in_array($modulepart, array('thirdparty','contact','member'))) { $path=$object->ref?$object->ref:$object->id; } @@ -4512,7 +4614,7 @@ function dol_nboflines_bis($text,$maxlinesize=0,$charset='UTF-8') else $pattern = '/(]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); - $nblines = floor((count($a)+1)/2); + $nblines = (int) floor((count($a)+1)/2); // count possible auto line breaks if($maxlinesize) { @@ -5095,7 +5197,7 @@ function dol_osencode($str) * Store also Code-Id into a cache to speed up next request on same key. * * @param DoliDB $db Database handler - * @param string $key Code to get Id + * @param string $key Code or Id to get Id or Code * @param string $tablename Table name without prefix * @param string $fieldkey Field for code * @param string $fieldid Field for id @@ -5355,7 +5457,7 @@ function printCommonFooter($zone='private') print ''."\n"; print "page_y=getParameterByName('page_y', 0);"; - print "if (page_y > 0) $('html, body').scrollTop(page_y);"; + print "if (page_y > 0) $('html, body').scrollTop(page_y);\n"; print ''."\n"; print 'jQuery(".reposition").click(function() { @@ -5377,7 +5479,7 @@ function printCommonFooter($zone='private') // Google Analytics (need Google module) if (! empty($conf->google->enabled) && ! empty($conf->global->MAIN_GOOGLE_AN_ID)) { - if (empty($conf->dol_use_jmobile)) + if (($conf->dol_use_jmobile != 4)) { print "\n"; 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 '
    '; - print ''; + + /* Not yet supporter for supplier + if ($societe->id > 0) + { + // Replacement + if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) + { + 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 '
    '; + } + } + else + { + print '
    '; + $tmp=' '; + $text = $tmp.$langs->trans("InvoiceReplacement") . ' '; + $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') '; + $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3); + print $desc; + print '
    '; + } + */ + + 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=' + jQuery(document).ready(function() { + if (! jQuery("#radio_creditnote").is(":checked")) + { + jQuery("#credit_note_options").hide(); + } + jQuery("#radio_creditnote").click(function() { + jQuery("#credit_note_options").show(); + }); + jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() { + jQuery("#credit_note_options").hide(); + }); + }); + '; + $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 '
    '; + } + } + 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 '
    '; + + print ''; + + if ($socid > 0) + { + // Discounts for third party + print '' . $langs->trans('Discounts') . ''; + if ($soc->remise_percent) + print $langs->trans("CompanyHasRelativeDiscount", '' . $soc->remise_percent . ''); + else + print $langs->trans("CompanyHasNoRelativeDiscount"); + print ' (' . $langs->trans("EditRelativeDiscount") . ')'; + print '. '; + print '
    '; + if ($absolute_discount) + print $langs->trans("CompanyHasAbsoluteDiscount", '' . price($absolute_discount) . '', $langs->trans("Currency" . $conf->currency)); + else + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + print ' (' . $langs->trans("EditGlobalDiscounts") . ')'; + print '.'; + print ''; + } // Label print ''.$langs->trans('Label').''; @@ -1474,35 +1823,6 @@ if ($action == 'create') print '' . $langs->trans('MulticurrencyTotalTTC') . '' . price($objectsrc->multicurrency_total_ttc) . ""; } } - else - { - // TODO more bugs - if (1==2 && ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) - { - print ''; - print ' '; - print ''.$langs->trans('Label').''; - print ''.$langs->trans('PriceUHT').''; - print ''.$langs->trans('VAT').''; - print ''.$langs->trans('Qty').''; - print ''.$langs->trans('PriceUTTC').''; - print ''; - - for ($i = 1 ; $i < 9 ; $i++) - { - $value_qty = '1'; - $value_tauxtva = ''; - print ''.$i.''; - print ''; - print ''; - print ''; - print $form->load_tva('tauxtva'.$i,$value_tauxtva,$societe,$mysoc); - print ''; - print ''; - print ''; - } - } - } // Other options $parameters=array('colspan' => ' colspan="6"'); @@ -1562,6 +1882,8 @@ else // fetch optionals attributes and labels $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $alreadypaid=$object->getSommePaiement(); + /* * View card */ @@ -1659,7 +1981,8 @@ else $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; @@ -1670,31 +1993,61 @@ else print $formconfirm; - /** - * Invoice - */ - print ''; - + // Supplier invoice card $linkback = ''.$langs->trans("BackToList").''; - // Ref - print ''; - print "\n"; + $morehtmlref='
    '; + // Ref supplier + $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->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->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($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.='
    '; - // Ref supplier - print ''; + $object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status - // Third party - print ''; - print ''; + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref'); - print '
    '.$form->editfieldkey("RefSupplier",'ref_supplier',$object->ref_supplier,$object,($object->statutrights->fournisseur->facture->creer)).''; - print $form->editfieldval("RefSupplier",'ref_supplier',$object->ref_supplier,$object,($object->statutrights->fournisseur->facture->creer)); - print '
    '.$langs->trans('Supplier').''.$societe->getNomUrl(1,'supplier'); - print '   ('.$langs->trans('OtherBills').')
    '; // Type - print ''; - print ''; - - /* - * List of payments - */ - $nbrows=9; $nbcols=3; - if (! empty($conf->projet->enabled)) $nbrows++; - if (! empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } - if (! empty($conf->incoterm->enabled)) $nbrows++; - - // Local taxes - if ($societe->localtax1_assuj=="1") $nbrows++; - if ($societe->localtax2_assuj=="1") $nbrows++; - - print ''; - + print ''; print ''; $form_permission = $object->statutrights->fournisseur->facture->creer && $object->getSommePaiement() <= 0; @@ -1955,58 +2200,10 @@ else print ''; // Status - $alreadypaid=$object->getSommePaiement(); - 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 ''; - - if (!empty($conf->multicurrency->enabled)) - { - // Multicurrency Amount HT - print ''; - print ''; - print ''; - - // Multicurrency Amount VAT - print ''; - print ''; - print ''; - - // Multicurrency Amount TTC - print ''; - print ''; - print ''; - } + //print ''; // Project + /* if (! empty($conf->projet->enabled)) { $langs->load('projects'); @@ -2036,6 +2233,7 @@ else print ''; print ''; } + */ // Incoterms if (!empty($conf->incoterm->enabled)) @@ -2060,11 +2258,309 @@ else print ''; } - // Other attributes - $cols = 4; - 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 '
    '.$langs->trans('Type').''; + print '
    '.$langs->trans('Type').''; print $object->getLibType(); if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) { @@ -1734,115 +2087,7 @@ else // Label print '
    '.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).''.$form->editfieldval("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).''; - - $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'; - $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'; - $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; $totalpaye = 0; - print ''; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - - $var=true; - if ($num > 0) - { - while ($i < $num) - { - $objp = $db->fetch_object($result); - $var=!$var; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) - { - $bankaccountstatic->id=$objp->baid; - $bankaccountstatic->ref=$objp->baref; - $bankaccountstatic->label=$objp->baref; - print ''; - } - print ''; - print ''; - print ''; - $totalpaye += $objp->amount; - $i++; - } - } - else - { - print ''; - } - - if ($object->paye == 0) - { - print ''; - print ''; - - $resteapayer = $object->total_ttc - $totalpaye; - - print ''; - print ''; - } - print '
    '.$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; - $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($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").'
    '.$langs->trans('AlreadyPaid').' :'.price($totalpaye).'
    '.$langs->trans("Billed").' :'.price($object->total_ttc).'
    '.$langs->trans('RemainderToPay').' :'.price($resteapayer).'
    '; - $db->free($result); - } - else - { - dol_print_error($db); - } - print '
    '.$form->editfieldval("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).'
    '.$langs->trans('Status').''.$object->getLibStatut(4,$alreadypaid).'
    '.$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).'
    ' . 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('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    '.$langs->trans('Status').''.$object->getLibStatut(4,$alreadypaid).'

    '; + print ''; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + { + // Multicurrency Amount HT + print ''; + print ''; + print ''; + + // Multicurrency Amount VAT + print ''; + print ''; + print ''; + + // Multicurrency Amount TTC + print ''; + 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 ''; + + 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('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)) . '
    '.$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).'
    '; + + /* + * List of payments + */ + $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->multicurrency->enabled)) $nbrows += 5; + + // 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'; + $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'; + $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; $totalpaye = 0; + print ''; + 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=!$var; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) + { + $bankaccountstatic->id=$objp->baid; + $bankaccountstatic->ref=$objp->baref; + $bankaccountstatic->label=$objp->baref; + print ''; + } + print ''; + print ''; + print ''; + $totalpaye += $objp->amount; + $i++; + } + } + else + { + print ''; + } + + /* + if ($object->paye == 0) + { + print ''; + print ''; + + $resteapayer = $object->total_ttc - $totalpaye; + + print ''; + print ''; + } + */ + + $db->free($result); + } + else + { + dol_print_error($db); + } + + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { + // Total already paid + print ''; + + $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 FactureFournisseur($db); + while ($i < $num) { + $obj = $db->fetch_object($resql); + $invoice->fetch($obj->fk_facture_source); + print ''; + print ''; + print ''; + $i ++; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + $creditnoteamount += $obj->amount_ttc; + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + $depositamount += $obj->amount_ttc; + } + } else { + dol_print_error($db); + } + + // Paye partiellement 'escompte' + if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'badsupplier' + if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'badsupplier') { + print ''; + // $resteapayeraffiche=0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'product_returned' + if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'product_returned') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + // Paye partiellement ou Abandon 'abandon' + if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') { + print ''; + $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; + } + + // Billed + print ''; + + // Remainder to pay + print ''; + print ''; + print ''; + } + else // Credit note + { + // Total already paid back + print ''; + + // Billed + print ''; + + // Remainder to pay back + print ''; + print ''; + print ''; + + // Sold credit note + // print ''; + // print ''; + } + + 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; + $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").'
    '.$langs->trans('AlreadyPaid').' :'.price($totalpaye).'
    '.$langs->trans("Billed").' :'.price($object->total_ttc).'
    '.$langs->trans('RemainderToPay').' :'.price($resteapayer).'
    '; + if ($object->type != FactureFournisseur::TYPE_DEPOSIT) + print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); + else + print $langs->trans('AlreadyPaid'); + print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
    '; + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + print $langs->trans("CreditNote") . ' '; + if ($invoice->type == FactureFournisseur::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) . ' 
    ' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
    '; + if ($resteapayeraffiche >= 0) + print $langs->trans('RemainderToPay'); + else + print $langs->trans('ExcessReceived'); + print ' :' . price($resteapayeraffiche) . ' 
    '; + print $langs->trans('AlreadyPaidBack'); + print ' :' . price($sign * $totalpaye) . ' 
    ' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
    '; + if ($resteapayeraffiche <= 0) + print $langs->trans('RemainderToPayBack'); + else + print $langs->trans('ExcessPaydBack'); + print ' :' . price($sign * $resteapayeraffiche) . ' 
    '.$langs->trans('TotalTTC').' :'.price($sign * + // $object->total_ttc).' 
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '

    '; if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { @@ -2085,16 +2581,12 @@ else /* * Lines */ - //$result = $object->getLinesArray(); - - - print '
    - - - - - - '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; if (! empty($conf->use_javascript_ajax) && $object->statut == FactureFournisseur::STATUS_DRAFT) { include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; @@ -2102,7 +2594,7 @@ else print ''; - global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; + global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; $forceall=1; $senderissupplier=1; $dateSelector=0; $inputalsopricewithtax=1; // Show object lines @@ -2177,7 +2669,6 @@ else else print ''.$langs->trans('SendByMail').''; } - // Make payments if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) { @@ -2224,6 +2715,15 @@ else print 'socid.'">'.$langs->trans('ToClone').''; } + // Create a credit note + if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $user->rights->fournisseur->facture->creer) + { + if (! $objectidnext) + { + print ''; + } + } + // Delete if ($action != 'edit' && $user->rights->fournisseur->facture->supprimer) { @@ -2305,7 +2805,7 @@ else if (! $file || ! is_readable($file)) { $result = $object->generateDocument(GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) + if ($result < 0) { dol_print_error($db,$object->error,$object->errors); exit; @@ -2324,10 +2824,12 @@ else 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 = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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='sin'.$object->id; if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 3ca1c2d05fa..c9a40f9b590 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -208,6 +208,7 @@ if ($object->id > 0) $modulepart = 'facture_fournisseur'; $permission = $user->rights->fournisseur->facture->creer; + $permtoedit = $user->rights->fournisseur->facture->creer; $param = '&facid=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index d234ea01bcb..ebe65f62122 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -58,7 +58,6 @@ if ($user->societe_id > 0) } $mode=GETPOST("mode"); -$modesearch=GETPOST("mode_search"); $search_product_category=GETPOST('search_product_category','int'); $search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha'); @@ -215,27 +214,6 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter") || GETPOS $option=''; } -if ($mode == 'search') -{ - if ($modesearch == 'soc') - { - $sql = "SELECT s.rowid FROM ".MAIN_DB_PREFIX."societe as s "; - $sql.= " WHERE s.nom LIKE '%".$db->escape($socname)."%'"; - $sql.= " AND s.entity IN (".getEntity('societe', 1).")"; - } - - $resql=$db->query($sql); - if ($resql) - { - if ( $db->num_rows($resql) == 1) - { - $obj = $db->fetch_object($resql); - $socid = $obj->rowid; - } - $db->free($resql); - } -} - if (empty($reshook)) { // Mass actions. Controls on number of lines checked @@ -313,7 +291,7 @@ if ($search_ref) else $sql .= natural_search('f.ref', $search_ref); } if ($search_ref) $sql .= natural_search('f.ref', $search_ref); -if ($search_ref_supplier) $sql .= natural_search('f.ref_supplier', $search_ref_supplier); +if ($search_refsupplier) $sql .= natural_search('f.ref_supplier', $search_refsupplier); if ($search_project) $sql .= natural_search('p.ref', $search_project); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_town) $sql.= natural_search('s.town', $search_town); @@ -322,7 +300,7 @@ if ($search_state) $sql.= natural_search("state.nom",$search_state); if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_montant_ht != '') $sql.= natural_search('f.total', $search_montant_ht, 1); +if ($search_montant_ht != '') $sql.= natural_search('f.total_ht', $search_montant_ht, 1); if ($search_montant_vat != '') $sql.= natural_search('f.total_tva', $search_montant_vat, 1); if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); if ($search_status != '' && $search_status >= 0) $sql.= " AND f.fk_statut = ".$db->escape($search_status); @@ -427,7 +405,7 @@ if ($resql) if ($month_lim) $param.='&month_lim='.urlencode($month_lim); if ($year_lim) $param.='&year_lim=' .urlencode($year_lim); if ($search_ref) $param.='&search_ref='.urlencode($search_ref); - if ($search_refsupplier) $param.='&search_refsupplier'.urlencode($search_refsupplier); + if ($search_refsupplier) $param.='&search_refsupplier='.urlencode($search_refsupplier); if ($search_label) $param.='&search_label='.urlencode($search_label); if ($search_company) $param.='&search_company='.urlencode($search_company); if ($search_montant_ht != '') $param.='&search_montant_ht='.urlencode($search_montant_ht); @@ -457,7 +435,7 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("BillsSuppliers").($socid?" $soc->name.":""),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,'title_accountancy',0,'','',$limit); + print_barre_liste($langs->trans("BillsSuppliers").($socid?" - $soc->name":""),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,'title_accountancy',0,'','',$limit); if ($search_all) { diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index 4e6795fd4fa..764a875019d 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -349,21 +349,17 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '
    '; - print ''; print ''; - print ''; + print ''; print ''; - print ''; - print ''; if (! empty($conf->banque->enabled)) { print ''; + print ''; } + print ''; + print ''; + print ''; print '
    '.$langs->trans('Company').''; + print '
    '.$langs->trans('Company').''; $supplierstatic->id=$obj->socid; $supplierstatic->name=$obj->name; print $supplierstatic->getNomUrl(1,'supplier'); print '
    '.$langs->trans('Date').''; $form->select_date($dateinvoice,'','','','',"addpaiement",1,1,0,0,'','',$object->date); - print ''.$langs->trans('Comments').'
    '.$langs->trans('PaymentMode').''; $form->select_types_paiements(empty($_POST['paiementid'])?$obj->fk_mode_reglement:$_POST['paiementid'],'paiementid'); print ''; - print '
    '.$langs->trans('Numero').'
    '.$langs->trans('Account').''; @@ -372,8 +368,12 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } else { - print '
     
     
    '.$langs->trans('Numero').'
    '.$langs->trans('Comments').''; + print '
    '; dol_fiche_end(); @@ -404,7 +404,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $i = 0; print '
    '; - if(!empty($conf->global->INVOICE_AUTO_FILLJS)){ + if (!empty($conf->use_javascript_ajax)){ //Add js for AutoFill print "\n".''."\n"; - } + }*/ if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) // jQuery plugin "mutiselect", "multiple-select", "select2"... { $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT; @@ -1068,7 +1079,11 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs // jQuery jMobile if (! $disablejmobile && (! empty($conf->global->MAIN_USE_JQUERY_JMOBILE) || defined('REQUIRE_JQUERY_JMOBILE') || ! empty($conf->dol_use_jmobile))) { - print ''."\n"; + $tmp=basename($_SERVER["PHP_SELF"]); + if ($tmp == 'get_menudiv.php' || $conf->dol_use_jmobile == 4) + { + print ''."\n"; + } } } @@ -1089,14 +1104,6 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs } } } - $themeparam='?lang='.$langs->defaultlang.'&theme='.$conf->theme.(GETPOST('optioncss')?'&optioncss='.GETPOST('optioncss','alpha',1):'').'&userid='.$user->id.'&entity='.$conf->entity; - $themeparam.=($ext?'&'.$ext:''); - if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&dol_resetcache='.$_SESSION['dol_resetcache']; - if (GETPOST('dol_hide_topmenu')) { $themeparam.='&dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); } - if (GETPOST('dol_hide_leftmenu')) { $themeparam.='&dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); } - if (GETPOST('dol_optimize_smallscreen')) { $themeparam.='&dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); } - if (GETPOST('dol_no_mouse_hover')) { $themeparam.='&dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); } - if (GETPOST('dol_use_jmobile')) { $themeparam.='&dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); } //print 'themepath='.$themepath.' themeparam='.$themeparam;exit; print ''."\n"; if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print ''."\n".''."\n"; @@ -1212,6 +1219,7 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs print ''."\n"; }*/ // jQuery DataTables + /* Removed a old hidden problematic feature never used in Dolibarr. If an external module need datatable, the module must provide all lib it needs and manage version problems with other dolibarr components if (! empty($conf->global->MAIN_USE_JQUERY_DATATABLES) || (defined('REQUIRE_JQUERY_DATATABLES') && constant('REQUIRE_JQUERY_DATATABLES'))) { print ''."\n"; @@ -1222,9 +1230,7 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs print ''."\n"; print ''."\n"; print ''."\n"; - print ''."\n"; - print ''."\n"; - } + }*/ // jQuery Timepicker if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER')) { @@ -1243,32 +1249,36 @@ function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs // We must force not using ajax because cache of jquery does not load js of other pages. // This also increase seriously speed onto mobile device where complex js code is very slow and memory very low. // Note: dol_use_jmobile=1 use jmobile without ajax, dol_use_jmobile=2 use jmobile with ajax - if (empty($conf->dol_use_jmobile) || ($conf->dol_use_jmobile != 2 && $conf->dol_use_jmobile != 3)) - { - print ''; - } - if (empty($conf->dol_use_jmobile) || $conf->dol_use_jmobile != 3) print ''."\n"; + // 3=??? + // 4=all pages, not only menu + $tmp=basename($_SERVER["PHP_SELF"]); + if ($tmp == 'get_menudiv.php' || $conf->dol_use_jmobile == 4) + { + if (empty($conf->dol_use_jmobile) || ($conf->dol_use_jmobile != 2 && $conf->dol_use_jmobile != 3)) + { + print ''; + } + if (empty($conf->dol_use_jmobile) || $conf->dol_use_jmobile != 3) print ''."\n"; + } } } @@ -1417,7 +1427,7 @@ function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $a if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') { $logouthtmltext.=$langs->trans("Logout").'
    '; - + $logouttext .=''; $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1); $logouttext .=''; @@ -1428,7 +1438,7 @@ function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $a $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1); } } - + print '

    '; } - - + $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; @@ -586,6 +651,15 @@ if ($resql) $tmpkey=preg_replace('/search_options_/','',$key); if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } + + // List of mass actions available + $arrayofmassactions = array( + // 'presend'=>$langs->trans("SendByMail"), + // 'builddoc'=>$langs->trans("PDFMerge"), + ); + //if ($user->rights->stock->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); + if ($massaction == 'presend') $arrayofmassactions=array(); + $massactionbutton=$form->selectMassAction('', $arrayofmassactions); print ''; if ($optioncss != '') print ''; @@ -598,84 +672,199 @@ if ($resql) print ''; if ($id > 0) print ''; - if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder,'',$num, $nbtotalofrecords, '', 0, '', '', $limit); - else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder,'',$num, $nbtotalofrecords, 'title_generic', 0, '', '', $limit); + if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder,$massactionbutton,$num, $nbtotalofrecords, '', 0, '', '', $limit); + else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder,$massactionbutton,$num, $nbtotalofrecords, 'title_generic', 0, '', '', $limit); - print ''; - print ""; - //print_liste_field_titre($langs->trans("Id"),$_SERVER["PHP_SELF"], "m.rowid","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"], "m.datem","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("ProductRef"),$_SERVER["PHP_SELF"], "p.ref","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("ProductLabel"),$_SERVER["PHP_SELF"], "p.ref","",$param,"",$sortfield,$sortorder); - if (! empty($conf->productbatch->enabled)) + if ($sall) + { + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + } + + $moreforfilter=''; + + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; + + if (! empty($moreforfilter)) { - $langs->load("productbatch"); - print_liste_field_titre($langs->trans("BatchNumberShort"),$_SERVER["PHP_SELF"],'m.batch','',$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("EatByDate"),$_SERVER["PHP_SELF"],'m.eatby','',$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("SellByDate"),$_SERVER["PHP_SELF"],'m.sellby','',$param,'align="center"',$sortfield,$sortorder); + print '
    '; + print $moreforfilter; + print '
    '; } - if (! $id > 0) print_liste_field_titre($langs->trans("Warehouse"),$_SERVER["PHP_SELF"], "","",$param,"",$sortfield,$sortorder); // We are on a specific warehouse card, no filter on other should be possible - print_liste_field_titre($langs->trans("Author"),$_SERVER["PHP_SELF"], "m.fk_user_author","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("InventoryCodeShort"),$_SERVER["PHP_SELF"], "m.inventorycode","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("LabelMovement"),$_SERVER["PHP_SELF"], "m.label","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Source"),$_SERVER["PHP_SELF"], "","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Qty"),$_SERVER["PHP_SELF"], "m.value","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre(""); + + $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; + $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + + print '
    '."\n"; + print ""; + if (! empty($arrayfields['m.rowid']['checked'])) print_liste_field_titre($arrayfields['m.rowid']['label'],$_SERVER["PHP_SELF"],'m.rowid','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['m.datem']['checked'])) print_liste_field_titre($arrayfields['m.datem']['label'],$_SERVER["PHP_SELF"],'m.datem','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'],$_SERVER["PHP_SELF"],'p.ref','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['p.label']['checked'])) print_liste_field_titre($arrayfields['p.label']['label'],$_SERVER["PHP_SELF"],'p.label','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['m.batch']['checked'])) print_liste_field_titre($arrayfields['m.batch']['label'],$_SERVER["PHP_SELF"],'m.batch','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['pl.eatby']['checked'])) print_liste_field_titre($arrayfields['pl.eatby']['label'],$_SERVER["PHP_SELF"],'pl.eatby','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['pl.sellby']['checked'])) print_liste_field_titre($arrayfields['pl.sellby']['label'],$_SERVER["PHP_SELF"],'pl.sellby','',$param,'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['m.warehouse']['checked'])) print_liste_field_titre($arrayfields['m.warehouse']['label'],$_SERVER["PHP_SELF"], "","",$param,"",$sortfield,$sortorder); // We are on a specific warehouse card, no filter on other should be possible + if (! empty($arrayfields['m.fk_user_author']['checked'])) print_liste_field_titre($arrayfields['m.fk_user_author']['label'],$_SERVER["PHP_SELF"], "m.fk_user_author","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['m.inventorycode']['checked'])) print_liste_field_titre($arrayfields['m.inventorycode']['label'],$_SERVER["PHP_SELF"], "m.inventorycode","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['m.label']['checked'])) print_liste_field_titre($arrayfields['m.label']['label'],$_SERVER["PHP_SELF"], "m.label","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['origin']['checked'])) print_liste_field_titre($arrayfields['origin']['label'],$_SERVER["PHP_SELF"], "","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['m.value']['checked'])) print_liste_field_titre($langs->trans("Qty"),$_SERVER["PHP_SELF"], "m.value","",$param,'align="right"',$sortfield,$sortorder); + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } + } + // Hook fields + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (! empty($arrayfields['m.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + if (! empty($arrayfields['m.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; // Lignes des champs de filtre print ''; - print ''; - // Product Ref - print ''; - // Product label - print ''; - // Batch - if (! empty($conf->productbatch->enabled)) - { - print ''; - print ''; - print ''; - } - // Warehouse - if (! $id > 0) + if (! empty($arrayfields['m.rowid']['checked'])) { - print ''; + } + if (! empty($arrayfields['m.datem']['checked'])) + { + print ''; + } + if (! empty($arrayfields['p.ref']['checked'])) + { + // Product Ref + print ''; + } + if (! empty($arrayfields['p.label']['checked'])) + { + // Product label + print ''; + } + // Batch + if (! empty($arrayfields['m.batch']['checked'])) + { + print ''; + } + if (! empty($arrayfields['pl.eatby']['checked'])) + { + print ''; + } + if (! empty($arrayfields['pl.sellby']['checked'])) + { + print ''; + } + // Warehouse + if (! empty($arrayfields['m.warehouse']['checked'])) + { + print ''; } - // Author - print ''; - // Inventory code - print ''; - // Label of movement - print ''; - // Origin of movement - print ''; - // Qty - print ''; + if (! empty($arrayfields['m.fk_user_author']['checked'])) + { + // Author + print ''; + } + if (! empty($arrayfields['m.inventorycode']['checked'])) + { + // Inventory code + print ''; + } + if (! empty($arrayfields['m.label']['checked'])) + { + // Label of movement + print ''; + } + if (! empty($arrayfields['origin']['checked'])) + { + // Origin of movement + print ''; + } + if (! empty($arrayfields['m.value']['checked'])) + { + // Qty + print ''; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields); + $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['m.datec']['checked'])) + { + print ''; + } + // Date modification + if (! empty($arrayfields['m.tms']['checked'])) + { + print ''; + } // Actions print '"; // Id movement - //print ''; // This is primary not movement id - // Date - print ''; - // Product ref - print '\n"; - // Product label - print '\n"; - // Batch - if (! empty($conf->productbatch->enabled)) - { - print ''; - print ''; - print ''; + if (! empty($arrayfields['m.rowid']['checked'])) + { + print ''; // This is primary not movement id + } + if (! empty($arrayfields['m.datem']['checked'])) + { + // Date + print ''; + } + if (! empty($arrayfields['p.ref']['checked'])) + { + // Product ref + print '\n"; + } + if (! empty($arrayfields['p.label']['checked'])) + { + // Product label + print '\n"; + } + if (! empty($arrayfields['m.batch']['checked'])) + { + print ''; + } + if (! empty($arrayfields['pl.eatby']['checked'])) + { + print ''; + } + if (! empty($arrayfields['pl.sellby']['checked'])) + { + print ''; } // Warehouse - if (! $id > 0) + if (! empty($arrayfields['m.warehouse']['checked'])) { print '\n"; } // Author - print '\n"; - // Inventory code - print ''; - // Label of movement - print ''; - // Origin of movement - print ''; - // Value - print ''; - - print ''; + if (! empty($arrayfields['m.fk_user_author']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['m.inventorycode']['checked'])) + { + // Inventory code + print ''; + } + if (! empty($arrayfields['m.label']['checked'])) + { + // Label of movement + print ''; + } + if (! empty($arrayfields['origin']['checked'])) + { + // Origin of movement + print ''; + } + if (! empty($arrayfields['m.value']['checked'])) + { + // Qty + print ''; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; print "\n"; $i++; diff --git a/htdocs/product/stock/product.php b/htdocs/product/stock/product.php index 2411dde51e4..4482e249410 100644 --- a/htdocs/product/stock/product.php +++ b/htdocs/product/stock/product.php @@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productstockentrepot.class.php'; if (! empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; $langs->load("products"); @@ -63,12 +64,97 @@ if ($user->societe_id) $socid=$user->societe_id; $result=restrictedArea($user,'produit&stock',$id,'product&product','','',$fieldid); +$object = new Product($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + +if ($id > 0 || ! empty($ref)) +{ + $result = $object->fetch($id, $ref); + +} +$modulepart='product'; + +// Get object canvas (By default, this is not defined, so standard usage of dolibarr) +$canvas = !empty($object->canvas)?$object->canvas:GETPOST("canvas"); +$objcanvas=null; +if (! empty($canvas)) +{ + require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; + $objcanvas = new Canvas($db,$action); + $objcanvas->getCanvas('stockproduct','card',$canvas); +} + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('stockproductcard','globalcard')); + + /* * Actions */ if ($cancel) $action=''; +$parameters=array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if($action == 'addlimitstockwarehouse') { + + $seuil_stock_alerte = GETPOST('seuil_stock_alerte'); + $desiredstock = GETPOST('desiredstock'); + + $maj_ok = true; + if($seuil_stock_alerte == '') { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("StockLimit")), null, 'errors'); + $maj_ok = false; + } + if($desiredstock == '') { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DesiredStock")), null, 'errors'); + $maj_ok = false; + } + + if($maj_ok) { + + $pse = new ProductStockEntrepot($db); + if($pse->fetch('', GETPOST('id'), GETPOST('fk_entrepot')) > 0) { + + // Update + $pse->seuil_stock_alerte = $seuil_stock_alerte; + $pse->desiredstock = $desiredstock; + if($pse->update($user) > 0) setEventMessage($langs->trans('ProductStockWarehouseUpdated')); + + } else { + + // Create + $pse->fk_entrepot = GETPOST('fk_entrepot'); + $pse->fk_product = GETPOST('id'); + $pse->seuil_stock_alerte = GETPOST('seuil_stock_alerte'); + $pse->desiredstock = GETPOST('desiredstock'); + if($pse->create($user) > 0) setEventMessage($langs->trans('ProductStockWarehouseCreated')); + + } + + } + + header("Location: ".$_SERVER["PHP_SELF"]."?id=".GETPOST('id')); + exit; + +} + +if($action == 'delete_productstockwarehouse') +{ + + $pse = new ProductStockEntrepot($db); + $pse->fetch(GETPOST('fk_productstockwarehouse')); + if($pse->delete($user) > 0) setEventMessage($langs->trans('ProductStockWarehouseDeleted')); + + $action = ''; + +} + // Set stock limit if ($action == 'setseuil_stock_alerte') { @@ -505,7 +591,11 @@ if ($id > 0 || $ref) print ''; - + + // Hook formObject + $parameters=array('colspan' => 3); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + // Desired stock print ''; print ""; print "
    '; - print ''; - if (empty($conf->productbatch->enabled)) print ' '; - //else print '
    '; - $syear = $year?$year:-1; - print ''; - //print $formother->selectyear($syear,'year',1, 20, 5); - print '
    '; - print ''; - print ''; - print ''; - print ''; + // Ref + print ''; + print ''; + print ''; + print ''; + if (empty($conf->productbatch->enabled)) print ' '; + //else print '
    '; + $syear = $year?$year:-1; + print ''; + //print $formother->selectyear($syear,'year',1, 20, 5); + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; //print ''; - print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1); + print $formproduct->selectWarehouses($search_warehouse, 'search_warehouse', '', 1, 0, 0, '', 0, 0, null, 'maxwidth200'); print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '  '; - print ''; - print '  '; - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '  '; + print ''; + print ''; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + print ''; + print ''; $searchpitco=$form->showFilterAndCheckAddButtons(0); @@ -690,6 +879,20 @@ if ($resql) { $objp = $db->fetch_object($resql); + $productstatic->id=$objp->rowid; + $productstatic->ref=$objp->product_ref; + $productstatic->label=$objp->produit; + $productstatic->type=$objp->type; + $productstatic->entity=$objp->entity; + $productlot->id = $objp->lotid; + $productlot->batch= $objp->batch; + $productlot->eatby= $objp->eatby; + $productlot->sellby= $objp->sellby; + + $warehousestatic->id=$objp->entrepot_id; + $warehousestatic->libelle=$objp->stock; + $warehousestatic->lieu=$objp->lieu; + $arrayofuniqueproduct[$objp->rowid]=$objp->produit; if(!empty($objp->fk_origin)) { $origin = $movement->get_origin($objp->fk_origin, $objp->origintype); @@ -700,61 +903,97 @@ if ($resql) $var=!$var; print "
    '.$objp->mid.''.dol_print_date($db->jdate($objp->datem),'dayhour').''; - $productstatic->id=$objp->rowid; - $productstatic->ref=$objp->product_ref; - $productstatic->label=$objp->produit; - $productstatic->type=$objp->type; - $productstatic->entity=$objp->entity; - print $productstatic->getNomUrl(1,'stock',16); - print "'; - /*$productstatic->id=$objp->rowid; - $productstatic->ref=$objp->produit; - $productstatic->type=$objp->type; - print $productstatic->getNomUrl(1,'',16);*/ - print $productstatic->label; - print "'.$objp->batch.''. dol_print_date($objp->eatby,'day') .''. dol_print_date($objp->sellby,'day') .''.$objp->mid.''.dol_print_date($db->jdate($objp->datem),'dayhour').''; + print $productstatic->getNomUrl(1,'stock',16); + print "'; + /*$productstatic->id=$objp->rowid; + $productstatic->ref=$objp->produit; + $productstatic->type=$objp->type; + print $productstatic->getNomUrl(1,'',16);*/ + print $productstatic->label; + print "'; + if ($productlot->id > 0) print $productlot->getNomUrl(1); + else print $productlot->batch; // the id may not be defined if movement was entered when lot was not saved or if lot was removed after movement. + print ''. dol_print_date($objp->eatby,'day') .''. dol_print_date($objp->sellby,'day') .''; - $warehousestatic->id=$objp->entrepot_id; - $warehousestatic->libelle=$objp->stock; - $warehousestatic->lieu=$objp->lieu; print $warehousestatic->getNomUrl(1); print "'; - $userstatic->id=$objp->fk_user_author; - $userstatic->lastname=$objp->login; - print $userstatic->getNomUrl(1); - print "'.$objp->inventorycode.''.$objp->label.''.$origin.''; - if ($objp->value > 0) print '+'; - print $objp->value.''; + $userstatic->id=$objp->fk_user_author; + $userstatic->lastname=$objp->login; + print $userstatic->getNomUrl(1); + print "'.$objp->inventorycode.''.$objp->label.''.$origin.''; + if ($objp->qt > 0) print '+'; + print $objp->qty; + print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
    '.$form->editfieldkey("StockLimit",'seuil_stock_alerte',$object->seuil_stock_alerte,$object,$user->rights->produit->creer).''; print $form->editfieldval("StockLimit",'seuil_stock_alerte',$object->seuil_stock_alerte,$object,$user->rights->produit->creer,'string'); print '
    '.$form->editfieldkey($form->textwithpicto($langs->trans("DesiredStock"), $langs->trans("DesiredStockDesc"), 1),'desiredstock',$object->desiredstock,$object,$user->rights->produit->creer); print ''; @@ -664,28 +754,33 @@ else /* */ /* ************************************************************************** */ +$parameters=array(); -if (empty($action) && $object->id) +$reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { - print "
    \n"; - if ($user->rights->stock->mouvement->creer) - { - print ''.$langs->trans("StockCorrection").''; - } - - //if (($user->rights->stock->mouvement->creer) && ! $object->hasbatch()) - if ($user->rights->stock->mouvement->creer) + if (empty($action) && $object->id) { - print ''.$langs->trans("StockTransfer").''; + print "
    \n"; + + if ($user->rights->stock->mouvement->creer) + { + print ''.$langs->trans("StockCorrection").''; + } + + //if (($user->rights->stock->mouvement->creer) && ! $object->hasbatch()) + if ($user->rights->stock->mouvement->creer) + { + print ''.$langs->trans("StockTransfer").''; + } + + print '
    '; } - print '
    '; } - - /* * Stock detail (by warehouse). May go down into batch details. */ @@ -824,6 +919,49 @@ print '
    "; +if(!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) { + + print '

    '; + print_titre($langs->trans('AddNewProductStockWarehouse')); + //print '
    '; + + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + + $pse = new ProductStockEntrepot($db); + $lines = $pse->fetchAll(GETPOST('id')); + + if(!empty($lines)) { + + $var=false; + foreach($lines as $line) { + + $ent = new Entrepot($db); + $ent->fetch($line['fk_entrepot']); + print ''; + print ''; + print ''; + print ''; + print ''; + $var=!$var; + + } + + } + + print "
    '.$formproduct->selectWarehouses('', 'fk_entrepot').'
    '.$ent->getNomUrl(3).''.$line['seuil_stock_alerte'].''.$line['desiredstock'].''.img_delete().'
    "; + + print ''; + +} llxFooter(); diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index b750db87234..3407c75a6f5 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -23,18 +23,6 @@ * Initialy built by build_class_from_table on 2016-05-17 12:22 */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) - // Change this following line to use the correct relative path (../, ../../, etc) $res=0; if (! $res && file_exists("../main.inc.php")) $res=@include '../main.inc.php'; // to work if your module directory is into dolibarr root htdocs directory @@ -44,18 +32,23 @@ if (! $res && file_exists("../../../../dolibarr/htdocs/main.inc.php")) $res=@inc if (! $res) die("Include of main fails"); // Change this following line to use the correct relative path from htdocs include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); -dol_include_once('/stock/class/productlot.class.php'); +include_once(DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'); +include_once(DOL_DOCUMENT_ROOT.'/product/class/product.class.php'); +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +dol_include_once('/product/stock/class/productlot.class.php'); // Load traductions files requiredby by page $langs->load("stock"); $langs->load("other"); +$langs->load("productbatch"); // Get parameters $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); $backtopage = GETPOST('backtopage'); -$myparam = GETPOST('myparam','alpha'); - +$batch = GETPOST('batch','alpha'); +$productid = GETPOST('productid','int'); +$ref = GETPOST('ref','alpha'); // ref is productid_batch $search_entity=GETPOST('search_entity','int'); $search_fk_product=GETPOST('search_fk_product','int'); @@ -64,35 +57,48 @@ $search_fk_user_creat=GETPOST('search_fk_user_creat','int'); $search_fk_user_modif=GETPOST('search_fk_user_modif','int'); $search_import_key=GETPOST('search_import_key','int'); +if (empty($action) && empty($id) && empty($ref)) $action='list'; // Protection if external user if ($user->societe_id > 0) { - //accessforbidden(); + //accessforbidden(); } +//$result = restrictedArea($user, 'mymodule', $id); -if (empty($action) && empty($id) && empty($ref)) $action='list'; -// Load object if id or ref is provided as parameter -$object=new Productlot($db); -if (($id > 0 || ! empty($ref)) && $action != 'add') +$object = new ProductLot($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +//include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id || $ref) { - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); + if ($ref) + { + $tmp=explode('_',$ref); + $productid=$tmp[0]; + $batch=$tmp[1]; + } + $object->fetch($id, $productid, $batch); } // Initialize technical object to manage hooks of modules. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('productlot')); -$extrafields = new ExtraFields($db); +$hookmanager->initHooks(array('productlotcard','globalcard')); +$permissionnote = $user->rights->stock->creer; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $user->rights->stock->creer; // Used by the include of actions_dellink.inc.php +$permissionedit = $user->rights->stock->creer; // Used by the include of actions_lineupdown.inc.php -/******************************************************************* -* ACTIONS -* -* Put here all code to do according to value of "action" parameter -********************************************************************/ + +/* + * Actions + */ $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -100,6 +106,47 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { + if ($action == 'seteatby' && $user->rights->stock->creer) + { + $newvalue = dol_mktime(12, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); + $result = $object->setValueFrom('eatby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY'); + if ($result < 0) dol_print_error($db, $object->error); + } + + if ($action == 'setsellby' && $user->rights->stock->creer) + { + $newvalue=dol_mktime(12, 0, 0, $_POST['sellbymonth'], $_POST['sellbyday'], $_POST['sellbyyear']); + $result = $object->setValueFrom('sellby', $newvalue, '', null, 'date', '', $user, 'PRODUCTLOT_MODIFY'); + if ($result < 0) dol_print_error($db, $object->error); + } + + 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) + { + // Actions on extra fields (by external module or standard code) + $hookmanager->initHooks(array('productlotdao')); + $parameters = array('id' => $object->id); + $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++; + } + } else if ($reshook < 0) + $error++; + } + + if ($error) + $action = 'edit_extras'; + } + // Action to add record if ($action == 'add') { @@ -114,14 +161,12 @@ if (empty($reshook)) /* object_prop_getpost_prop */ - $object->entity=GETPOST('entity','int'); - $object->fk_product=GETPOST('fk_product','int'); - $object->batch=GETPOST('batch','alpha'); - $object->fk_user_creat=GETPOST('fk_user_creat','int'); - $object->fk_user_modif=GETPOST('fk_user_modif','int'); - $object->import_key=GETPOST('import_key','int'); - - + $object->entity=GETPOST('entity','int'); + $object->fk_product=GETPOST('fk_product','int'); + $object->batch=GETPOST('batch','alpha'); + $object->fk_user_creat=GETPOST('fk_user_creat','int'); + $object->fk_user_modif=GETPOST('fk_user_modif','int'); + $object->import_key=GETPOST('import_key','int'); if (empty($object->ref)) { @@ -159,16 +204,13 @@ if (empty($reshook)) if ($action == 'update' && ! GETPOST('cancel')) { $error=0; - - - $object->entity=GETPOST('entity','int'); - $object->fk_product=GETPOST('fk_product','int'); - $object->batch=GETPOST('batch','alpha'); - $object->fk_user_creat=GETPOST('fk_user_creat','int'); - $object->fk_user_modif=GETPOST('fk_user_modif','int'); - $object->import_key=GETPOST('import_key','int'); - + $object->entity=GETPOST('entity','int'); + $object->fk_product=GETPOST('fk_product','int'); + $object->batch=GETPOST('batch','alpha'); + $object->fk_user_creat=GETPOST('fk_user_creat','int'); + $object->fk_user_modif=GETPOST('fk_user_modif','int'); + $object->import_key=GETPOST('import_key','int'); if (empty($object->ref)) { @@ -219,13 +261,11 @@ if (empty($reshook)) -/*************************************************** -* VIEW -* -* Put here all code to build page -****************************************************/ +/* + * View + */ -llxHeader('','MyPageName',''); +llxHeader('','ProductLot',''); $form=new Form($db); @@ -251,7 +291,7 @@ jQuery(document).ready(function() { // Part to create if ($action == 'create') { - print load_fiche_titre($langs->trans("NewMyModule")); + print load_fiche_titre($langs->trans("Batch")); print '
    '; print ''; @@ -262,12 +302,12 @@ if ($action == 'create') print ''."\n"; // print ''; // -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print '
    '.$langs->trans("Label").'
    '.$langs->trans("Fieldentity").'
    '.$langs->trans("Fieldfk_product").'
    '.$langs->trans("Fieldbatch").'
    '.$langs->trans("Fieldfk_user_creat").'
    '.$langs->trans("Fieldfk_user_modif").'
    '.$langs->trans("Fieldimport_key").'
    '.$langs->trans("Fieldentity").'
    '.$langs->trans("Fieldfk_product").'
    '.$langs->trans("Fieldbatch").'
    '.$langs->trans("Fieldfk_user_creat").'
    '.$langs->trans("Fieldfk_user_modif").'
    '.$langs->trans("Fieldimport_key").'
    '."\n"; @@ -279,64 +319,60 @@ print ''.$langs->trans("Fieldimport_key").'trans("MyModule")); - - print ''; - print ''; - print ''; - print ''; - - dol_fiche_head(); - - print ''."\n"; - // print ''; - // -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; - - print '
    '.$langs->trans("Label").'
    '.$langs->trans("Fieldentity").'
    '.$langs->trans("Fieldfk_product").'
    '.$langs->trans("Fieldbatch").'
    '.$langs->trans("Fieldfk_user_creat").'
    '.$langs->trans("Fieldfk_user_modif").'
    '.$langs->trans("Fieldimport_key").'
    '; - - dol_fiche_end(); - - print '
    '; - print '   '; - print '
    '; - - print ''; -} - - - // Part to show record -if ($id && (empty($action) || $action == 'view' || $action == 'delete')) +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { - print load_fiche_titre($langs->trans("MyModule")); + $res = $object->fetch_optionals($object->id, $extralabels); + + //print load_fiche_titre($langs->trans("Batch")); - dol_fiche_head(); - + $head = productlot_prepare_head($object); + dol_fiche_head($head, 'card', $langs->trans("Batch"), 0, 'barcode'); + + if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMyOjbect'), $langs->trans('ConfirmDeleteMyObject'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteBatch'), $langs->trans('ConfirmDeleteBatch'), 'confirm_delete', '', 0, 1); print $formconfirm; } print ''."\n"; - // print ''; - // -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; + + $linkback = '' . $langs->trans("BackToList") . ''; + + // Ref + print ''; + print ''; + print ''; + + // Product + print ''; + // Eat by + print ''; + print ''; + + // Sell by + print ''; + print ''; + + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + print '
    '.$langs->trans("Label").'
    '.$langs->trans("Fieldentity").'$object->entity
    '.$langs->trans("Fieldfk_product").'$object->fk_product
    '.$langs->trans("Fieldbatch").'$object->batch
    '.$langs->trans("Fieldfk_user_creat").'$object->fk_user_creat
    '.$langs->trans("Fieldfk_user_modif").'$object->fk_user_modif
    '.$langs->trans("Fieldimport_key").'$object->import_key
    ' . $langs->trans('Batch') . ''; + print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'batch'); + print '
    '.$langs->trans("Product").''; + $producttmp = new Product($db); + $producttmp->fetch($object->fk_product); + print $producttmp->getNomUrl(1, 'stock'); + print '
    '; + print $form->editfieldkey($langs->trans('Eatby'), 'eatby', $object->eatby, $object, $user->rights->stock->creer, 'datepicker'); + print ''; + print $form->editfieldval($langs->trans('Eatby'), 'eatby', $object->eatby, $object, $user->rights->stock->creer, 'datepicker'); + print '
    '; + print $form->editfieldkey($langs->trans('Sellby'), 'sellby', $object->sellby, $object, $user->rights->stock->creer, 'datepicker'); + print ''; + print $form->editfieldval($langs->trans('Sellby'), 'sellby', $object->sellby, $object, $user->rights->stock->creer, 'datepicker'); + print '
    '; dol_fiche_end(); @@ -350,17 +386,23 @@ print ''.$langs->trans("Fieldimport_key").'rights->stock->write) +/*TODO if ($user->rights->stock->lire) { print ''."\n"; } - if ($user->rights->stock->delete) + if ($user->rights->stock->supprimer) { print ''."\n"; } +*/ } print '
    '."\n"; + + + print ''.$langs->trans("ShowCurrentStockOfLot").'
    '; + print '
    '; + print ''.$langs->trans("ShowLogOfMovementIfLot").'
    '; } diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index a4ea70f9c2d..1843506bd79 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -22,18 +22,6 @@ * Initialy built by build_class_from_table on 2016-05-17 12:22 */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) - // Change this following line to use the correct relative path (../, ../../, etc) $res=0; if (! $res && file_exists("../main.inc.php")) $res=@include '../main.inc.php'; // to work if your module directory is into dolibarr root htdocs directory @@ -93,11 +81,11 @@ if ($user->societe_id > 0) } // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array -$hookmanager->initHooks(array('productbatchlist')); +$hookmanager->initHooks(array('product_lotlist')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels -$extralabels = $extrafields->fetch_name_optionals_label('productbatch'); +$extralabels = $extrafields->fetch_name_optionals_label('product_lot'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); // List of fields to search into when doing a "search in all" @@ -145,7 +133,7 @@ if (($id > 0 || ! empty($ref)) && $action != 'add') */ if (GETPOST('cancel')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -236,7 +224,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."product_lot as t"; -if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot_extrafields as ef on (u.rowid = ef.fk_object)"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lot_extrafields as ef on (t.rowid = ef.fk_object)"; $sql.= ", ".MAIN_DB_PREFIX."product as p"; $sql.= " WHERE p.rowid = t.fk_product"; //$sql.= " WHERE u.entity IN (".getEntity('mytable',1).")"; @@ -289,15 +277,15 @@ if ($resql) $arrayofselected=is_array($toselect)?$toselect:array(); - $params=''; + $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($search_entity != '') $params.= '&search_entity='.urlencode($search_entity); - if ($search_product != '') $params.= '&search_product='.urlencode($search_product); - if ($search_batch != '') $params.= '&search_batch='.urlencode($search_batch); - if ($search_fk_user_creat != '') $params.= '&search_fk_user_creat='.urlencode($search_fk_user_creat); - if ($search_fk_user_modif != '') $params.= '&search_fk_user_modif='.urlencode($search_fk_user_modif); - if ($search_import_key != '') $params.= '&search_import_key='.urlencode($search_import_key); + if ($search_entity != '') $param.= '&search_entity='.urlencode($search_entity); + if ($search_product != '') $param.= '&search_product='.urlencode($search_product); + if ($search_batch != '') $param.= '&search_batch='.urlencode($search_batch); + if ($search_fk_user_creat != '') $param.= '&search_fk_user_creat='.urlencode($search_fk_user_creat); + if ($search_fk_user_modif != '') $param.= '&search_fk_user_modif='.urlencode($search_fk_user_modif); + if ($search_import_key != '') $param.= '&search_import_key='.urlencode($search_import_key); if ($optioncss != '') $param.='&optioncss='.$optioncss; // Add $param from extra fields foreach ($search_array_options as $key => $val) @@ -323,7 +311,7 @@ if ($resql) print ''; print ''; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); if ($sall) { @@ -355,14 +343,14 @@ if ($resql) // Fields title print ''; - if (! empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'],$_SERVER['PHP_SELF'],'t.entity','',$params,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'],$_SERVER['PHP_SELF'],'t.batch','',$params,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'],$_SERVER['PHP_SELF'],'t.fk_product','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'],$_SERVER['PHP_SELF'],'t.eatby','',$params,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'],$_SERVER['PHP_SELF'],'t.sellby','',$params,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'],$_SERVER['PHP_SELF'],'t.fk_user_creat','',$params,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'],$_SERVER['PHP_SELF'],'t.fk_user_modif','',$params,'',$sortfield,$sortorder); - if (! empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'],$_SERVER['PHP_SELF'],'t.import_key','',$params,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.entity']['checked'])) print_liste_field_titre($arrayfields['t.entity']['label'],$_SERVER['PHP_SELF'],'t.entity','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.batch']['checked'])) print_liste_field_titre($arrayfields['t.batch']['label'],$_SERVER['PHP_SELF'],'t.batch','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_product']['checked'])) print_liste_field_titre($arrayfields['t.fk_product']['label'],$_SERVER['PHP_SELF'],'t.fk_product','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.eatby']['checked'])) print_liste_field_titre($arrayfields['t.eatby']['label'],$_SERVER['PHP_SELF'],'t.eatby','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.sellby']['checked'])) print_liste_field_titre($arrayfields['t.sellby']['label'],$_SERVER['PHP_SELF'],'t.sellby','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_user_creat']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_creat']['label'],$_SERVER['PHP_SELF'],'t.fk_user_creat','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.fk_user_modif']['checked'])) print_liste_field_titre($arrayfields['t.fk_user_modif']['label'],$_SERVER['PHP_SELF'],'t.fk_user_modif','',$param,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.import_key']['checked'])) print_liste_field_titre($arrayfields['t.import_key']['label'],$_SERVER['PHP_SELF'],'t.import_key','',$param,'',$sortfield,$sortorder); // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { @@ -448,7 +436,8 @@ if ($resql) print ''; print ''."\n"; - + $productlot = new Productlot($db); + $i=0; $var=true; $totalarray=array(); @@ -459,6 +448,9 @@ if ($resql) { $var = !$var; + $productlot->id = $obj->rowid; + $productlot->batch = $obj->batch; + // You can use here results print ''; if (! empty($arrayfields['t.entity']['checked'])) @@ -468,7 +460,7 @@ if ($resql) } if (! empty($arrayfields['t.batch']['checked'])) { - print ''.$obj->batch.''; + print ''.$productlot->getNomUrl(1).''; if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['t.fk_product']['checked'])) @@ -609,10 +601,6 @@ if ($resql) $genallowed=$user->rights->facture->lire; $delallowed=$user->rights->facture->lire; - print '
    '; - $paramwithoutshowfiles=preg_replace('/show_files=1&?/','',$param); - $title=$langs->trans("MassFilesArea").' ('.$langs->trans("Hide").')'; - print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); } else diff --git a/htdocs/product/stock/replenish.php b/htdocs/product/stock/replenish.php index ebd9f63f127..a9b2dc57b1b 100644 --- a/htdocs/product/stock/replenish.php +++ b/htdocs/product/stock/replenish.php @@ -3,6 +3,7 @@ * Copyright (C) 2013-2016 Laurent Destaileur * Copyright (C) 2014 Regis Houssin * Copyright (C) 2016 Juanjo Menent + * Copyright (C) 2016 ATM Consulting * * 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 @@ -29,6 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once './lib/replenishment.lib.php'; $langs->load("products"); @@ -53,6 +55,8 @@ $salert = GETPOST('salert', 'alpha'); $mode = GETPOST('mode','alpha'); $fourn_id = GETPOST('fourn_id','int'); +$fk_supplier = GETPOST('fk_supplier','int'); +$fk_entrepot = GETPOST('fk_entrepot','int'); $texte = ''; $sortfield = GETPOST('sortfield','alpha'); @@ -129,19 +133,19 @@ if ($action == 'order' && isset($_POST['valid'])) $line = new CommandeFournisseurLigne($db); $line->qty = $qty; $line->fk_product = $obj->fk_product; - + $product = new Product($db); $product->fetch($obj->fk_product); - if (! empty($conf->global->MAIN_MULTILANGS)) + if (! empty($conf->global->MAIN_MULTILANGS)) { - $product->getMultiLangs(); + $product->getMultiLangs(); } $line->desc = $product->description; if (! empty($conf->global->MAIN_MULTILANGS)) { // TODO Get desc in language of thirdparty } - + $line->tva_tx = $obj->tva_tx; $line->subprice = $obj->unitprice; $line->total_ht = $obj->unitprice * $qty; @@ -250,17 +254,39 @@ if ($action == 'order' && isset($_POST['valid'])) */ $form = new Form($db); +$formproduct = new FormProduct($db); $title = $langs->trans('Status'); +if(!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { + $sqldesiredtock=$db->ifsql("pse.desiredstock IS NULL", "p.desiredstock", "pse.desiredstock"); + $sqlalertstock=$db->ifsql("pse.seuil_stock_alerte IS NULL", "p.seuil_stock_alerte", "pse.seuil_stock_alerte"); +} else { + $sqldesiredtock='p.desiredstock'; + $sqlalertstock='p.seuil_stock_alerte'; +} + + $sql = 'SELECT p.rowid, p.ref, p.label, p.description, p.price,'; $sql.= ' p.price_ttc, p.price_base_type,p.fk_product_type,'; -$sql.= ' p.tms as datem, p.duration, p.tobuy,'; -$sql.= ' p.desiredstock, p.seuil_stock_alerte as alertstock,'; +$sql.= ' p.tms as datem, p.duration, p.tobuy'; +$sql.= ' ,p.desiredstock,p.seuil_stock_alerte'; +if(!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { + $sql.= ', pse.desiredstock' ; + $sql.= ', pse.seuil_stock_alerte' ; +} +$sql.= ' ,'.$sqldesiredtock.' as desiredstock, '.$sqlalertstock.' as alertstock,'; + $sql.= ' SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").') as stock_physique'; $sql.= ' FROM ' . MAIN_DB_PREFIX . 'product as p'; $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'product_stock as s'; $sql.= ' ON p.rowid = s.fk_product'; +if($fk_supplier > 0) { + $sql.= ' INNER JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid AND pfp.fk_soc = '.$fk_supplier.')'; +} +if(!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_warehouse_properties AS pse ON (p.rowid = pse.fk_product AND pse.fk_entrepot = '.$fk_entrepot.')'; +} $sql.= ' WHERE p.entity IN (' . getEntity("product", 1) . ')'; if ($sall) { $sql .= ' AND (p.ref LIKE "%'.$db->escape($sall).'%" '; @@ -295,7 +321,12 @@ if (!empty($canvas)) $sql .= ' AND p.canvas = "' . $db->escape($canvas) . '"'; $sql.= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price'; $sql.= ', p.price_ttc, p.price_base_type,p.fk_product_type, p.tms'; $sql.= ', p.duration, p.tobuy'; -$sql.= ', p.desiredstock, p.seuil_stock_alerte'; +$sql.= ', p.desiredstock'; +$sql.= ', p.seuil_stock_alerte'; +if(!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) { + $sql.= ', pse.desiredstock' ; + $sql.= ', pse.seuil_stock_alerte' ; +} $sql.= ', s.fk_product'; if ($usevirtualstock) @@ -331,24 +362,24 @@ if ($usevirtualstock) $sqlReceptionFourn.= " AND fd.fk_product = p.rowid"; $sqlReceptionFourn.= " AND cf.fk_statut IN (3,4))"; - $sql.= ' HAVING ((('.$db->ifsql("p.desiredstock IS NULL", "0", "p.desiredstock").' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql.= ' HAVING ((('.$db->ifsql($sqldesiredtock." IS NULL", "0", $sqldesiredtock).' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; $sql.= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; - $sql.= ' OR (p.seuil_stock_alerte >= 0 AND (p.seuil_stock_alerte > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql.= ' OR ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; $sql.= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.'))))'; if ($salert == 'on') // Option to see when stock is lower than alert { - $sql.= ' AND (p.seuil_stock_alerte > 0 AND (p.seuil_stock_alerte > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql.= ' AND ('.$sqlalertstock.' > 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; $sql.= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; $alertchecked = 'checked'; } } else { - $sql.= ' HAVING ((p.desiredstock > 0 AND (p.desiredstock > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; - $sql.= ' OR (p.seuil_stock_alerte > 0 AND (p.seuil_stock_alerte > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))))'; + $sql.= ' HAVING (('.$sqldesiredtock.' > 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; + $sql.= ' OR ('.$sqlalertstock.' > 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").'))))'; if ($salert == 'on') // Option to see when stock is lower than alert { - $sql.= ' AND (p.seuil_stock_alerte > 0 AND (p.seuil_stock_alerte > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; + $sql.= ' AND ('.$sqlalertstock.' > 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')))'; $alertchecked = 'checked'; } } @@ -384,16 +415,6 @@ $head[1][2] = 'replenishorders'; print load_fiche_titre($langs->trans('Replenishment'), '', 'title_generic.png'); - -print '
    '. - ''. - ''. - ''. - ''. - ''. - ''. - ''; - dol_fiche_head($head, 'replenish', '', 0, ''); print $langs->trans("ReplenishmentStatusDesc").'
    '."\n"; @@ -401,21 +422,40 @@ if ($usevirtualstock == 1) { print $langs->trans("CurentSelectionMode").': '; print $langs->trans("CurentlyUsingVirtualStock").' - '; - print ''.$langs->trans("UsePhysicalStock").'
    '; + print ''.$langs->trans("UsePhysicalStock").'
    '; } if ($usevirtualstock == 0) { print $langs->trans("CurentSelectionMode").': '; print $langs->trans("CurentlyUsingPhysicalStock").' - '; - print ''.$langs->trans("UseVirtualStock").'
    '; + print ''.$langs->trans("UseVirtualStock").'
    '; } print '
    '."\n"; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print '
    '; +print $langs->trans('Warehouse').' '.$formproduct->selectWarehouses($fk_entrepot, 'fk_entrepot', '', 1); +print '
    '; +print '
    '; +print $langs->trans('Supplier').' '.$form->select_company($fk_supplier, 'fk_supplier', 'fournisseur=1', 1); +print '
    '; +print '
    '; +print ''; +print '
    '; +print '
    '; + if ($sref || $snom || $sall || $salert || GETPOST('search', 'alpha')) { $filters = '&sref=' . $sref . '&snom=' . $snom; $filters .= '&sall=' . $sall; $filters .= '&salert=' . $salert; $filters .= '&mode=' . $mode; + $filters .= '&fk_supplier=' . $fk_supplier; + $filters .= '&fk_entrepot=' . $fk_entrepot; print_barre_liste( $texte, $page, @@ -432,6 +472,8 @@ if ($sref || $snom || $sall || $salert || GETPOST('search', 'alpha')) { $filters .= (isset($type)?'&type=' . $type:''); $filters .= '&=' . $salert; $filters .= '&mode=' . $mode; + $filters .= '&fk_supplier=' . $fk_supplier; + $filters .= '&fk_entrepot=' . $fk_entrepot; print_barre_liste( $texte, $page, @@ -450,11 +492,23 @@ $param = (isset($type)? '&type=' . $type : ''); $param .= '&fourn_id=' . $fourn_id . '&snom='. $snom . '&salert=' . $salert; $param .= '&sref=' . $sref; $param .= '&mode=' . $mode; +$param .= '&fk_supplier=' . $fk_supplier; +$param .= '&fk_entrepot=' . $fk_entrepot; $stocklabel = $langs->trans('Stock'); if ($usevirtualstock == 1) $stocklabel = $langs->trans('VirtualStock'); if ($usevirtualstock == 0) $stocklabel = $langs->trans('PhysicalStock'); +print '
    '. + ''. + ''. + ''. + ''. + ''. + ''. + ''. + ''. + ''; // Lines of title print ''; @@ -605,7 +659,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) print ''; // Supplier - print ''. $form->select_product_fourn_price($prod->id, 'fourn'.$i, 1).''; + print ''. $form->select_product_fourn_price($prod->id, 'fourn'.$i, $fk_supplier).''; print ''; } @@ -622,6 +676,8 @@ if ($num > $conf->liste_limit) $filters .= '&sall=' . $sall; $filters .= '&salert=' . $salert; $filters .= '&mode=' . $mode; + $filters .= '&fk_supplier=' . $fk_supplier; + $filters .= '&fk_entrepot=' . $fk_entrepot; print_barre_liste('', $page, 'replenish.php', $filters, $sortfield, $sortorder, '', $num, 0, ''); } else @@ -631,6 +687,8 @@ if ($num > $conf->liste_limit) $filters .= (isset($type)? '&type=' . $type : ''); $filters .= '&salert=' . $salert; $filters .= '&mode=' . $mode; + $filters .= '&fk_supplier=' . $fk_supplier; + $filters .= '&fk_entrepot=' . $fk_entrepot; print_barre_liste('', $page, 'replenish.php', $filters, $sortfield, $sortorder, '', $num, 0, ''); } } diff --git a/htdocs/product/traduction.php b/htdocs/product/traduction.php index 15174f82fb4..b609e96661a 100644 --- a/htdocs/product/traduction.php +++ b/htdocs/product/traduction.php @@ -246,6 +246,9 @@ else dol_banner_tab($object, 'ref', $linkback, ($user->societe_id?0:1), 'ref'); + print '
    '; + + $cnt_trans = 0; if (! empty($object->multilangs)) { @@ -253,8 +256,8 @@ else { $cnt_trans++; $s=picto_from_langcode($key); - print "
    ".($s?$s.' ':'')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', '')."
    "; print ''; + print ''; print ''; print ''; if (! empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) diff --git a/htdocs/projet/activity/perday.php b/htdocs/projet/activity/perday.php index 0c509240684..012a71f21a0 100644 --- a/htdocs/projet/activity/perday.php +++ b/htdocs/projet/activity/perday.php @@ -62,6 +62,7 @@ $month=GETPOST('remonth')?GETPOST('remonth'):(GETPOST("month","int")?GETPOST("mo $day=GETPOST('reday')?GETPOST('reday'):(GETPOST("day","int")?GETPOST("day","int"):date("d")); $day = (int) $day; $week=GETPOST("week","int")?GETPOST("week","int"):date("W"); +$search_project_ref = GETPOST('search_project_ref', 'alpha'); $monthofday=GETPOST('addtimemonth'); @@ -79,6 +80,17 @@ $object=new Task($db); * Actions */ +// Purge criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $action = ''; + $search_project_ref = ''; +} +if (GETPOST("button_search_x") || GETPOST("button_search.x") || GETPOST("button_search")) +{ + $action = ''; +} + if (GETPOST('submitdateselect')) { $daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); @@ -253,6 +265,8 @@ $formproject=new FormProjets($db); $projectstatic=new Project($db); $project = new Project($db); $taskstatic = new Task($db); +$thirdpartystatic = new Societe($db); + $prev = dol_getdate($daytoparse - (24 * 3600)); $prev_year = $prev['year']; @@ -278,7 +292,8 @@ if ($id) } $onlyopenedproject=1; // or -1 -$tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, '', $onlyopenedproject); // We want to see all task of opened project i am allowed to see, not only mine. Later only mine will be editable later. +$morewherefilter=''; +$tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter); // We want to see all task of opened project i am allowed to see, not only mine. Later only mine will be editable later. $projectsrole=$taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id?$project->id:0), 0, $onlyopenedproject); $tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id?$project->id:0), 0, $onlyopenedproject); //var_dump($tasksarray); @@ -290,12 +305,14 @@ llxHeader("",$title,""); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, '', 'title_project'); -$param=($mode?'&mode='.$mode:''); +$param=''; +$param.=($mode?'&mode='.$mode:''); +$param.=($search_project_ref?'&search_project_ref='.$search_project_ref:''); // Show navigation bar -$nav ="".img_previous($langs->trans("Previous"))."\n"; +$nav =''.img_previous($langs->trans("Previous"))."\n"; $nav.=" ".dol_print_date(dol_mktime(0,0,0,$month,$day,$year),"day")." \n"; -$nav.="".img_next($langs->trans("Next"))."\n"; +$nav.=''.img_next($langs->trans("Next"))."\n"; $nav.="   (".$langs->trans("Today").")"; $nav.='
    '.$form->select_date(-1,'',0,0,2,"addtime",1,0,1).' '; $nav.=' '; @@ -362,6 +379,9 @@ print "\n"; //print ''; //print ''; //print ''; + +print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. + print '
    '; print $langs->trans("AssignTaskToMe").'
    '; $formproject->selectTasks($socid?$socid:-1, $taskid, 'taskid', 32, 0, 1, 1); @@ -370,15 +390,18 @@ print ''.$nav.'
    '; print '
    '; print '
    '.($s?$s.' ':'')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', '').'
    '.$langs->trans('Label').''.$object->multilangs[$key]["label"].'
    '.$langs->trans('Description').''.$object->multilangs[$key]["description"].'
    '; print ''; -print ''; print ''; print ''; +print ''; +if (! empty($conf->global->PROJECT_LINES_PERDAY_SHOW_THIRDPARTY)) +{ + print ''; +} print ''; print ''; print ''; @@ -386,9 +409,28 @@ if ($usertoprocess->id == $user->id) print ''; print ''; print ''; -print ''; +print ''; print "\n"; +print ''; +print ''; +print ''; +print ''; +if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +// Action column +print ''; +print "\n"; + + // By default, we can edit only tasks we are assigned to $restrictviewformytask=(empty($conf->global->PROJECT_TIME_SHOW_TASK_NOT_ASSIGNED)?1:0); diff --git a/htdocs/projet/activity/perweek.php b/htdocs/projet/activity/perweek.php index cb525842f61..396eb352d3b 100644 --- a/htdocs/projet/activity/perweek.php +++ b/htdocs/projet/activity/perweek.php @@ -58,11 +58,12 @@ $nowtmp=dol_getdate($now); $nowday=$nowtmp['mday']; $nowmonth=$nowtmp['mon']; $nowyear=$nowtmp['year']; -$year=GETPOST('reyear')?GETPOST('reyear'):(GETPOST("year","int")?GETPOST("year","int"):date("Y")); -$month=GETPOST('remonth')?GETPOST('remonth'):(GETPOST("month","int")?GETPOST("month","int"):date("m")); -$day=GETPOST('reday')?GETPOST('reday'):(GETPOST("day","int")?GETPOST("day","int"):date("d")); +$year=GETPOST('reyear')?GETPOST('reyear','int'):(GETPOST("year")?GETPOST("year","int"):date("Y")); +$month=GETPOST('remonth')?GETPOST('remonth','int'):(GETPOST("month")?GETPOST("month","int"):date("m")); +$day=GETPOST('reday')?GETPOST('reday','int'):(GETPOST("day")?GETPOST("day","int"):date("d")); $day = (int) $day; $week=GETPOST("week","int")?GETPOST("week","int"):date("W"); +$search_project_ref = GETPOST('search_project_ref', 'alpha'); $startdayarray=dol_get_first_day_week($day, $month, $year); @@ -93,6 +94,17 @@ $object=new Task($db); * Actions */ +// Purge criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $action = ''; + $search_project_ref = ''; +} +if (GETPOST("button_search_x") || GETPOST("button_search.x") || GETPOST("button_search")) +{ + $action = ''; +} + if (GETPOST('submitdateselect')) { $daytoparse = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); @@ -103,7 +115,7 @@ if (GETPOST('submitdateselect')) if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask')) { $action = 'assigntask'; - + if ($taskid > 0) { $result = $object->fetch($taskid, $ref); @@ -119,6 +131,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), '', 'errors'); $error++; } + if (! $error) { $idfortaskuser=$user->id; @@ -176,7 +189,7 @@ if ($action == 'addtime' && $user->rights->projet->lire && GETPOST('assigntask') $action=''; } -if ($action == 'addtime' && $user->rights->projet->lire) +if ($weclickonassign && $action == 'addtime' && $user->rights->projet->lire) { $timetoadd=$_POST['task']; if (empty($timetoadd)) @@ -276,7 +289,8 @@ if ($id) } $onlyopenedproject=1; // or -1 -$tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, '', $onlyopenedproject); // We want to see all task of opened project i am allowed to see, not only mine. Later only mine will be editable later. +$morewherefilter=''; +$tasksarray=$taskstatic->getTasksArray(0, 0, ($project->id?$project->id:0), $socid, 0, $search_project_ref, $onlyopenedproject, $morewherefilter); // We want to see all task of opened project i am allowed to see, not only mine. Later only mine will be editable later. $projectsrole=$taskstatic->getUserRolesForProjectsOrTasks($usertoprocess, 0, ($project->id?$project->id:0), 0, $onlyopenedproject); $tasksrole=$taskstatic->getUserRolesForProjectsOrTasks(0, $usertoprocess, ($project->id?$project->id:0), 0, $onlyopenedproject); //var_dump($tasksarray); @@ -288,12 +302,14 @@ llxHeader("",$title,"",'','','',array('/core/js/timesheet.js')); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, '', 'title_project'); -$param=($mode?'&mode='.$mode:''); +$param=''; +$param.=($mode?'&mode='.$mode:''); +$param.=($search_project_ref?'&search_project_ref='.$search_project_ref:''); // Show navigation bar -$nav ="".img_previous($langs->trans("Previous"))."\n"; +$nav =''.img_previous($langs->trans("Previous"))."\n"; $nav.=" ".dol_print_date(dol_mktime(0,0,0,$first_month,$first_day,$first_year),"%Y").", ".$langs->trans("WeekShort")." ".$week." \n"; -$nav.="".img_next($langs->trans("Next"))."\n"; +$nav.=''.img_next($langs->trans("Next"))."\n"; $nav.="   (".$langs->trans("Today").")"; $nav.='
    '.$form->select_date(-1,'',0,0,2,"addtime",1,0,1).' '; $nav.=' '; @@ -358,6 +374,9 @@ print "\n"; //print ''; //print ''; //print ''; + +print '
    '.$nav.'
    '; // We move this before the assign to components so, the default submit button is not the assign to. + print '
    '; print $langs->trans("AssignTaskToMe").'
    '; $formproject->selectTasks($socid?$socid:-1, $taskid, 'taskid', 32, 0, 1, 1); @@ -366,19 +385,19 @@ print ''.$nav.'
    '; print '
    '; print '
    '.$langs->trans("Project").''.$langs->trans("RefTask").''.$langs->trans("LabelTask").''.$langs->trans("ProjectRef").''.$langs->trans("ThirdParty").''.$langs->trans("PlannedWorkload").''.$langs->trans("ProgressDeclared").''.$langs->trans("TimeSpent").''.$langs->trans("T else print ''.$langs->trans("TimeSpentByUser").''.$langs->trans("HourStart").''.$langs->trans("Duration").''.$langs->trans("Note").''.$langs->trans("Note").'
    '; +$searchpitco=$form->showFilterAndCheckAddButtons(0); +print $searchpitco; +print '
    '; + print ''; +print ''; +print ''; +print ''; if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) { print ''; } -print ''; -print ''; -print ''; print ''; print ''; print ''; @@ -389,10 +408,29 @@ $startday=dol_mktime(12, 0, 0, $startdayarray['first_month'], $startdayarray['fi for($i=0;$i<7;$i++) { - print ''; + print ''; } print ''; +print "\n"; +print ''; +print ''; +print ''; +print ''; +if (! empty($conf->global->PROJECT_LINES_PERWEEK_SHOW_THIRDPARTY)) print ''; +print ''; +print ''; +print ''; +print ''; +for($i=0;$i<7;$i++) +{ + print ''; +} +// Action column +print ''; print "\n"; // By default, we can edit only tasks we are assigned to diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index ce39fad4a14..f4c5d871fc6 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -494,7 +494,7 @@ if ($action == 'create' && $user->rights->projet->creer) // Thirdparty if ($conf->societe->enabled) { - print ''; } - // Public - print ''; - print ''; // Opportunity probability print ''; - print ''; print ''; @@ -567,7 +567,7 @@ if ($action == 'create' && $user->rights->projet->creer) print ''; print ''; - if($conf->categorie->enabled) { + if ($conf->categorie->enabled) { // Categories print ''; - // Date start - print ''; - - // Date end - print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Opportunity status @@ -762,6 +749,19 @@ else print ''; } + // Date start + print ''; + + // Date end + print ''; + // Budget print ''; print ''; @@ -799,48 +799,62 @@ else } else { - print '
    '.$langs->trans("RefTask").''.$langs->trans("LabelTask").''.$langs->trans("ProjectRef").''.$langs->trans("ThirdParty").''.$langs->trans("Project").''.$langs->trans("RefTask").''.$langs->trans("LabelTask").''.$langs->trans("PlannedWorkload").''.$langs->trans("ProgressDeclared").''.$langs->trans("TimeSpent").''.dol_print_date($startday + ($i * 3600 * 24), '%a').'
    '.dol_print_date($startday + ($i * 3600 * 24), 'dayreduceformat').'
    '.dol_print_date($startday + ($i * 3600 * 24), '%a').'
    '.dol_print_date($startday + ($i * 3600 * 24), 'dayreduceformat').'
    '; +$searchpitco=$form->showFilterAndCheckAddButtons(0); +print $searchpitco; +print '
    '.$langs->trans("ThirdParty").''; + print '
    '.$langs->trans("ThirdParty").''; $filteronlist=''; if (! empty($conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST)) $filteronlist=$conf->global->PROJECT_FILTER_FOR_THIRDPARTY_LIST; $text=$form->select_thirdparty_list(GETPOST('socid','int'), 'socid', $filteronlist, 'SelectThirdParty', 1, 0, array(), '', 0, 0, 'minwidth300'); @@ -517,8 +517,8 @@ if ($action == 'create' && $user->rights->projet->creer) print '
    '.$langs->trans("Visibility").''; + // Visibility + print '
    '.$langs->trans("Visibility").''; $array=array(); if (empty($conf->global->PROJECT_DISABLE_PRIVATE_PROJECT)) $array[0] = $langs->trans("PrivateProject"); if (empty($conf->global->PROJECT_DISABLE_PUBLIC_PROJECT)) $array[1] = $langs->trans("SharedProject"); @@ -539,13 +539,13 @@ if ($action == 'create' && $user->rights->projet->creer) { // Opportunity status print '
    '.$langs->trans("OpportunityStatus").''; + print ''; print $formproject->selectOpportunityStatus('opp_status', GETPOST('opp_status')?GETPOST('opp_status'):$object->opp_status); print '
    '.$langs->trans("OpportunityProbability").' %'; + print ' %'; print ''; print '
    '.$langs->trans("Categories").''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_PROJECT, '', 'parent', 64, 0, 1); @@ -661,7 +661,7 @@ else { $formquestion=array( 'text' => $langs->trans("ConfirmClone"), - array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int')>0?GETPOST('socid', 'int'):$object->socid, 'socid', '', "None")), + array('type' => 'other','name' => 'socid','label' => $langs->trans("SelectThirdParty"),'value' => $form->select_company(GETPOST('socid', 'int')>0?GETPOST('socid', 'int'):$object->socid, 'socid', '', "None", 0, 0, null, 0, 'minwidth200')), array('type' => 'checkbox', 'name' => 'clone_contacts', 'label' => $langs->trans("CloneContacts"), 'value' => true), array('type' => 'checkbox', 'name' => 'clone_tasks', 'label' => $langs->trans("CloneTasks"), 'value' => true), array('type' => 'checkbox', 'name' => 'move_date', 'label' => $langs->trans("CloneMoveDate"), 'value' => true), @@ -670,7 +670,7 @@ else array('type' => 'checkbox', 'name' => 'clone_task_files', 'label' => $langs->trans("CloneTaskFiles"), 'value' => false) ); - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CloneProject"), $langs->trans("ConfirmCloneProject"), "confirm_clone", $formquestion, '', 1, 300); + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CloneProject"), $langs->trans("ConfirmCloneProject"), "confirm_clone", $formquestion, '', 1, 300, 590); } @@ -727,19 +727,6 @@ else // Status print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print $form->select_date($object->date_start?$object->date_start:-1,'projectstart',0,0,0,'',1,0,1); - print '     '. $langs->trans("ProjectReportDate"); - print '
    '.$langs->trans("DateEnd").''; - print $form->select_date($object->date_end?$object->date_end:-1,'projectend',0,0,0,'',1,0,1); - print '
    '.$langs->trans("DateStart").''; + print $form->select_date($object->date_start?$object->date_start:-1,'projectstart',0,0,0,'',1,0,1); + print '     '. $langs->trans("ProjectReportDate"); + print '
    '.$langs->trans("DateEnd").''; + print $form->select_date($object->date_end?$object->date_end:-1,'projectend',0,0,0,'',1,0,1); + print '
    '.$langs->trans("Budget").'
    '; - + // Project card + $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; + // Other attributes + $parameters=array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"'); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields,'edit'); + } + print '
    '.$langs->trans("Ref").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$object->title; + // Thirdparty + if ($object->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + // Define a complementary filter for search of next/prev ref. if (! $user->rights->projet->all->lire) { $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; } + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Ref + /* + print ''; + */ // Label - print ''; + //print ''; // Third party - print ''; + */ // Visibility - print ''; // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; + //print ''; if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { @@ -860,32 +874,51 @@ else if (strcmp($object->opp_amount,'')) print price($object->opp_amount,'',$langs,1,0,0,$conf->currency); print ''; } - + + // Date start - end + print ''; + // Budget print ''; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Ref").''; print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref'); print '
    '.$langs->trans("Label").''.$object->title.'
    '.$langs->trans("Label").''.$object->title.'
    '.$langs->trans("ThirdParty").''; + /* + print '
    '.$langs->trans("ThirdParty").''; if ($object->thirdparty->id > 0) print $object->thirdparty->getNomUrl(1, 'project'); else print' '; print '
    '.$langs->trans("Visibility").''; + print '
    '.$langs->trans("Visibility").''; if ($object->public) print $langs->trans('SharedProject'); else print $langs->trans('PrivateProject'); print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($object->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($object->date_end,'day'); - print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($object->date_start,'day'); + $end=dol_print_date($object->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,1,0,0,$conf->currency); print '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + // Description - print ''; // Categories if($conf->categorie->enabled) { - print '"; - } - - // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && ! empty($extrafields->attribute_label)) - { - print $object->showOptionals($extrafields); + print '"; } + print '
    '.$langs->trans("Description").''; + print ''.$langs->trans("Description").''; print nl2br($object->description); print '
    '.$langs->trans("Categories").''; - print $form->showCategories($object->id,'project',1); - print "
    '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; } dol_fiche_end(); @@ -937,7 +970,16 @@ else { if ($action != "edit" ) { - // Modify + + // 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. + { + print ''; + } + + // Modify if ($object->statut != 2 && $user->rights->projet->creer) { if ($userWrite > 0) @@ -1090,17 +1132,10 @@ else $var=true; - $somethingshown=$formfile->show_documents('project',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf); + print $formfile->showdocuments('project',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf); print '
    '; - if (!empty($object->id)) - { - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown=$formactions->showactions($object,'project',$socid); - } print '
    '; } diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index 0e7333708f1..4ac568182de 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -37,7 +37,8 @@ class Project extends CommonObject public $table_element_line = 'projet_task'; public $fk_element = 'fk_projet'; protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - + public $picto = 'projectpub'; + /** * {@inheritdoc} */ @@ -705,6 +706,13 @@ class Project extends CommonObject if ($this->statut != 1) { + // Check parameters + if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->title)) + { + $this->error=$langs->trans("ErrorFieldFormat",$langs->transnoentities("Label")).'. '.$langs->trans('RemoveString',$langs->transnoentitiesnoconv("CopyOf")); + return -1; + } + $this->db->begin(); $sql = "UPDATE " . MAIN_DB_PREFIX . "projet"; @@ -770,7 +778,7 @@ class Project extends CommonObject if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { - // TODO What to do if fk_opp_status is not code 'WIN' or 'LOST' + // TODO What to do if fk_opp_status is not code 'WON' or 'LOST' } dol_syslog(get_class($this)."::setClose", LOG_DEBUG); @@ -881,15 +889,17 @@ class Project extends CommonObject * @param int $addlabel 0=Default, 1=Add label into string, >1=Add first chars into string * @param string $moreinpopup Text to add into popup * @param string $sep Separator between ref and label if option addlabel is set + * @param int $notooltip 1=Disable tooltip * @return string Chaine avec URL */ - function getNomUrl($withpicto=0, $option='', $addlabel=0, $moreinpopup='', $sep=' - ') + function getNomUrl($withpicto=0, $option='', $addlabel=0, $moreinpopup='', $sep=' - ', $notooltip=0) { - global $langs; + global $conf, $langs, $user; + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + $result = ''; - $link = ''; - $linkend = ''; + $label=''; if ($option != 'nolink') $label = '' . $langs->trans("ShowProject") . ''; if (! empty($this->ref)) @@ -903,33 +913,44 @@ class Project extends CommonObject if (! empty($this->datee)) $label .= ($label?'
    ':'').'' . $langs->trans('DateEnd') . ': ' . dol_print_date($this->datee, 'day'); // The space must be after the : to not being explode when showing the title in img_picto if ($moreinpopup) $label.='
    '.$moreinpopup; - $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; if ($option != 'nolink') { if (preg_match('/\.php$/',$option)) { - $link = ''; + $url = DOL_URL_ROOT . '/projet/tasks.php?id=' . $this->id; } else { - $link = 'public) $picto = 'project'; - - if ($withpicto) $result.=($link . img_object($label, $picto, 'class="classfortooltip"') . $linkend); + $linkstart = ''; + $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.=$link . $this->ref . $linkend . (($addlabel && $this->title) ? $sep . dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : ''); + if ($withpicto != 2) $result.=$linkstart . $this->ref . $linkend . (($addlabel && $this->title) ? $sep . dol_trunc($this->title, ($addlabel > 1 ? $addlabel : 0)) : ''); return $result; } @@ -1196,6 +1217,7 @@ class Project extends CommonObject if (is_numeric($defaultref) && $defaultref <= 0) $defaultref=''; $clone_project->ref=$defaultref; + $clone_project->title=$langs->trans("CopyOf").' '.$clone_project->title; // Create clone $result=$clone_project->create($user,$notrigger); @@ -1319,9 +1341,9 @@ class Project extends CommonObject $tasksarray=$taskstatic->getTasksArray(0, 0, $fromid, $socid, 0); - //manage new parent clone task id $tab_conv_child_parent=array(); + // Loop on each task, to clone it foreach ($tasksarray as $tasktoclone) { $result_clone = $taskstatic->createFromClone($tasktoclone->id,$clone_project_id,$tasktoclone->fk_parent,$move_date,true,false,$clone_task_file,true,false); diff --git a/htdocs/projet/class/task.class.php b/htdocs/projet/class/task.class.php index 40b5667c9c0..ad2f5faecbe 100644 --- a/htdocs/projet/class/task.class.php +++ b/htdocs/projet/class/task.class.php @@ -33,7 +33,8 @@ class Task extends CommonObject { public $element='project_task'; //!< Id that identify managed objects public $table_element='projet_task'; //!< Name of table without prefix where object is stored - + public $picto = 'task'; + var $fk_task_parent; var $label; var $description; @@ -58,6 +59,8 @@ class Task extends CommonObject var $timespent_fk_user; var $timespent_note; + public $oldcopy; + /** * Constructor @@ -316,6 +319,30 @@ class Task extends CommonObject } } + if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) + { + // We remove directory + if ($conf->projet->dir_output) + { + $project = new Project($this->db); + $project->fetch($this->fk_project); + + $olddir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->oldcopy->ref); + $newdir = $conf->projet->dir_output.'/'.dol_sanitizeFileName($project->ref).'/'.dol_sanitizeFileName($this->ref); + if (file_exists($olddir)) + { + include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + $res=dol_move($olddir, $newdir); + if (! $res) + { + $langs->load("errors"); + $this->error=$langs->trans('ErrorFailToRenameDir',$olddir,$newdir); + $error++; + } + } + } + } + // Commit or rollback if ($error) { @@ -494,12 +521,15 @@ class Task extends CommonObject * @param string $mode Mode 'task', 'time', 'contact', 'note', document' define page to link to. * @param int $addlabel 0=Default, 1=Add label into string, >1=Add first chars into string * @param string $sep Separator between ref and label if option addlabel is set + * @param int $notooltip 1=Disable tooltip * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$option='',$mode='task', $addlabel=0, $sep=' - ') + function getNomUrl($withpicto=0,$option='',$mode='task', $addlabel=0, $sep=' - ', $notooltip=0) { - global $langs; + global $conf, $langs, $user; + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + $result=''; $label = '' . $langs->trans("ShowTask") . ''; if (! empty($this->ref)) @@ -510,17 +540,30 @@ class Task extends CommonObject { $label .= "
    ".get_date_range($this->date_start,$this->date_end,'',$langs,0); } - $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + + $url = DOL_URL_ROOT.'/projet/tasks/'.$mode.'.php?id='.$this->id.($option=='withproject'?'&withproject=1':''); - $link = ''; $linkend=''; - + $picto='projecttask'; - - if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$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.=$link.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + if ($withpicto != 2) $result.=$linkstart.$this->ref.$linkend . (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); return $result; } @@ -574,7 +617,7 @@ class Task extends CommonObject $sql = "SELECT p.rowid as projectid, p.ref, p.title as plabel, p.public, p.fk_statut as projectstatus,"; $sql.= " t.rowid as taskid, t.ref as taskref, t.label, t.description, t.fk_task_parent, t.duration_effective, t.progress, t.fk_statut as status,"; $sql.= " t.dateo as date_start, t.datee as date_end, t.planned_workload, t.rang,"; - $sql.= " s.nom as thirdparty_name"; + $sql.= " s.rowid as thirdparty_id, s.nom as thirdparty_name"; $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON p.fk_soc = s.rowid"; if ($mode == 0) @@ -691,6 +734,7 @@ class Task extends CommonObject $tasks[$i]->date_end = $this->db->jdate($obj->date_end); $tasks[$i]->rang = $obj->rang; + $tasks[$i]->thirdparty_id = $obj->thirdparty_id; $tasks[$i]->thirdparty_name = $obj->thirdparty_name; } @@ -1242,6 +1286,9 @@ class Task extends CommonObject // Load source object $clone_task->fetch($fromid); + $clone_task->fetch_optionals(); + //var_dump($clone_task->array_options);exit; + $origin_task->fetch($fromid); $defaultref=''; diff --git a/htdocs/projet/contact.php b/htdocs/projet/contact.php index 794e9c3af00..c2a24458015 100644 --- a/htdocs/projet/contact.php +++ b/htdocs/projet/contact.php @@ -149,53 +149,42 @@ if ($id > 0 || ! empty($ref)) dol_fiche_head($head, 'contact', $langs->trans("Project"), 0, ($object->public?'projectpub':'project')); - /* - * Projet synthese pour rappel - */ - print ''; + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$object->title; + // Thirdparty + if ($object->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - $linkback = ''.$langs->trans("BackToList").''; - // Ref - print ''; - - // Label - print ''; - - // Customer - print ""; - print ''; + print '
    '; + print '
    '; + print '
    '; + print '
    '.$langs->trans('Ref').''; - // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) - { - $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); - $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; - } - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); - print '
    '.$langs->trans("Label").''.$object->title.'
    ".$langs->trans("ThirdParty")."'; - if ($object->thirdparty->id > 0) print $object->thirdparty->getNomUrl(1); - else print ' '; - print '
    '; + // Visibility - print ''; - // Status - print ''; - - // Date start - print ''; - - // Date end - print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Opportunity status @@ -204,21 +193,66 @@ if ($id > 0 || ! empty($ref)) if ($code) print $langs->trans("OppStatus".$code); print ''; + // Opportunity percent + print ''; + // Opportunity Amount print ''; } - // Budget + // Date start - end + print ''; + + // Budget print ''; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + print "
    '.$langs->trans("Visibility").''; + print '
    '.$langs->trans("Visibility").''; if ($object->public) print $langs->trans('SharedProject'); else print $langs->trans('PrivateProject'); print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($object->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($object->date_end,'day'); - print '
    '.$langs->trans("OpportunityProbability").''; + if (strcmp($object->opp_percent,'')) print price($object->opp_percent,'',$langs,1,0).' %'; + print '
    '.$langs->trans("OpportunityAmount").''; if (strcmp($object->opp_amount,'')) print price($object->opp_amount,'',$langs,0,0,0,$conf->currency); print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($object->date_start,'day'); + $end=dol_print_date($object->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,0,0,0,$conf->currency); print '
    "; - print ''; - + print ''; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($object->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print ''; + + print '
    '; + + dol_fiche_end(); + + print '
    '; + // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); foreach($dirtpls as $reldir) diff --git a/htdocs/projet/document.php b/htdocs/projet/document.php index d59dec0dc4a..f6f1a51fed7 100644 --- a/htdocs/projet/document.php +++ b/htdocs/projet/document.php @@ -106,48 +106,50 @@ if ($object->id > 0) $totalsize+=$file['size']; } + + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$object->title; + // Thirdparty + if ($object->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print ''; - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - - // Label - print ''; - - // Company - print ''; - - // Visibility - print ''; - - // Statut - print ''; - // Files infos - print ''; - print ''; + print ''; + print ''; print "
    '.$langs->trans("Ref").''; - // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) - { - $projectsListId = $object->getProjectsAuthorizedForUser($user,0,0); - $object->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; - } - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref'); - print '
    '.$langs->trans("Label").''.$object->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($object->thirdparty->id)) print $object->thirdparty->getNomUrl(1); - else print ' '; - print '
    '.$langs->trans("Visibility").''; - if ($object->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    '.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
    '.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
    \n"; - print "
    \n"; + + print ''; + + + dol_fiche_end(); $modulepart = 'project'; $permission = ($userWrite > 0); + $permtoedit = ($userWrite > 0); include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php index ea731b5c617..e94042f43d3 100644 --- a/htdocs/projet/element.php +++ b/htdocs/projet/element.php @@ -5,6 +5,7 @@ * Copyright (C) 2012-2016 Juanjo Menent * Copyright (C) 2015 Alexandre Spangaro * Copyright (C) 2015 Marcos García + * Copyright (C) 2016 Josep Lluís Amador * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,7 +23,7 @@ /** * \file htdocs/projet/element.php - * \ingroup projet facture + * \ingroup projet * \brief Page of project referrers */ @@ -120,46 +121,42 @@ $head=project_prepare_head($object); dol_fiche_head($head, 'element', $langs->trans("Project"),0,($object->public?'projectpub':'project')); -print ''; +// Project card $linkback = ''.$langs->trans("BackToList").''; -print ''; -print ''; +dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); -print ''; + +print '
    '; +print '
    '; +print '
    '; + +print '
    '.$langs->trans("Ref").''; +$morehtmlref='
    '; +// Title +$morehtmlref.=$object->title; +// Thirdparty +if ($object->thirdparty->id > 0) +{ + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); +} +$morehtmlref.='
    '; + // Define a complementary filter for search of next/prev ref. if (! $user->rights->projet->all->lire) { - $projectsListId = $object->getProjectsAuthorizedForUser($user,0,0); - $object->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; } -print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref'); -print '
    '.$langs->trans("Label").''.$object->title.'
    '.$langs->trans("ThirdParty").''; -if (! empty($object->thirdparty->id)) print $object->thirdparty->getNomUrl(1); -else print ' '; -print '
    '; // Visibility -print ''; -// Statut -print ''; - -// Date start -print ''; - -// Date end -print ''; - if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { // Opportunity status @@ -168,19 +165,62 @@ if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) if ($code) print $langs->trans("OppStatus".$code); print ''; + // Opportunity percent + print ''; + // Opportunity Amount print ''; } -// Budget -print ''; +// Budget +print ''; + +// Other attributes +$cols = 2; +include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + print '
    '.$langs->trans("Visibility").''; +print '
    '.$langs->trans("Visibility").''; if ($object->public) print $langs->trans('SharedProject'); else print $langs->trans('PrivateProject'); print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("DateStart").''; -print dol_print_date($object->date_start,'day'); -print '
    '.$langs->trans("DateEnd").''; -print dol_print_date($object->date_end,'day'); -print '
    '.$langs->trans("OpportunityProbability").''; + if (strcmp($object->opp_percent,'')) print price($object->opp_percent,'',$langs,1,0).' %'; + print '
    '.$langs->trans("OpportunityAmount").''; - if (strcmp($object->opp_amount,'')) print price($object->opp_amount,'',$langs,0,0,0,$conf->currency); + if (strcmp($object->opp_amount,'')) print price($object->opp_amount,'',$langs,1,0,0,$conf->currency); print '
    '.$langs->trans("Budget").''; -if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,0,0,0,$conf->currency); +// Date start - end +print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; +print dol_print_date($object->date_start,'day'); +$end=dol_print_date($object->date_end,'day'); +if ($end) print ' - '.$end; print '
    '.$langs->trans("Budget").''; +if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,1,0,0,$conf->currency); +print '
    '; +print ''; +print '
    '; +print '
    '; +print '
    '; + +print ''; + +// Description +print ''; + +// Categories +if($conf->categorie->enabled) { + print '"; +} + +print '
    '.$langs->trans("Description").''; +print nl2br($object->description); +print '
    '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'project',1); + print "
    '; + +print '
    '; +print '
    '; +print ''; + +print '
    '; + dol_fiche_end(); @@ -484,7 +524,13 @@ foreach ($listofreferent as $key => $value) } else $total_ht_by_line=$element->total_ht; - $total_ht = $total_ht + $total_ht_by_line; + $qualifiedfortotal=true; + if ($key == 'invoice') + { + if (! empty($element->close_code) && $element->close_code == 'replaced') $qualifiedfortotal=false; // Replacement invoice, do not include into total + } + + if ($qualifiedfortotal) $total_ht = $total_ht + $total_ht_by_line; if ($tablename == 'don') $total_ttc_by_line=$element->amount; elseif ($tablename == 'projet_task') @@ -494,7 +540,7 @@ foreach ($listofreferent as $key => $value) } else $total_ttc_by_line=$element->total_ttc; - $total_ttc = $total_ttc + $total_ttc_by_line; + if ($qualifiedfortotal) $total_ttc = $total_ttc + $total_ttc_by_line; } // Calculate margin @@ -630,15 +676,16 @@ foreach ($listofreferent as $key => $value) print load_fiche_titre($langs->trans($title), $addform, ''); + print "\n".''."\n"; print ''; print ''; // Remove link print ''; // Ref - print ''; + print ''.$langs->trans("Ref").''; // Date - print ''; // Thirdparty or user @@ -767,16 +814,33 @@ foreach ($listofreferent as $key => $value) print "\n"; // Date - if ($tablename == 'commande_fournisseur' || $tablename == 'supplier_order') $date=$element->date_commande; - elseif ($tablename == 'projet_task') $date=''; // We show no date. Showing date of beginning of task make user think it is date of time consumed - else + $date=''; + if ($tablename == 'expensereport_det') $date = $element->date; // No draft status on lines + elseif (! empty($element->status) || ! empty($element->statut) || ! empty($element->fk_status)) { - $date=$element->date; - if (empty($date)) $date=$element->datep; - if (empty($date)) $date=$element->date_contrat; - if (empty($date)) $date=$element->datev; //Fiche inter + if ($tablename=='don') $date = $element->datedon; + if ($tablename == 'commande_fournisseur' || $tablename == 'supplier_order') + { + $date=($element->date_commande?$element->date_commande:$element->date_valid); + } + elseif ($tablename == 'supplier_proposal') $date=$element->date_validation; // There is no other date for this + elseif ($tablename == 'fichinter') $date=$element->datev; // There is no other date for this + elseif ($tablename == 'projet_task') $date=''; // We show no date. Showing date of beginning of task make user think it is date of time consumed + else + { + $date=$element->date; // invoice, ... + if (empty($date)) $date=$element->date_contrat; + if (empty($date)) $date=$element->datev; + } } - print ''; + print ''; // Third party or user print '
    '.$langs->trans("Ref").''; + print ''; if (! in_array($tablename, array('projet_task'))) print $langs->trans("Date"); print ''.dol_print_date($date,'day').''; + if ($tablename == 'actioncomm') + { + print dol_print_date($element->datep,'dayhour'); + if ($element->datef && $element->datef > $element->datep) print " - ".dol_print_date($element->datef,'dayhour'); + } + else print dol_print_date($date,'day'); + print ''; diff --git a/htdocs/projet/ganttview.php b/htdocs/projet/ganttview.php index e26a56c3cc7..1751b30a4bb 100644 --- a/htdocs/projet/ganttview.php +++ b/htdocs/projet/ganttview.php @@ -98,58 +98,90 @@ if ($id > 0 || ! empty($ref)) $param=($mode=='mine'?'&mode=mine':''); - print ''; + + // Project card + $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - - print ''; - - print ''; - print ''; - + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; - print $langs->trans("Ref"); - print ''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$object->title; + // Thirdparty + if ($object->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + // Define a complementary filter for search of next/prev ref. if (! $user->rights->projet->all->lire) { - $projectsListId = $object->getProjectsAuthorizedForUser($user,0,0); - $object->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; } - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '', $param); - print '
    '.$langs->trans("Label").''.$object->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($object->thirdparty->id)) print $object->thirdparty->getNomUrl(1); - else print ' '; - print '
    '; + // Visibility - print ''; - - // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; - - // Budget - print ''; - + + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + print '
    '.$langs->trans("Visibility").''; + print '
    '.$langs->trans("Visibility").''; if ($object->public) print $langs->trans('SharedProject'); else print $langs->trans('PrivateProject'); print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($object->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($object->date_end,'day'); - print '
    '.$langs->trans("Budget").''; - if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,0,0,0,$conf->currency); - print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($object->date_start,'day'); + $end=dol_print_date($object->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; + if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,1,0,0,$conf->currency); + print '
    '; - + print ''; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($object->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print ''; + + print '
    '; + + dol_fiche_end(); } diff --git a/htdocs/projet/info.php b/htdocs/projet/info.php index c2e45560f74..5a975b4ec1e 100644 --- a/htdocs/projet/info.php +++ b/htdocs/projet/info.php @@ -26,44 +26,153 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; - -if (!$user->rights->projet->lire) accessforbidden(); +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; $langs->load("projects"); +if (GETPOST('actioncode','array')) +{ + $actioncode=GETPOST('actioncode','array',3); + if (! count($actioncode)) $actioncode='0'; +} +else +{ + $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE)); +} +$search_agenda_label=GETPOST('search_agenda_label'); + // Security check $socid=0; $id = GETPOST("id",'int'); if ($user->societe_id) $socid=$user->societe_id; $result=restrictedArea($user,'projet',$id,''); +if (!$user->rights->projet->lire) accessforbidden(); + + + +/* + * Actions + */ + +$parameters=array('id'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +{ + $actioncode=''; + $search_agenda_label=''; +} + /* * View */ +$form = new Form($db); + $title=$langs->trans("Project").' - '.$object->ref.' '.$object->name; if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->ref.' '.$object->name.' - '.$langs->trans("Info"); $help_url="EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"; llxHeader("",$title,$help_url); -$projet = new Project($db); -$projet->fetch($id); -$projet->info($id); -$soc = new Societe($db); -$soc->fetch($projet->socid); +$object = new Project($db); +$object->fetch($id); +$object->fetch_thirdparty(); +$object->info($id); -$head = project_prepare_head($projet); +$head = project_prepare_head($object); -dol_fiche_head($head, 'info', $langs->trans("Project"), 0, ($object->public?'projectpub':'project')); +dol_fiche_head($head, 'agenda', $langs->trans("Project"), 0, ($object->public?'projectpub':'project')); -print '
    '; -dol_print_object_info($projet); -print '
    '; +// Project card + +$linkback = ''.$langs->trans("BackToList").''; + +$morehtmlref='
    '; +// Title +$morehtmlref.=$object->title; +// Thirdparty +if ($object->thirdparty->id > 0) +{ + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); +} +$morehtmlref.='
    '; + +// Define a complementary filter for search of next/prev ref. +if (! $user->rights->projet->all->lire) +{ + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; +} + +dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + +print '
    '; +print '
    '; + +dol_print_object_info($object, 1); print '
    '; +print '
    '; + +dol_fiche_end(); + + +// Actions buttons + +$out=''; +$permok=$user->rights->agenda->myactions->create; +if ($permok) +{ + $out.='&projectid='.$object->id; +} + + +print '
    '; + +if (! empty($conf->agenda->enabled)) +{ + if (! empty($user->rights->agenda->myactions->create) || ! empty($user->rights->agenda->allactions->create)) + { + print ''.$langs->trans("AddAction").''; + } + else + { + print ''.$langs->trans("AddAction").''; + } +} + +print '
    '; + + +if (!empty($object->id)) +{ + print load_fiche_titre($langs->trans("ActionsOnProject"),'',''); + + // List of actions on element + /*include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions=new FormActions($db); + $somethingshown=$formactions->showactions($object,'project',0);*/ + + // List of todo actions + //show_actions_todo($conf,$langs,$db,$object,null,0,$actioncode); + + // List of done actions + //show_actions_done($conf,$langs,$db,$object,null,0,$actioncode); + + // List of all actions + $filters=array(); + $filters['search_agenda_label']=$search_agenda_label; + show_actions_done($conf,$langs,$db,$object,null,0,$actioncode, '', $filters); +} + + llxFooter(); $db->close(); diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index 04edadda890..787d902768d 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -63,6 +63,7 @@ $pageprev = $page - 1; $pagenext = $page + 1; $search_all=GETPOST("search_all"); +$search_categ=GETPOST("search_categ",'alpha'); $search_ref=GETPOST("search_ref"); $search_label=GETPOST("search_label"); $search_societe=GETPOST("search_societe"); @@ -141,33 +142,44 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } -// Do we click on purge search criteria ? -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +$parameters=array('socid'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) { - $search_all=''; - $search_ref=""; - $search_label=""; - $search_societe=""; - $search_year=""; - $search_status=-1; - $search_opp_status=-1; - $search_opp_amount=''; - $search_opp_percent=''; - $search_budget_amount=''; - $search_public=""; - $search_sale=""; - $search_user=''; - $sday=""; - $smonth=""; - $syear=""; - $day=""; - $month=""; - $year=""; - $search_array_options=array(); -} + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + // Purge search criteria + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers + { + $search_all=''; + $search_categ=''; + $search_ref=""; + $search_label=""; + $search_societe=""; + $search_year=""; + $search_status=-1; + $search_opp_status=-1; + $search_opp_amount=''; + $search_opp_percent=''; + $search_budget_amount=''; + $search_public=""; + $search_sale=""; + $search_user=''; + $sday=""; + $smonth=""; + $syear=""; + $day=""; + $month=""; + $year=""; + $search_array_options=array(); + } +} /* @@ -183,8 +195,6 @@ $formproject = new FormProjets($db); $title=$langs->trans("Projects"); if ($search_user == $user->id) $title=$langs->trans("MyProjects"); -llxHeader("",$title,"EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"); - // Get list of project id allowed to user (in a string list separated by coma) if (! $user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1,$socid); @@ -204,13 +214,16 @@ if ($resql) else dol_print_error($db); if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0'; // To avoid sql syntax error if not found + $distinct='DISTINCT'; // We add distinct until we are added a protection to be sure a contact of a project and task is only once. $sql = "SELECT ".$distinct." p.rowid as projectid, p.ref, p.title, p.fk_statut, p.fk_opp_status, p.public, p.fk_user_creat"; $sql.= ", p.datec as date_creation, p.dateo as date_start, p.datee as date_end, p.opp_amount, p.opp_percent, p.tms as date_update, p.budget_amount"; $sql.= ", s.nom as name, s.rowid as socid"; $sql.= ", cls.code as opp_status_code"; +// We'll need these fields in order to filter by categ +if ($search_categ) $sql .= ", cs.fk_categorie, cs.fk_project"; // Add fields for extrafields -foreach ($extrafields->attribute_list as $key => $val) $sql.=",ef.".$key.' as options_'.$key; +foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key.' as options_'.$key : ''); // Add fields from hooks $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook @@ -219,6 +232,8 @@ $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_extrafields as ef on (p.rowid = ef.fk_object)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls on p.fk_opp_status = cls.rowid"; +// We'll need this table joined to the select in order to filter by categ +if (! empty($search_categ)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_project as cs ON p.rowid = cs.fk_project"; // We'll need this table joined to the select in order to filter by categ // We'll need this table joined to the select in order to filter by sale if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON sc.fk_soc = s.rowid"; if ($search_user > 0) @@ -229,6 +244,8 @@ $sql.= " WHERE p.entity IN (".getEntity('project',1).')'; if (! $user->rights->projet->all->lire) $sql.= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users // No need to check company, as filtering of projects must be done by getProjectsAuthorizedForUser if ($socid) $sql.= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; +if ($search_categ > 0) $sql.= " AND cs.fk_categorie = ".$db->escape($search_categ); +if ($search_categ == -2) $sql.= " AND cs.fk_categorie IS NULL"; if ($search_ref) $sql .= natural_search('p.ref', $search_ref); if ($search_label) $sql .= natural_search('p.title', $search_label); if ($search_societe) $sql .= natural_search('s.nom', $search_societe); @@ -261,12 +278,16 @@ else if ($year > 0) $sql.= " AND p.datee BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); -if ($search_status >= 0) $sql .= " AND p.fk_statut = ".$db->escape($search_status); +if ($search_status >= 0) +{ + if ($search_status == 99) $sql .= " AND p.fk_statut <> 2"; + else $sql .= " AND p.fk_statut = ".$db->escape($search_status); +} if ($search_opp_status) { if (is_numeric($search_opp_status) && $search_opp_status > 0) $sql .= " AND p.fk_opp_status = ".$db->escape($search_opp_status); if ($search_opp_status == 'all') $sql .= " AND p.fk_opp_status IS NOT NULL"; - if ($search_opp_status == 'openedopp') $sql .= " AND p.fk_opp_status IS NOT NULL AND p.fk_opp_status NOT IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WIN','LOST'))"; + if ($search_opp_status == 'openedopp') $sql .= " AND p.fk_opp_status IS NOT NULL AND p.fk_opp_status NOT IN (SELECT rowid FROM ".MAIN_DB_PREFIX."c_lead_status WHERE code IN ('WON','LOST'))"; if ($search_opp_status == 'none') $sql .= " AND p.fk_opp_status IS NULL"; } if ($search_public!='') $sql .= " AND p.public = ".$db->escape($search_public); @@ -307,467 +328,546 @@ $sql.= $db->plimit($limit + 1,$offset); dol_syslog("list allowed project", LOG_DEBUG); //print $sql; $resql = $db->query($sql); -if ($resql) +if (! $resql) { - $var=true; - $num = $db->num_rows($resql); - - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sday) $param.='&sday='.$day; - if ($smonth) $param.='&smonth='.$smonth; - if ($syear) $param.='&syear=' .$syear; - if ($day) $param.='&day='.$day; - if ($month) $param.='&month='.$month; - if ($year) $param.='&year=' .$year; - if ($socid) $param.='&socid='.$socid; - if ($search_all != '') $param.='&search_all='.$search_all; - if ($search_ref != '') $param.='&search_ref='.$search_ref; - if ($search_label != '') $param.='&search_label='.$search_label; - if ($search_societe != '') $param.='&search_societe='.$search_societe; - if ($search_status >= 0) $param.='&search_status='.$search_status; - if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all','none'))) $param.='&search_opp_status='.urlencode($search_opp_status); - if ((is_numeric($search_opp_percent) && $search_opp_percent >= 0) || in_array($search_opp_percent, array('all','none'))) $param.='&search_opp_percent='.urlencode($search_opp_percent); - if ($search_public != '') $param.='&search_public='.$search_public; - if ($search_user > 0) $param.='&search_user='.$search_user; - if ($search_sale > 0) $param.='&search_sale='.$search_sale; - if ($search_opp_amount != '') $param.='&search_opp_amount='.$search_opp_amount; - if ($search_budget_amount != '') $param.='&search_budget_amount='.$search_budget_amount; - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - $text=$langs->trans("Projects"); - if ($search_user == $user->id) $text=$langs->trans('MyProjects'); - - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($text, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $nbtotalofrecords, 'title_project', 0, '', '', $limit); - - // Show description of content - if ($search_user == $user->id) print $langs->trans("MyProjectsDesc").'

    '; - else - { - if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("ProjectsDesc").'

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

    '; - } - - if ($search_all) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); - } - - // If the user can view thirdparties other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; - $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth300'); - $moreforfilter.='
    '; - } - - // If the user can view user other than himself - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('ProjectsWithThisUserAsContact'). ': '; - $includeonly=''; - if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth300'); - $moreforfilter.='
    '; - - if (! empty($moreforfilter)) - { - print '
    '; - print $moreforfilter; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '
    '; - } - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print ''; - - print ''; - if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'],$_SERVER["PHP_SELF"],"p.ref","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'],$_SERVER["PHP_SELF"],"p.title","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['commercial']['checked'])) print_liste_field_titre($arrayfields['commercial']['label'],$_SERVER["PHP_SELF"],"","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.dateo']['checked'])) print_liste_field_titre($arrayfields['p.dateo']['label'],$_SERVER["PHP_SELF"],"p.dateo","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['p.datee']['checked'])) print_liste_field_titre($arrayfields['p.datee']['label'],$_SERVER["PHP_SELF"],"p.datee","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['p.public']['checked'])) print_liste_field_titre($arrayfields['p.public']['label'],$_SERVER["PHP_SELF"],"p.public","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'],$_SERVER["PHP_SELF"],'p.opp_amount',"",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'],$_SERVER["PHP_SELF"],'p.fk_opp_status',"",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'],$_SERVER["PHP_SELF"],'p.opp_percent',"",$param,'align="right"',$sortfield,$sortorder); - if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'],$_SERVER["PHP_SELF"],'p.budget_amount',"",$param,'align="right"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'],$_SERVER["PHP_SELF"],"p.fk_statut","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; - - print ''; - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.title']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - // Sale representative - if (! empty($arrayfields['commercial']['checked'])) - { - print ''; - } - // Start date - if (! empty($arrayfields['p.dateo']['checked'])) - { - print ''; - } - // End date - if (! empty($arrayfields['p.datee']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.public']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.opp_amount']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.fk_opp_status']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.opp_percent']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.budget_amount']['checked'])) - { - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['p.datec']['checked'])) - { - // Date creation - print ''; - } - if (! empty($arrayfields['p.tms']['checked'])) - { - // Date modification - print ''; - } - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print ''; - } - // Action column - print ''; - - print ''."\n"; - - $i = 0; - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); - - $projectstatic->id = $obj->projectid; - $projectstatic->user_author_id = $obj->fk_user_creat; - $projectstatic->public = $obj->public; - $projectstatic->ref = $obj->ref; - $projectstatic->datee = $obj->date_end; - $projectstatic->statut = $obj->fk_statut; - $projectstatic->opp_status = $obj->fk_opp_status; - - $userAccess = $projectstatic->restrictedProjectArea($user); // why this ? - if ($userAccess >= 0) - { - $var=!$var; - print ""; - - // Project url - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - } - // Title - if (! empty($arrayfields['p.title']['checked'])) - { - print ''; - } - // Company - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - // Sales Representatives - if (! empty($arrayfields['commercial']['checked'])) - { - print ''; - } - // Date start - if (! empty($arrayfields['p.dateo']['checked'])) - { - print ''; - } - // Date end - if (! empty($arrayfields['p.datee']['checked'])) - { - print ''; - } - // Visibility - if (! empty($arrayfields['p.public']['checked'])) - { - print ''; - } - // Amount - if (! empty($arrayfields['p.opp_amount']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.fk_opp_status']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.opp_percent']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.budget_amount']['checked'])) - { - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['p.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['p.tms']['checked'])) - { - print ''; - } - // Status - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - $projectstatic->statut = $obj->fk_statut; - print ''; - } - // Action column - print ''; - - print "\n"; - - } - - $i++; - - } - $db->free($resql); - - $parameters=array('sql' => $sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - print "
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ' '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($syear?$syear:-1,'syear',1, 20, 5); - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print ''; - $array=array(''=>'',0 => $langs->trans("PrivateProject"),1 => $langs->trans("SharedProject")); - print $form->selectarray('search_public',$array,$search_public); - print ''; - print ''; - print ''; - print $formproject->selectOpportunityStatus('search_opp_status',$search_opp_status,1,1,1); - print ''; - print ''; - print ''; - print ''; - print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; - print ''; - print ''; - print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('Draft'),'1'=>$langs->trans('Opened'),'2'=>$langs->trans('Closed')),$search_status); - print ''; - $searchpitco=$form->showFilterAndCheckAddButtons(0); - print $searchpitco; - print '
    '; - print $projectstatic->getNomUrl(1); - if ($projectstatic->hasDelay()) print img_warning($langs->trans('Late')); - print ''; - print dol_trunc($obj->title,80); - print ''; - if ($obj->socid) - { - $socstatic->id=$obj->socid; - $socstatic->name=$obj->name; - print $socstatic->getNomUrl(1); - } - else - { - print ' '; - } - print ''; - if ($obj->socid) - { - $socstatic->id=$obj->socid; - $socstatic->name=$obj->name; - $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); - $nbofsalesrepresentative=count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) // We print only number - { - print ''; - print $nbofsalesrepresentative; - print ''; - } - else if ($nbofsalesrepresentative > 0) - { - $userstatic=new User($db); - $j=0; - foreach($listsalesrepresentatives as $val) - { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['lastname']; - $userstatic->firstname=$val['firstname']; - $userstatic->email=$val['email']; - $userstatic->statut=$val['statut']; - $userstatic->entity=$val['entity']; - print $userstatic->getNomUrl(1); - $j++; - if ($j < $nbofsalesrepresentative) print ', '; - } - } - //else print $langs->trans("NoSalesRepresentativeAffected"); - } - else - { - print ' '; - } - print ''; - print dol_print_date($db->jdate($obj->date_start),'day'); - print ''; - print dol_print_date($db->jdate($obj->date_end),'day'); - print ''; - if ($obj->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print ''; - if ($obj->opp_status_code) print price($obj->opp_amount, 1, '', 1, -1, -1, ''); - print ''; - if ($obj->opp_status_code) print $langs->trans("OppStatusShort".$obj->opp_status_code); - print ''; - if ($obj->opp_percent) print price($obj->opp_percent, 1, '', 1, 0).'%'; - print ''; - if ($obj->budget_amount != '') print price($obj->budget_amount, 1, '', 1, -1, -1); - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$projectstatic->getLibStatut(5).'
    \n"; - print "\n"; + dol_print_error($db); + exit; } + +$var=true; +$num = $db->num_rows($resql); + +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +{ + $obj = $db->fetch_object($resql); + $id = $obj->projectid; + header("Location: ".DOL_URL_ROOT.'/projet/card.php?id='.$id); + exit; +} + +llxHeader("",$title,"EN:Module_Projects|FR:Module_Projets|ES:Módulo_Proyectos"); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($sday) $param.='&sday='.$day; +if ($smonth) $param.='&smonth='.$smonth; +if ($syear) $param.='&syear=' .$syear; +if ($day) $param.='&day='.$day; +if ($month) $param.='&month='.$month; +if ($year) $param.='&year=' .$year; +if ($socid) $param.='&socid='.$socid; +if ($search_all != '') $param.='&search_all='.$search_all; +if ($search_ref != '') $param.='&search_ref='.$search_ref; +if ($search_label != '') $param.='&search_label='.$search_label; +if ($search_societe != '') $param.='&search_societe='.$search_societe; +if ($search_status >= 0) $param.='&search_status='.$search_status; +if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all','openedopp','none'))) $param.='&search_opp_status='.urlencode($search_opp_status); +if ((is_numeric($search_opp_percent) && $search_opp_percent >= 0) || in_array($search_opp_percent, array('all','openedopp','none'))) $param.='&search_opp_percent='.urlencode($search_opp_percent); +if ($search_public != '') $param.='&search_public='.$search_public; +if ($search_user > 0) $param.='&search_user='.$search_user; +if ($search_sale > 0) $param.='&search_sale='.$search_sale; +if ($search_opp_amount != '') $param.='&search_opp_amount='.$search_opp_amount; +if ($search_budget_amount != '') $param.='&search_budget_amount='.$search_budget_amount; +if ($optioncss != '') $param.='&optioncss='.$optioncss; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +$text=$langs->trans("Projects"); +if ($search_user == $user->id) $text=$langs->trans('MyProjects'); + +print '
    '; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($text, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $nbtotalofrecords, 'title_project', 0, '', '', $limit); + +// Show description of content +if ($search_user == $user->id) print $langs->trans("MyProjectsDesc").'

    '; else { - dol_print_error($db); + if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("ProjectsDesc").'

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

    '; } +if ($search_all) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); +} + +$moreforfilter=''; + +// Filter on categories +if (! empty($conf->categorie->enabled)) +{ + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('Categories'). ': '; + $moreforfilter.=$formother->select_categories('project',$search_categ,'search_categ',1); + $moreforfilter.='
    '; +} + +// If the user can view user other than himself +$moreforfilter.='
    '; +$moreforfilter.=$langs->trans('ProjectsWithThisUserAsContact'). ': '; +$includeonly=''; +if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); +$moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth300'); +$moreforfilter.='
    '; + +// If the user can view thirdparties other than his' +if ($user->rights->societe->client->voir || $socid) +{ + $langs->load("commercial"); + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; + $moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth300'); + $moreforfilter.='
    '; +} + +if (! empty($moreforfilter)) +{ + print '
    '; + print $moreforfilter; + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '
    '; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print ''; + +print ''; +if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'],$_SERVER["PHP_SELF"],"p.ref","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'],$_SERVER["PHP_SELF"],"p.title","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['commercial']['checked'])) print_liste_field_titre($arrayfields['commercial']['label'],$_SERVER["PHP_SELF"],"","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['p.dateo']['checked'])) print_liste_field_titre($arrayfields['p.dateo']['label'],$_SERVER["PHP_SELF"],"p.dateo","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['p.datee']['checked'])) print_liste_field_titre($arrayfields['p.datee']['label'],$_SERVER["PHP_SELF"],"p.datee","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['p.public']['checked'])) print_liste_field_titre($arrayfields['p.public']['label'],$_SERVER["PHP_SELF"],"p.public","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'],$_SERVER["PHP_SELF"],'p.opp_amount',"",$param,'align="right"',$sortfield,$sortorder); +if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'],$_SERVER["PHP_SELF"],'p.fk_opp_status',"",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'],$_SERVER["PHP_SELF"],'p.opp_percent',"",$param,'align="right"',$sortfield,$sortorder); +if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'],$_SERVER["PHP_SELF"],'p.budget_amount',"",$param,'align="right"',$sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['p.datec']['checked'])) print_liste_field_titre($arrayfields['p.datec']['label'],$_SERVER["PHP_SELF"],"p.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['p.tms']['checked'])) print_liste_field_titre($arrayfields['p.tms']['label'],$_SERVER["PHP_SELF"],"p.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'],$_SERVER["PHP_SELF"],"p.fk_statut","",$param,'align="right"',$sortfield,$sortorder); +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); +print "\n"; + +print ''; +if (! empty($arrayfields['p.ref']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.title']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['s.nom']['checked'])) +{ + print ''; +} +// Sale representative +if (! empty($arrayfields['commercial']['checked'])) +{ + print ''; +} +// Start date +if (! empty($arrayfields['p.dateo']['checked'])) +{ + print ''; +} +// End date +if (! empty($arrayfields['p.datee']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.public']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.opp_amount']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.fk_opp_status']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.opp_percent']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.budget_amount']['checked'])) +{ + print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['p.datec']['checked'])) +{ + // Date creation + print ''; +} +if (! empty($arrayfields['p.tms']['checked'])) +{ + // Date modification + print ''; +} +if (! empty($arrayfields['p.fk_statut']['checked'])) +{ + print ''; +} +// Action column +print ''; + +print ''."\n"; + +$i=0; +$var=true; +$totalarray=array(); +while ($i < min($num,$limit)) +{ + $obj = $db->fetch_object($resql); + + $projectstatic->id = $obj->projectid; + $projectstatic->user_author_id = $obj->fk_user_creat; + $projectstatic->public = $obj->public; + $projectstatic->ref = $obj->ref; + $projectstatic->datee = $obj->date_end; + $projectstatic->statut = $obj->fk_statut; + $projectstatic->opp_status = $obj->fk_opp_status; + + $userAccess = $projectstatic->restrictedProjectArea($user); // why this ? + if ($userAccess >= 0) + { + $var=!$var; + print ""; + + // Project url + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Title + if (! empty($arrayfields['p.title']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Company + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Sales Representatives + if (! empty($arrayfields['commercial']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date start + if (! empty($arrayfields['p.dateo']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date end + if (! empty($arrayfields['p.datee']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Visibility + if (! empty($arrayfields['p.public']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Amount + if (! empty($arrayfields['p.opp_amount']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totaloppfield']=$totalarray['nbfield']; + } + if (! empty($arrayfields['p.fk_opp_status']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['p.opp_percent']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + if (! empty($arrayfields['p.budget_amount']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalbudgetfield']=$totalarray['nbfield']; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + } + } + if (! $i) $totalarray['nbfield']++; + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['p.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['p.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + if (! empty($arrayfields['p.fk_statut']['checked'])) + { + $projectstatic->statut = $obj->fk_statut; + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print "\n"; + + } + + $i++; + +} + +// Show total line +if (isset($totalarray['totaloppfield']) || isset($totalarray['totalbudgetfield'])) +{ + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + elseif ($totalarray['totaloppfield'] == $i) print ''; + elseif ($totalarray['totalbudgetfield'] == $i) print ''; + else print ''; + } + print ''; +} + +$db->free($resql); + +$parameters=array('sql' => $sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print "
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ' '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($syear?$syear:-1,'syear',1, 20, 5); + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; + $array=array(''=>'',0 => $langs->trans("PrivateProject"),1 => $langs->trans("SharedProject")); + print $form->selectarray('search_public',$array,$search_public); + print ''; + print ''; + print ''; + print $formproject->selectOpportunityStatus('search_opp_status',$search_opp_status,1,1,1); + print ''; + print ''; + print ''; + print ''; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + print ''; + print ''; + $arrayofstatus = array(); + foreach($projectstatic->statuts_short as $key => $val) $arrayofstatus[$key]=$langs->trans($val); + $arrayofstatus['99']=$langs->trans("NotClosed").' ('.$langs->trans('Draft').'+'.$langs->trans('Opened').')'; + print $form->selectarray('search_status', $arrayofstatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100'); + print ''; +$searchpitco=$form->showFilterAndCheckAddButtons(0); +print $searchpitco; +print '
    '; + print $projectstatic->getNomUrl(1); + if ($projectstatic->hasDelay()) print img_warning($langs->trans('Late')); + print ''; + print dol_trunc($obj->title,80); + print ''; + if ($obj->socid) + { + $socstatic->id=$obj->socid; + $socstatic->name=$obj->name; + print $socstatic->getNomUrl(1); + } + else + { + print ' '; + } + print ''; + if ($obj->socid) + { + $socstatic->id=$obj->socid; + $socstatic->name=$obj->name; + $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); + $nbofsalesrepresentative=count($listsalesrepresentatives); + if ($nbofsalesrepresentative > 3) // We print only number + { + print ''; + print $nbofsalesrepresentative; + print ''; + } + else if ($nbofsalesrepresentative > 0) + { + $userstatic=new User($db); + $j=0; + foreach($listsalesrepresentatives as $val) + { + $userstatic->id=$val['id']; + $userstatic->lastname=$val['lastname']; + $userstatic->firstname=$val['firstname']; + $userstatic->email=$val['email']; + $userstatic->statut=$val['statut']; + $userstatic->entity=$val['entity']; + print $userstatic->getNomUrl(1); + $j++; + if ($j < $nbofsalesrepresentative) print ', '; + } + } + //else print $langs->trans("NoSalesRepresentativeAffected"); + } + else + { + print ' '; + } + print ''; + print dol_print_date($db->jdate($obj->date_start),'day'); + print ''; + print dol_print_date($db->jdate($obj->date_end),'day'); + print ''; + if ($obj->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print ''; + if ($obj->opp_status_code) + { + print price($obj->opp_amount, 1, '', 1, -1, -1, ''); + $totalarray['totalopp'] += $obj->opp_amount; + } + print ''; + if ($obj->opp_status_code) print $langs->trans("OppStatusShort".$obj->opp_status_code); + print ''; + if ($obj->opp_percent) print price($obj->opp_percent, 1, '', 1, 0).'%'; + print ''; + if ($obj->budget_amount != '') + { + print price($obj->budget_amount, 1, '', 1, -1, -1); + $totalarray['totalbudget'] += $obj->budget_amount; + } + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour'); + print ''.$projectstatic->getLibStatut(5).''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['totalopp']).''.price($totalarray['totalbudget']).'
    \n"; +print "
    \n"; llxFooter(); diff --git a/htdocs/projet/note.php b/htdocs/projet/note.php index 43df7ce3b3d..31081c92256 100644 --- a/htdocs/projet/note.php +++ b/htdocs/projet/note.php @@ -79,61 +79,41 @@ if ($id > 0 || ! empty($ref)) $head = project_prepare_head($object); dol_fiche_head($head, 'notes', $langs->trans('Project'), 0, ($object->public?'projectpub':'project')); - print ''; - + + // Project card + $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - - // Label - print ''; - - // Third party - print ''; - - // Visibility - print ''; - - // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; - - // Budget - print ''; - print "
    '.$langs->trans("Ref").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$object->title; + // Thirdparty + if ($object->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + // Define a complementary filter for search of next/prev ref. if (! $user->rights->projet->all->lire) { - $projectsListId = $object->getProjectsAuthorizedForUser($user,0,0); - $object->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; } - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref'); - print '
    '.$langs->trans("Label").''.$object->title.'
    '.$langs->trans("ThirdParty").''; - if ($object->thirdparty->id > 0) print $object->thirdparty->getNomUrl(1); - else print' '; - print '
    '.$langs->trans("Visibility").''; - if ($object->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($object->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($object->date_end,'day'); - print '
    '.$langs->trans("Budget").''; - if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,0,0,0,$conf->currency); - print '
    "; - - print '
    '; - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
    '; + print '
    '; + $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; - + + print '
    '; + + print '
    '; + dol_fiche_end(); } diff --git a/htdocs/projet/tasks.php b/htdocs/projet/tasks.php index 9def807c746..986c0537bc5 100644 --- a/htdocs/projet/tasks.php +++ b/htdocs/projet/tasks.php @@ -211,64 +211,106 @@ if ($id > 0 || ! empty($ref)) $param=($mode=='mine'?'&mode=mine':''); - print ''; - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$object->title; + // Thirdparty + if ($object->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $object->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print ''; + print '
    '; + print '
    '; + print '
    '; - print '
    '; - print ''; + print '
    '; - print $langs->trans("Ref"); - print ''; - // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) - { - $projectsListId = $object->getProjectsAuthorizedForUser($user,0,0); - $object->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; - } - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '', $param); - print '
    '.$langs->trans("Label").''.$object->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($object->thirdparty->id)) print $object->thirdparty->getNomUrl(1); - else print ' '; - print '
    '; - // Visibility - print ''; + // Visibility + print ''; - // Statut - print ''; + /*if (! empty($conf->global->PROJECT_USE_OPPORTUNITIES)) + { + // Opportunity status + print ''; - // Date start - print ''; + // Opportunity percent + print ''; - // Date end - print ''; + // Opportunity Amount + print ''; + }*/ - // Budget - print ''; - - // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && ! empty($extrafields_project->attribute_label)) - { - print $object->showOptionals($extrafields_project); - } + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Visibility").''; - if ($object->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
    '.$langs->trans("Visibility").''; + if ($object->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print '
    '.$langs->trans("Status").''.$object->getLibStatut(4).'
    '.$langs->trans("OpportunityStatus").''; + $code = dol_getIdFromCode($db, $object->opp_status, 'c_lead_status', 'rowid', 'code'); + if ($code) print $langs->trans("OppStatus".$code); + print '
    '.$langs->trans("DateStart").''; - print dol_print_date($object->date_start,'day'); - print '
    '.$langs->trans("OpportunityProbability").''; + if (strcmp($object->opp_percent,'')) print price($object->opp_percent,'',$langs,1,0).' %'; + print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($object->date_end,'day'); - print '
    '.$langs->trans("OpportunityAmount").''; + if (strcmp($object->opp_amount,'')) print price($object->opp_amount,'',$langs,1,0,0,$conf->currency); + print '
    '.$langs->trans("Budget").''; - if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,0,0,0,$conf->currency); - print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($object->date_start,'day'); + $end=dol_print_date($object->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; + if (strcmp($object->budget_amount, '')) print price($object->budget_amount,'',$langs,1,0,0,$conf->currency); + print '
    '; + + print ''; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($object->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($object->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print ''; + + print '
    '; - print '
    '; dol_fiche_end(); } diff --git a/htdocs/projet/tasks/contact.php b/htdocs/projet/tasks/contact.php index 6689f966c15..dcb9f7426a8 100644 --- a/htdocs/projet/tasks/contact.php +++ b/htdocs/projet/tasks/contact.php @@ -191,49 +191,85 @@ if ($id > 0 || ! empty($ref)) $param=($mode=='mine'?'&mode=mine':''); - print ''; - - // Ref - print ''; - - print ''; - - print ''; - print ''; - - // Visibility - print ''; - - // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; - - print '
    '; - print $langs->trans("Ref"); - print ''; - // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) - { - $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,0); - $projectstatic->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; - } - print $form->showrefnav($projectstatic,'project_ref','',1,'ref','ref','',$param.'&withproject=1'); - print '
    '.$langs->trans("Label").''.$projectstatic->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($projectstatic->thirdparty->id)) print $projectstatic->thirdparty->getNomUrl(1); - else print ' '; - print '
    '.$langs->trans("Visibility").''; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
    '.$langs->trans("Status").''.$projectstatic->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($projectstatic->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($projectstatic->date_end,'day'); - print '
    '; + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$projectstatic->title; + // Thirdparty + if ($projectstatic->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $projectstatic->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $projectstatic->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($projectstatic, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Visibility + print ''; + + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Visibility").''; + if ($projectstatic->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($projectstatic->date_start,'day'); + $end=dol_print_date($projectstatic->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; + if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount,'',$langs,1,0,0,$conf->currency); + print '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($projectstatic->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($projectstatic->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; dol_fiche_end(); } diff --git a/htdocs/projet/tasks/document.php b/htdocs/projet/tasks/document.php index c9a69fc81a4..7c62fb651f1 100644 --- a/htdocs/projet/tasks/document.php +++ b/htdocs/projet/tasks/document.php @@ -134,50 +134,86 @@ if ($object->id > 0) $param=($mode=='mine'?'&mode=mine':''); - print ''; - - // Ref - print ''; - - print ''; - - print ''; - print ''; - - // Visibility - print ''; - - // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; - - print '
    '; - print $langs->trans("Ref"); - print ''; - // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) - { - $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,0); - $projectstatic->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; - } - print $form->showrefnav($projectstatic,'project_ref','',1,'ref','ref','',$param.'&withproject=1'); - print '
    '.$langs->trans("Label").''.$projectstatic->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($projectstatic->thirdparty->id)) print $projectstatic->thirdparty->getNomUrl(1); - else print ' '; - print '
    '.$langs->trans("Visibility").''; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
    '.$langs->trans("Status").''.$projectstatic->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($projectstatic->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($projectstatic->date_end,'day'); - print '
    '; + // Project card + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$projectstatic->title; + // Thirdparty + if ($projectstatic->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $projectstatic->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $projectstatic->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($projectstatic, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Visibility + print ''; + + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Visibility").''; + if ($projectstatic->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($projectstatic->date_start,'day'); + $end=dol_print_date($projectstatic->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; + if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount,'',$langs,1,0,0,$conf->currency); + print '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($projectstatic->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($projectstatic->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + dol_fiche_end(); } @@ -242,6 +278,7 @@ if ($object->id > 0) if ($withproject) $param .= '&withproject=1'; $modulepart = 'project_task'; $permission = $user->rights->projet->creer; + $permtoedit = $user->rights->projet->creer; $relativepathwithnofile=dol_sanitizeFileName($projectstatic->ref).'/'.dol_sanitizeFileName($object->ref).'/'; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/projet/tasks/list.php b/htdocs/projet/tasks/list.php index 47083e9032d..1179ca7546e 100644 --- a/htdocs/projet/tasks/list.php +++ b/htdocs/projet/tasks/list.php @@ -99,14 +99,14 @@ $fieldstosearchall = array( if (empty($user->socid)) $fieldstosearchall['t.note_private']="NotePrivate"; $arrayfields=array( - 'p.ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>1), - 'p.title'=>array('label'=>$langs->trans("ProjectLabel"), 'checked'=>0), - 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>0), - 'p.fk_statut'=>array('label'=>$langs->trans("ProjectStatus"), 'checked'=>1), 't.ref'=>array('label'=>$langs->trans("RefTask"), 'checked'=>1, 'position'=>80), 't.label'=>array('label'=>$langs->trans("LabelTask"), 'checked'=>1, 'position'=>80), 't.dateo'=>array('label'=>$langs->trans("DateStart"), 'checked'=>1, 'position'=>100), 't.datee'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1, 'position'=>101), + 'p.ref'=>array('label'=>$langs->trans("ProjectRef"), 'checked'=>1), + 'p.title'=>array('label'=>$langs->trans("ProjectLabel"), 'checked'=>0), + 's.nom'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>0), + 'p.fk_statut'=>array('label'=>$langs->trans("ProjectStatus"), 'checked'=>1), 't.planned_workload'=>array('label'=>$langs->trans("PlannedWorkload"), 'checked'=>1, 'position'=>102), 't.duration_effective'=>array('label'=>$langs->trans("TimeSpent"), 'checked'=>1, 'position'=>103), 't.progress_calculated'=>array('label'=>$langs->trans("ProgressCalculated"), 'checked'=>1, 'position'=>104), @@ -129,28 +129,41 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } -// Purge criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +$parameters=array('socid'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) { - $search_all=""; - $search_project=""; - $search_projectstatus=-1; - $search_project_ref=""; - $search_project_title=""; - $search_task_ref=""; - $search_task_label=""; - $search_task_description=""; - $search_task_user=-1; - $search_project_user=-1; - $sday=''; - $smonth=''; - $syear=''; - $day=''; - $month=''; - $year=''; + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers + { + $search_all=""; + $search_project=""; + $search_projectstatus=-1; + $search_project_ref=""; + $search_project_title=""; + $search_task_ref=""; + $search_task_label=""; + $search_task_description=""; + $search_task_user=-1; + $search_project_user=-1; + $sday=''; + $smonth=''; + $syear=''; + $day=''; + $month=''; + $year=''; + $search_array_options=array(); + } } + if (empty($search_projectstatus) && $search_projectstatus == '') $search_projectstatus=1; @@ -173,8 +186,6 @@ if ($search_task_user > 0) $tuser->fetch($search_task_user); $title=$langs->trans("Activities"); if ($search_task_user == $user->id) $title=$langs->trans("MyActivities"); -llxHeader("",$title,"Projet"); - if ($id) { $projectstatic->fetch($id); @@ -221,8 +232,8 @@ $sql = "SELECT ".$distinct." p.rowid as projectid, p.ref as projectref, p.title $sql.= ", s.nom as name, s.rowid as socid"; $sql.= ", t.datec as date_creation, t.dateo as date_start, t.datee as date_end, t.tms as date_update"; $sql.= ", t.rowid as id, t.ref, t.label, t.planned_workload, t.duration_effective, t.progress, t.fk_statut"; -// Add fields for extrafields -foreach ($extrafields->attribute_list as $key => $val) $sql.=",ef.".$key.' as options_'.$key; +// 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 $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook @@ -231,14 +242,8 @@ $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid,"; $sql.= " ".MAIN_DB_PREFIX."projet_task as t"; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($search_project_user > 0) -{ - $sql.=", ".MAIN_DB_PREFIX."element_contact as ecp"; -} -if ($search_task_user > 0) -{ - $sql.=", ".MAIN_DB_PREFIX."element_contact as ect"; -} +if ($search_project_user > 0) $sql.=", ".MAIN_DB_PREFIX."element_contact as ecp"; +if ($search_task_user > 0) $sql.=", ".MAIN_DB_PREFIX."element_contact as ect"; $sql.= " WHERE t.fk_projet = p.rowid"; $sql.= " AND p.entity IN (".getEntity('project',1).')'; if (! $user->rights->projet->all->lire) $sql.=" AND p.rowid IN (".($projectsListId?$projectsListId:'0').")"; // public and assigned to projects, or restricted to company for external users @@ -276,7 +281,11 @@ else if ($year > 0) $sql.= " AND t.datee BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); -if ($search_projectstatus >= 0) $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); +if ($search_projectstatus >= 0) +{ + if ($search_projectstatus == 99) $sql .= " AND p.fk_statut <> 2"; + else $sql .= " AND p.fk_statut = ".$db->escape($search_projectstatus); +} if ($search_public!='') $sql .= " AND p.public = ".$db->escape($search_public); if ($search_project_user > 0) $sql.= " AND ecp.fk_c_type_contact IN (".join(',',array_keys($listofprojectcontacttype)).") AND ecp.element_id = p.rowid AND ecp.fk_socpeople = ".$search_project_user; if ($search_task_user > 0) $sql.= " AND ect.fk_c_type_contact IN (".join(',',array_keys($listoftaskcontacttype)).") AND ect.element_id = t.rowid AND ect.fk_socpeople = ".$search_task_user; @@ -312,454 +321,513 @@ $sql.= $db->plimit($limit + 1,$offset); dol_syslog("list allowed project", LOG_DEBUG); //print $sql; $resql = $db->query($sql); -if ($resql) -{ - $var=true; - $num = $db->num_rows($resql); - - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sday) $param.='&sday='.$day; - if ($smonth) $param.='&smonth='.$smonth; - if ($syear) $param.='&syear=' .$syear; - if ($day) $param.='&day='.$day; - if ($month) $param.='&month='.$month; - if ($year) $param.='&year=' .$year; - if ($socid) $param.='&socid='.$socid; - if ($search_all != '') $param.='&search_all='.$search_all; - if ($search_project_ref != '') $param.='&search_project_ref='.$search_project_ref; - if ($search_project_title != '') $param.='&search_project_title='.$search_project_title; - if ($search_ref != '') $param.='&search_ref='.$search_ref; - if ($search_label != '') $param.='&search_label='.$search_label; - if ($search_societe != '') $param.='&search_societe='.$search_societe; - if ($search_projectstatus != '') $param.='&search_projectstatus='.$search_projectstatus; - if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all','none'))) $param.='&search_opp_status='.urlencode($search_opp_status); - if ($search_public != '') $param.='&search_public='.$search_public; - if ($search_project_user > 0) $param.='&search_project_user='.$search_project_user; - if ($search_task_user > 0) $param.='&search_task_user='.$search_task_user; - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - print '
    '; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, $nbtotalofrecords, 'title_project', 0, '', '', $limit); - - // Show description of content - if ($search_task_user == $user->id) print $langs->trans("MyTasksDesc").'

    '; - else - { - if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("TasksOnProjectsDesc").'

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

    '; - } - - if ($search_all) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); - } - - // If the user can view users - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('ProjectsWithThisUserAsContact'). ' '; - $includeonly=''; - if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); - $moreforfilter.=$form->select_dolusers($search_project_user, 'search_project_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth300'); - $moreforfilter.='
    '; - - // If the user can view users - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('TasksWithThisUserAsContact'). ': '; - $includeonly=''; - if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); - $moreforfilter.=$form->select_dolusers($search_task_user, 'search_task_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth300'); - $moreforfilter.='
    '; - - if (! empty($moreforfilter)) - { - print '
    '; - print $moreforfilter; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - print '
    '; - } - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print ''; - - print ''; - if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'],$_SERVER["PHP_SELF"],"p.ref","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'],$_SERVER["PHP_SELF"],"p.title","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'],$_SERVER["PHP_SELF"],"p.fk_statut","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'],$_SERVER["PHP_SELF"],"t.ref","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'],$_SERVER["PHP_SELF"],"t.label","",$param,"",$sortfield,$sortorder); - if (! empty($arrayfields['t.dateo']['checked'])) print_liste_field_titre($arrayfields['t.dateo']['label'],$_SERVER["PHP_SELF"],"t.dateo","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['t.datee']['checked'])) print_liste_field_titre($arrayfields['t.datee']['label'],$_SERVER["PHP_SELF"],"t.datee","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['t.planned_workload']['checked'])) print_liste_field_titre($arrayfields['t.planned_workload']['label'],$_SERVER["PHP_SELF"],"t.planned_workload","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['t.duration_effective']['checked'])) print_liste_field_titre($arrayfields['t.duration_effective']['label'],$_SERVER["PHP_SELF"],"t.duration_effective","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['t.progress_calculated']['checked'])) print_liste_field_titre($arrayfields['t.progress_calculated']['label'],$_SERVER["PHP_SELF"],"","",$param,'align="center"'); - if (! empty($arrayfields['t.progress']['checked'])) print_liste_field_titre($arrayfields['t.progress']['label'],$_SERVER["PHP_SELF"],"t.progress","",$param,'align="center"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'],$_SERVER["PHP_SELF"],"t.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'],$_SERVER["PHP_SELF"],"t.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; - - print ''; - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.title']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print ''; - } - if (! empty($arrayfields['t.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['t.label']['checked'])) - { - print ''; - } - // Start date - if (! empty($arrayfields['t.dateo']['checked'])) - { - print ''; - } - // End date - if (! empty($arrayfields['t.datee']['checked'])) - { - print ''; - } - if (! empty($arrayfields['t.planned_workload']['checked'])) print ''; - if (! empty($arrayfields['t.duration_effective']['checked'])) print ''; - if (! empty($arrayfields['t.progress_calculated']['checked'])) print ''; - if (! empty($arrayfields['t.progress']['checked'])) print ''; - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['t.datec']['checked'])) - { - // Date creation - print ''; - } - if (! empty($arrayfields['t.tms']['checked'])) - { - // Date modification - print ''; - } - // Action column - print ''; - print ''; - - - $i = 0; - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); - - $projectstatic->id = $obj->projectid; - $projectstatic->ref = $obj->projectref; - $projectstatic->title = $obj->projecttitle; - $projectstatic->public = $obj->public; - $projectstatic->statut = $obj->projectstatus; - $projectstatic->datee = $db->jdate($obj->projectdatee); - - $taskstatic->id = $obj->id; - $taskstatic->ref = $obj->ref; - $taskstatic->label = $obj->label; - $taskstatic->fk_statut = $obj->fk_statut; - $taskstatic->progress = $obj->progress; - $taskstatic->datee = $db->jdate($obj->date_end); // deprecated - $taskstatic->date_end = $db->jdate($obj->date_end); - - $userAccess = $projectstatic->restrictedProjectArea($user); // why this ? - if ($userAccess >= 0) - { - $var=!$var; - print ""; - - // Project url - if (! empty($arrayfields['p.ref']['checked'])) - { - print ''; - } - // Title - if (! empty($arrayfields['p.title']['checked'])) - { - print ''; - } - // Company - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - // Status - if (! empty($arrayfields['p.fk_statut']['checked'])) - { - print ''; - } - // Ref - if (! empty($arrayfields['t.ref']['checked'])) - { - print ''; - } - // Label - if (! empty($arrayfields['t.label']['checked'])) - { - print ''; - } - // Date start - if (! empty($arrayfields['t.dateo']['checked'])) - { - print ''; - } - // Date end - if (! empty($arrayfields['t.datee']['checked'])) - { - print ''; - } - - $plannedworkloadoutputformat='allhourmin'; - $timespentoutputformat='allhourmin'; - if (! empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat=$conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; - if (! empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat=$conf->global->PROJECT_TIME_SPENT_FORMAT; - - // Planned workload - if (! empty($arrayfields['t.planned_workload']['checked'])) - { - print ''; - } - // Time spent - if (! empty($arrayfields['t.duration_effective']['checked'])) - { - $showlineingray=0;$showproject=1; - print ''; - } - // Calculated progress - if (! empty($arrayfields['t.progress_calculated']['checked'])) - { - print ''; - } - // Declared progress - if (! empty($arrayfields['t.progress']['checked'])) - { - print ''; - } - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['t.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['t.tms']['checked'])) - { - print ''; - } - // Status - /*if (! empty($arrayfields['p.fk_statut']['checked'])) - { - $projectstatic->statut = $obj->fk_statut; - print ''; - }*/ - // Action column - print ''; - - print "\n"; - - //print projectLinesa(); - } - - $i++; - } - $db->free($resql); - - $parameters=array('sql' => $sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - print "
    '; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $listofstatus=array(-1=>' '); - foreach($projectstatic->statuts_short as $key => $val) $listofstatus[$key]=$langs->trans($val); - print $form->selectarray('search_projectstatus', $listofstatus, $search_projectstatus); - print ''; - print ''; - print ''; - print ''; - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($syear?$syear:-1,'syear',1, 20, 5); - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year?$year:-1,'year',1, 20, 5); - print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } - print ''; - print ''; - print ''; - $searchpitco=$form->showFilterAndCheckAddButtons(0); - print $searchpitco; - print '
    '; - print $projectstatic->getNomUrl(1, 'task'); - if ($projectstatic->hasDelay()) print img_warning("Late"); - print ''; - print dol_trunc($obj->projecttitle,80); - print ''; - if ($obj->socid) - { - $socstatic->id=$obj->socid; - $socstatic->name=$obj->name; - print $socstatic->getNomUrl(1); - } - else - { - print ' '; - } - print ''; - print $projectstatic->getLibStatut(1); - print ''; - print $taskstatic->getNomUrl(1,'withproject'); - if ($taskstatic->hasDelay()) print img_warning("Late"); - print ''; - print $taskstatic->label; - print ''; - print dol_print_date($db->jdate($obj->date_start),'day'); - print ''; - print dol_print_date($db->jdate($obj->date_end),'day'); - print ''; - $fullhour=convertSecondToTime($obj->planned_workload,$plannedworkloadoutputformat); - $workingdelay=convertSecondToTime($obj->planned_workload,'all',86400,7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks - if ($obj->planned_workload != '') - { - print $fullhour; - // TODO Add delay taking account of working hours per day and working day per week - //if ($workingdelay != $fullhour) print '
    ('.$workingdelay.')'; - } - //else print '--:--'; - print '
    '; - if ($showlineingray) print ''; - else print ''; - if ($obj->duration_effective) print convertSecondToTime($obj->duration_effective,$timespentoutputformat); - else print '--:--'; - if ($showlineingray) print ''; - else print ''; - print ''; - if ($obj->planned_workload || $obj->duration_effective) - { - if ($obj->planned_workload) print round(100 * $obj->duration_effective / $obj->planned_workload,2).' %'; - else print $langs->trans('WorkloadNotDefined'); - } - print ''; - if ($obj->progress != '') - { - print $obj->progress.' %'; - } - print ''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$projectstatic->getLibStatut(5).'
    "; - - print '
    '; -} -else +if (! $resql) { dol_print_error($db); + exit; } +$var=true; +$num = $db->num_rows($resql); + +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) +{ + $obj = $db->fetch_object($resql); + $id = $obj->id; + header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); + exit; +} + +llxHeader("",$title,"Projet"); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($sday) $param.='&sday='.$day; +if ($smonth) $param.='&smonth='.$smonth; +if ($syear) $param.='&syear=' .$syear; +if ($day) $param.='&day='.$day; +if ($month) $param.='&month='.$month; +if ($year) $param.='&year=' .$year; +if ($socid) $param.='&socid='.$socid; +if ($search_all != '') $param.='&search_all='.$search_all; +if ($search_project_ref != '') $param.='&search_project_ref='.$search_project_ref; +if ($search_project_title != '') $param.='&search_project_title='.$search_project_title; +if ($search_ref != '') $param.='&search_ref='.$search_ref; +if ($search_label != '') $param.='&search_label='.$search_label; +if ($search_societe != '') $param.='&search_societe='.$search_societe; +if ($search_projectstatus != '') $param.='&search_projectstatus='.$search_projectstatus; +if ((is_numeric($search_opp_status) && $search_opp_status >= 0) || in_array($search_opp_status, array('all','none'))) $param.='&search_opp_status='.urlencode($search_opp_status); +if ($search_public != '') $param.='&search_public='.$search_public; +if ($search_project_user > 0) $param.='&search_project_user='.$search_project_user; +if ($search_task_user > 0) $param.='&search_task_user='.$search_task_user; +if ($optioncss != '') $param.='&optioncss='.$optioncss; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +print '
    '; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, "", $num, $nbtotalofrecords, 'title_project', 0, '', '', $limit); + +// Show description of content +if ($search_task_user == $user->id) print $langs->trans("MyTasksDesc").'

    '; +else +{ + if ($user->rights->projet->all->lire && ! $socid) print $langs->trans("TasksOnProjectsDesc").'

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

    '; +} + +if ($search_all) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $search_all) . join(', ',$fieldstosearchall); +} + +// If the user can view users +$moreforfilter.='
    '; +$moreforfilter.=$langs->trans('ProjectsWithThisUserAsContact'). ' '; +$includeonly=''; +if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); +$moreforfilter.=$form->select_dolusers($search_project_user, 'search_project_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth300'); +$moreforfilter.='
    '; + +// If the user can view users +$moreforfilter.='
    '; +$moreforfilter.=$langs->trans('TasksWithThisUserAsContact'). ': '; +$includeonly=''; +if (empty($user->rights->user->user->lire)) $includeonly=array($user->id); +$moreforfilter.=$form->select_dolusers($search_task_user, 'search_task_user', 1, '', 0, $includeonly, '', 0, 0, 0, '', 0, '', 'maxwidth300'); +$moreforfilter.='
    '; + +if (! empty($moreforfilter)) +{ + print '
    '; + print $moreforfilter; + $parameters=array(); + $reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + print '
    '; +} + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print ''; + +print ''; +if (! empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'],$_SERVER["PHP_SELF"],"t.ref","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'],$_SERVER["PHP_SELF"],"t.label","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['t.dateo']['checked'])) print_liste_field_titre($arrayfields['t.dateo']['label'],$_SERVER["PHP_SELF"],"t.dateo","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['t.datee']['checked'])) print_liste_field_titre($arrayfields['t.datee']['label'],$_SERVER["PHP_SELF"],"t.datee","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'],$_SERVER["PHP_SELF"],"p.ref","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'],$_SERVER["PHP_SELF"],"p.title","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'],$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['p.fk_statut']['checked'])) print_liste_field_titre($arrayfields['p.fk_statut']['label'],$_SERVER["PHP_SELF"],"p.fk_statut","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['t.planned_workload']['checked'])) print_liste_field_titre($arrayfields['t.planned_workload']['label'],$_SERVER["PHP_SELF"],"t.planned_workload","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['t.duration_effective']['checked'])) print_liste_field_titre($arrayfields['t.duration_effective']['label'],$_SERVER["PHP_SELF"],"t.duration_effective","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['t.progress_calculated']['checked'])) print_liste_field_titre($arrayfields['t.progress_calculated']['label'],$_SERVER["PHP_SELF"],"","",$param,'align="center"'); +if (! empty($arrayfields['t.progress']['checked'])) print_liste_field_titre($arrayfields['t.progress']['label'],$_SERVER["PHP_SELF"],"t.progress","",$param,'align="center"',$sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['t.datec']['checked'])) print_liste_field_titre($arrayfields['t.datec']['label'],$_SERVER["PHP_SELF"],"t.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['t.tms']['checked'])) print_liste_field_titre($arrayfields['t.tms']['label'],$_SERVER["PHP_SELF"],"t.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); +print "\n"; + +print ''; +if (! empty($arrayfields['t.ref']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['t.label']['checked'])) +{ + print ''; +} +// Start date +if (! empty($arrayfields['t.dateo']['checked'])) +{ + print ''; +} +// End date +if (! empty($arrayfields['t.datee']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.ref']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.title']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['s.nom']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['p.fk_statut']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['t.planned_workload']['checked'])) print ''; +if (! empty($arrayfields['t.duration_effective']['checked'])) print ''; +if (! empty($arrayfields['t.progress_calculated']['checked'])) print ''; +if (! empty($arrayfields['t.progress']['checked'])) print ''; +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['t.datec']['checked'])) +{ + // Date creation + print ''; +} +if (! empty($arrayfields['t.tms']['checked'])) +{ + // Date modification + print ''; +} +// Action column +print ''; +print ''; + + +$plannedworkloadoutputformat='allhourmin'; +$timespentoutputformat='allhourmin'; +if (! empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat=$conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; +if (! empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat=$conf->global->PROJECT_TIME_SPENT_FORMAT; + +$now = dol_now(); +$i=0; +$var=true; +$totalarray=array(); +while ($i < min($num,$limit)) +{ + $obj = $db->fetch_object($resql); + + $projectstatic->id = $obj->projectid; + $projectstatic->ref = $obj->projectref; + $projectstatic->title = $obj->projecttitle; + $projectstatic->public = $obj->public; + $projectstatic->statut = $obj->projectstatus; + $projectstatic->datee = $db->jdate($obj->projectdatee); + + $taskstatic->id = $obj->id; + $taskstatic->ref = $obj->ref; + $taskstatic->label = $obj->label; + $taskstatic->fk_statut = $obj->fk_statut; + $taskstatic->progress = $obj->progress; + $taskstatic->datee = $db->jdate($obj->date_end); // deprecated + $taskstatic->date_end = $db->jdate($obj->date_end); + + $userAccess = $projectstatic->restrictedProjectArea($user); // why this ? + if ($userAccess >= 0) + { + $var=!$var; + print ""; + + // Ref + if (! empty($arrayfields['t.ref']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Label + if (! empty($arrayfields['t.label']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date start + if (! empty($arrayfields['t.dateo']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date end + if (! empty($arrayfields['t.datee']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Project ref + if (! empty($arrayfields['p.ref']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Project title + if (! empty($arrayfields['p.title']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Third party + if (! empty($arrayfields['s.nom']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Project status + if (! empty($arrayfields['p.fk_statut']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + + // Planned workload + if (! empty($arrayfields['t.planned_workload']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totalplannedworkloadfield']=$totalarray['nbfield']; + $totalarray['totalplannedworkload'] += $obj->planned_workload; + } + // Time spent + if (! empty($arrayfields['t.duration_effective']['checked'])) + { + $showlineingray=0;$showproject=1; + print ''; + if (! $i) $totalarray['nbfield']++; + if (! $i) $totalarray['totaldurationeffectivefield']=$totalarray['nbfield']; + $totalarray['totaldurationeffective'] += $obj->duration_effective; + } + // Calculated progress + if (! empty($arrayfields['t.progress_calculated']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Declared progress + if (! empty($arrayfields['t.progress']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + } + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Date creation + if (! empty($arrayfields['t.datec']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Date modification + if (! empty($arrayfields['t.tms']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + // Status + /*if (! empty($arrayfields['p.fk_statut']['checked'])) + { + $projectstatic->statut = $obj->fk_statut; + print ''; + }*/ + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print "\n"; + + //print projectLinesa(); + } + + $i++; +} + +// Show total line +if (isset($totalarray['totaldurationeffectivefield']) || isset($totalarray['totalplannedworkloadfield'])) +{ + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + elseif ($totalarray['totalplannedworkloadfield'] == $i) print ''; + elseif ($totalarray['totaldurationeffectivefield'] == $i) print ''; + else print ''; + } + print ''; +} + +$db->free($resql); + +$parameters=array('sql' => $sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print "
    '; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($syear?$syear:-1,'syear',1, 20, 5); + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $arrayofstatus = array(); + foreach($projectstatic->statuts_short as $key => $val) $arrayofstatus[$key]=$langs->trans($val); + $arrayofstatus['99']=$langs->trans("NotClosed").' ('.$langs->trans('Draft').'+'.$langs->trans('Opened').')'; + print $form->selectarray('search_projectstatus', $arrayofstatus, $search_projectstatus, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100'); + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + print ''; + print ''; +$searchpitco=$form->showFilterAndCheckAddButtons(0); +print $searchpitco; +print '
    '; + print $taskstatic->getNomUrl(1,'withproject'); + if ($taskstatic->hasDelay()) print img_warning("Late"); + print ''; + print $taskstatic->label; + print ''; + print dol_print_date($db->jdate($obj->date_start),'day'); + print ''; + print dol_print_date($db->jdate($obj->date_end),'day'); + print ''; + print $projectstatic->getNomUrl(1, 'task'); + if ($projectstatic->hasDelay()) print img_warning("Late"); + print ''; + print dol_trunc($obj->projecttitle,80); + print ''; + if ($obj->socid) + { + $socstatic->id=$obj->socid; + $socstatic->name=$obj->name; + print $socstatic->getNomUrl(1); + } + else + { + print ' '; + } + print ''; + print $projectstatic->getLibStatut(1); + print ''; + $fullhour=convertSecondToTime($obj->planned_workload,$plannedworkloadoutputformat); + $workingdelay=convertSecondToTime($obj->planned_workload,'all',86400,7); // TODO Replace 86400 and 7 to take account working hours per day and working day per weeks + if ($obj->planned_workload != '') + { + print $fullhour; + // TODO Add delay taking account of working hours per day and working day per week + //if ($workingdelay != $fullhour) print '
    ('.$workingdelay.')'; + } + //else print '--:--'; + print '
    '; + if ($showlineingray) print ''; + else print ''; + if ($obj->duration_effective) print convertSecondToTime($obj->duration_effective,$timespentoutputformat); + else print '--:--'; + if ($showlineingray) print ''; + else print ''; + print ''; + if ($obj->planned_workload || $obj->duration_effective) + { + if ($obj->planned_workload) print round(100 * $obj->duration_effective / $obj->planned_workload,2).' %'; + else print $langs->trans('WorkloadNotDefined'); + } + print ''; + if ($obj->progress != '') + { + print $obj->progress.' %'; + } + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour'); + print ''.$projectstatic->getLibStatut(5).''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
    '.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.convertSecondToTime($totalarray['totalplannedworkload'],$plannedworkloadoutputformat).''.convertSecondToTime($totalarray['totaldurationeffective'],$timespentoutputformat).'
    "; + +print '
    '; llxFooter(); - $db->close(); diff --git a/htdocs/projet/tasks/note.php b/htdocs/projet/tasks/note.php index 5d5cb38dbe5..f443facaabf 100644 --- a/htdocs/projet/tasks/note.php +++ b/htdocs/projet/tasks/note.php @@ -113,53 +113,86 @@ if ($object->id > 0) dol_fiche_head($head, $tab, $langs->trans("Project"),0,($projectstatic->public?'projectpub':'project')); $param=($mode=='mine'?'&mode=mine':''); - - print ''; - - // Ref - print ''; - - // Project - print ''; - - // Company - print ''; - print ''; - + + dol_banner_tab($projectstatic, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; - print $langs->trans("Ref"); - print ''; + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$projectstatic->title; + // Thirdparty + if ($projectstatic->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $projectstatic->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + // Define a complementary filter for search of next/prev ref. if (! $user->rights->projet->all->lire) { - $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,0); - $projectstatic->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $projectstatic->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; } - print $form->showrefnav($projectstatic,'project_ref','',1,'ref','ref','',$param.'&withproject=1'); - print '
    '.$langs->trans("Label").''.$projectstatic->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($projectstatic->thirdparty->id)) print $projectstatic->thirdparty->getNomUrl(1); - else print ' '; - print '
    '; + // Visibility - print ''; - - // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; - + + // Other attributes + $cols = 2; + //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + print '
    '.$langs->trans("Visibility").''; + print '
    '.$langs->trans("Visibility").''; if ($projectstatic->public) print $langs->trans('SharedProject'); else print $langs->trans('PrivateProject'); print '
    '.$langs->trans("Status").''.$projectstatic->getLibStatut(4).'
    '.$langs->trans("DateStart").''; + + // Date start - end + print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; print dol_print_date($projectstatic->date_start,'day'); + $end=dol_print_date($projectstatic->date_end,'day'); + if ($end) print ' - '.$end; print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($projectstatic->date_end,'day'); + + // Budget + print '
    '.$langs->trans("Budget").''; + if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount,'',$langs,1,0,0,$conf->currency); print '
    '; - + + print ''; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($projectstatic->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($projectstatic->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print ''; + + print '
    '; + dol_fiche_end(); } @@ -203,7 +236,7 @@ if ($object->id > 0) print '
    '; - $colwidth=30; + $cssclass='titlefield'; $moreparam=$param; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/projet/tasks/task.php b/htdocs/projet/tasks/task.php index 55b286047d9..cbee3683f73 100644 --- a/htdocs/projet/tasks/task.php +++ b/htdocs/projet/tasks/task.php @@ -82,6 +82,7 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->projet->creer) if (! $error) { $object->fetch($id,$ref); + $object->oldcopy = clone $object; $tmparray=explode('_',$_POST['task_parent']); $task_parent=$tmparray[1]; @@ -92,8 +93,8 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->projet->creer) $object->description = $_POST['description']; $object->fk_task_parent = $task_parent; $object->planned_workload = $planned_workload; - $object->date_start = dol_mktime($_POST['dateohour'],$_POST['dateomin'],0,$_POST['dateomonth'],$_POST['dateoday'],$_POST['dateoyear'],'user'); - $object->date_end = dol_mktime($_POST['dateehour'],$_POST['dateemin'],0,$_POST['dateemonth'],$_POST['dateeday'],$_POST['dateeyear'],'user'); + $object->date_start = dol_mktime($_POST['dateohour'],$_POST['dateomin'],0,$_POST['dateomonth'],$_POST['dateoday'],$_POST['dateoyear']); + $object->date_end = dol_mktime($_POST['dateehour'],$_POST['dateemin'],0,$_POST['dateemonth'],$_POST['dateeday'],$_POST['dateeyear']); $object->progress = $_POST['progress']; // Fill array 'array_options' with data from add form @@ -224,52 +225,86 @@ if ($id > 0 || ! empty($ref)) $param=($mode=='mine'?'&mode=mine':''); - print ''; - - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - - print ''; - - print ''; - print ''; - - // Visibility - print ''; - - // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; - - print '
    '; - print $langs->trans("Ref"); - print ''; - // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) - { - $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,0); - $projectstatic->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; - } - print $form->showrefnav($projectstatic,'project_ref',$linkback,1,'ref','ref','',$param.'&withproject=1'); - print '
    '.$langs->trans("Label").''.$projectstatic->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($projectstatic->thirdparty->id)) print $projectstatic->thirdparty->getNomUrl(1); - else print ' '; - print '
    '.$langs->trans("Visibility").''; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
    '.$langs->trans("Status").''.$projectstatic->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($projectstatic->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($projectstatic->date_end,'day'); - print '
    '; - + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$projectstatic->title; + // Thirdparty + if ($projectstatic->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $projectstatic->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $projectstatic->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($projectstatic, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Visibility + print ''; + + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Visibility").''; + if ($projectstatic->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($projectstatic->date_start,'day'); + $end=dol_print_date($projectstatic->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; + if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount,'',$langs,1,0,0,$conf->currency); + print '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($projectstatic->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($projectstatic->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + dol_fiche_end(); } @@ -528,9 +563,9 @@ if ($id > 0 || ! empty($ref)) print ''; } - print '
    '; - print ''; // ancre - + print '
    '; + print ''; // ancre + /* * Documents generes */ @@ -542,9 +577,11 @@ if ($id > 0 || ! empty($ref)) $var=true; - $somethingshown=$formfile->show_documents('project_task',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf); + print $formfile->showdocuments('project_task',$filename,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf); - print '
    '; + print '
    '; + + print '
    '; } } } diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index 0caf1461e88..276fc1cd722 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -301,69 +301,85 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) $param=($mode=='mine'?'&mode=mine':''); - print ''; - - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - - // Label - print ''; - - // Thirdparty - print ''; - print ''; - - // Visibility - print ''; - - // Statut - print ''; - - // Date start - print ''; - - // Date end - print ''; - - if ((! $id && ! $ref) || ! empty($projectidforalltimes)) // Not a dedicated task - { - // Budget - print ''; - - // Other options - $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$projectstatic,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && ! empty($extrafields_project->attribute_label)) - { - print $projectstatic->showOptionals($extrafields_project); - } - } - - print '
    '; - print $langs->trans("Ref"); - print ''; - // Define a complementary filter for search of next/prev ref. - if (! $user->rights->projet->all->lire) - { - $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,0); - $projectstatic->next_prev_filter=" rowid in (".(count($projectsListId)?join(',',array_keys($projectsListId)):'0').")"; - } - print $form->showrefnav($projectstatic,'project_ref',$linkback,1,'ref','ref','',$param.'&withproject=1'); - print '
    '.$langs->trans("Label").''.$projectstatic->title.'
    '.$langs->trans("ThirdParty").''; - if (! empty($projectstatic->thirdparty->id)) print $projectstatic->thirdparty->getNomUrl(1); - else print ' '; - print '
    '.$langs->trans("Visibility").''; - if ($projectstatic->public) print $langs->trans('SharedProject'); - else print $langs->trans('PrivateProject'); - print '
    '.$langs->trans("Status").''.$projectstatic->getLibStatut(4).'
    '.$langs->trans("DateStart").''; - print dol_print_date($projectstatic->date_start,'day'); - print '
    '.$langs->trans("DateEnd").''; - print dol_print_date($projectstatic->date_end,'day'); - print '
    '.$langs->trans("Budget").''; - if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount,'',$langs,0,0,0,$conf->currency); - print '
    '; + // Project card + + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref='
    '; + // Title + $morehtmlref.=$projectstatic->title; + // Thirdparty + if ($projectstatic->thirdparty->id > 0) + { + $morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $projectstatic->thirdparty->getNomUrl(1, 'project'); + } + $morehtmlref.='
    '; + + // Define a complementary filter for search of next/prev ref. + if (! $user->rights->projet->all->lire) + { + $objectsListId = $object->getProjectsAuthorizedForUser($user,0,0); + $projectstatic->next_prev_filter=" rowid in (".(count($objectsListId)?join(',',array_keys($objectsListId)):'0').")"; + } + + dol_banner_tab($projectstatic, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Visibility + print ''; + + // Date start - end + print ''; + + // Budget + print ''; + + // Other attributes + $cols = 2; + //include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
    '.$langs->trans("Visibility").''; + if ($projectstatic->public) print $langs->trans('SharedProject'); + else print $langs->trans('PrivateProject'); + print '
    '.$langs->trans("DateStart").' - '.$langs->trans("DateEnd").''; + print dol_print_date($projectstatic->date_start,'day'); + $end=dol_print_date($projectstatic->date_end,'day'); + if ($end) print ' - '.$end; + print '
    '.$langs->trans("Budget").''; + if (strcmp($projectstatic->budget_amount, '')) print price($projectstatic->budget_amount,'',$langs,1,0,0,$conf->currency); + print '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + // Description + print ''; + + // Categories + if($conf->categorie->enabled) { + print '"; + } + + print '
    '.$langs->trans("Description").''; + print nl2br($projectstatic->description); + print '
    '.$langs->trans("Categories").''; + print $form->showCategories($projectstatic->id,'project',1); + print "
    '; + + print '
    '; + print '
    '; + print '
    '; + + print '
    '; dol_fiche_end(); @@ -494,7 +510,7 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -504,20 +520,20 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) print ''; // Date - print ''; // Contributor - print ''; // Note - print ''; // Progress declared @@ -566,7 +582,8 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) $arrayfields['t.task_date']=array('label'=>$langs->trans("Date"), 'checked'=>1); if ((empty($id) && empty($ref)) || ! empty($projectidforalltimes)) // Not a dedicated task { - $arrayfields['t.task_ref']=array('label'=>$langs->trans("Task"), 'checked'=>1); + $arrayfields['t.task_ref']=array('label'=>$langs->trans("RefTask"), 'checked'=>1); + $arrayfields['t.task_label']=array('label'=>$langs->trans("LabelTask"), 'checked'=>1); } $arrayfields['author']=array('label'=>$langs->trans("By"), 'checked'=>1); $arrayfields['t.note']=array('label'=>$langs->trans("Note"), 'checked'=>1); @@ -694,6 +711,7 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) if ((empty($id) && empty($ref)) || ! empty($projectidforalltimes)) // Not a dedicated task { if (! empty($arrayfields['t.task_ref']['checked'])) print_liste_field_titre($arrayfields['t.task_ref']['label'],$_SERVER['PHP_SELF'],'pt.ref','',$params,'',$sortfield,$sortorder); + if (! empty($arrayfields['t.task_label']['checked'])) print_liste_field_titre($arrayfields['t.task_label']['label'],$_SERVER['PHP_SELF'],'pt.label','',$params,'',$sortfield,$sortorder); } if (! empty($arrayfields['author']['checked'])) print_liste_field_titre($arrayfields['author']['label'],$_SERVER['PHP_SELF'],'','',$params,'',$sortfield,$sortorder); if (! empty($arrayfields['t.note']['checked'])) print_liste_field_titre($arrayfields['t.note']['label'],$_SERVER['PHP_SELF'],'t.note','',$params,'',$sortfield,$sortorder); @@ -726,9 +744,10 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) if ((empty($id) && empty($ref)) || ! empty($projectidforalltimes)) // Not a dedicated task { if (! empty($arrayfields['t.task_ref']['checked'])) print ''; + if (! empty($arrayfields['t.task_label']['checked'])) print ''; } if (! empty($arrayfields['author']['checked'])) print ''; - if (! empty($arrayfields['t.note']['checked'])) print ''; + if (! empty($arrayfields['t.note']['checked'])) print ''; if (! empty($arrayfields['t.task_duration']['checked'])) print ''; if (! empty($arrayfields['value']['checked'])) print ''; // Extra fields @@ -796,7 +815,7 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) if (! $i) $totalarray['nbfield']++; } - // Task + // Task ref if (! empty($arrayfields['t.task_ref']['checked'])) { if ((empty($id) && empty($ref)) || ! empty($projectidforalltimes)) // Not a dedicated task @@ -811,7 +830,19 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) } } - // User + // Task label + if (! empty($arrayfields['t.task_label']['checked'])) + { + if ((empty($id) && empty($ref)) || ! empty($projectidforalltimes)) // Not a dedicated task + { + print ''; + if (! $i) $totalarray['nbfield']++; + } + } + + // User if (! empty($arrayfields['author']['checked'])) { print ''; print ''; + // Other attributes + $parameters=array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"'); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields,'edit'); + } + + print '
    '.$langs->trans("Date").''.$langs->trans("Date").''.$langs->trans("By").''.$langs->trans("Note").''.$langs->trans("ProgressDeclared").'
    '; + print ''; //$newdate=dol_mktime(12,0,0,$_POST["timemonth"],$_POST["timeday"],$_POST["timeyear"]); $newdate=''; - print $form->select_date($newdate,'time',1,1,2,"timespent_date",1,0,1); + print $form->select_date($newdate, 'time', ($conf->browser->layout == 'phone'?2:1), 1, 2, "timespent_date", 1, 0, 1); print ''; + print ''; print img_object('','user','class="hideonsmartphone"'); $contactsoftask=$object->getListContactId('internal'); if (count($contactsoftask)>0) { $userid=$contactsoftask[0]; - print $form->select_dolusers((GETPOST('userid')?GETPOST('userid'):$userid), 'userid', 0, '', 0, '', $contactsoftask, 0, 0, 0, '', 0, $langs->trans("ResourceNotAssignedToTheTask")); + print $form->select_dolusers((GETPOST('userid')?GETPOST('userid'):$userid), 'userid', 0, '', 0, '', $contactsoftask, 0, 0, 0, '', 0, $langs->trans("ResourceNotAssignedToTheTask"), 'maxwidth200'); } else { @@ -526,8 +542,8 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) print ''; - print ''; + print ''; + print ''; print ''; + print $task_time->label; + print ''; diff --git a/htdocs/public/members/public_list.php b/htdocs/public/members/public_list.php index 4171bbab2e1..404b7085bdb 100644 --- a/htdocs/public/members/public_list.php +++ b/htdocs/public/members/public_list.php @@ -114,7 +114,7 @@ $sql.= " AND statut = 1"; $sql.= " AND public = 1"; $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($conf->liste_limit+1, $offset); -//$sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe, zip, town, d.email, t.libelle as type, d.morphy, d.statut, t.cotisation"; +//$sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe, zip, town, d.email, t.libelle as type, d.morphy, d.statut, t.subscription"; //$sql .= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."adherent_type as t"; //$sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = $statut"; //$sql .= " ORDER BY $sortfield $sortorder " . $db->plimit($conf->liste_limit, $offset); diff --git a/htdocs/public/opensurvey/studs.php b/htdocs/public/opensurvey/studs.php index 834f17b8b2c..6f242a00544 100644 --- a/htdocs/public/opensurvey/studs.php +++ b/htdocs/public/opensurvey/studs.php @@ -41,7 +41,6 @@ if (GETPOST('sondage')) $object=new Opensurveysondage($db); $result=$object->fetch(0,$numsondage); -if ($result <= 0) dol_print_error('','Failed to get survey id '.$numsondage); $nblignes=$object->fetch_lines(); @@ -241,6 +240,16 @@ $arrayofjs=array(); $arrayofcss=array('/opensurvey/css/style.css'); llxHeaderSurvey($object->titre, "", 0, 0, $arrayofjs, $arrayofcss); +if (empty($object->ref)) // For survey, id is a hex string +{ + $langs->load("errors"); + print $langs->trans("ErrorRecordNotFound"); + + llxFooterSurvey(); + + $db->close(); + exit; +} // Define format of choices $toutsujet=explode(",",$object->sujet); diff --git a/htdocs/public/paybox/newpayment.php b/htdocs/public/paybox/newpayment.php index 481fd17f049..1945aa6c8cf 100644 --- a/htdocs/public/paybox/newpayment.php +++ b/htdocs/public/paybox/newpayment.php @@ -649,7 +649,7 @@ if (GETPOST("source") == 'membersubscription' && $valid) $langs->load("members"); require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $member=new Adherent($db); $result=$member->fetch('',$ref); @@ -660,7 +660,7 @@ if (GETPOST("source") == 'membersubscription' && $valid) } else { - $subscription=new Cotisation($db); + $subscription=new Subscription($db); } $amount=$subscription->total_ttc; diff --git a/htdocs/public/paypal/newpayment.php b/htdocs/public/paypal/newpayment.php index dcb43c07170..b5d105d6cf6 100644 --- a/htdocs/public/paypal/newpayment.php +++ b/htdocs/public/paypal/newpayment.php @@ -804,7 +804,7 @@ if (GETPOST("source") == 'membersubscription' && $valid) $langs->load("members"); require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - require_once DOL_DOCUMENT_ROOT.'/adherents/class/cotisation.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; $member=new Adherent($db); $result=$member->fetch('',$ref); @@ -815,7 +815,7 @@ if (GETPOST("source") == 'membersubscription' && $valid) } else { - $subscription=new Cotisation($db); + $subscription=new Subscription($db); } $amount=$subscription->total_ttc; diff --git a/htdocs/public/test/test_arrays.php b/htdocs/public/test/test_arrays.php index 05a291d5c4d..05eaafc3e09 100644 --- a/htdocs/public/test/test_arrays.php +++ b/htdocs/public/test/test_arrays.php @@ -31,7 +31,6 @@ if (empty($usedolheader)) Test page - @@ -39,7 +38,6 @@ if (empty($usedolheader)) - @@ -54,22 +52,8 @@ if (empty($usedolheader)) } else { - $arraycss=array('/includes/jquery/plugins/datatables/media/css/jquery.dataTables.css', - '/includes/jquery/plugins/datatables/extensions/Buttons/css/buttons.dataTables.min.css', - '/includes/jquery/plugins/datatables/extensions/ColReorder/css/colReorder.dataTables.min.css' - ); - $arrayjs=array('/includes/jquery/plugins/datatables/media/js/jquery.dataTables.js', - '/includes/jquery/plugins/datatables/extensions/Buttons/js/dataTables.buttons.js', - '/includes/jquery/plugins/datatables/extensions/Buttons/js/buttons.colVis.min.js', - '/includes/jquery/plugins/datatables/extensions/Buttons/js/buttons.html5.min.js', - '/includes/jquery/plugins/datatables/extensions/Buttons/js/buttons.flash.min.js', - '/includes/jquery/plugins/datatables/extensions/Buttons/js/buttons.print.min.js', - '/includes/jquery/plugins/datatables/extensions/ColReorder/js/dataTables.colReorder.min.js', - '/includes/jszip/jszip.min.js', - '/includes/pdfmake/pdfmake.min.js', - '/includes/pdfmake/vfs_fonts.js' - ); - + $arraycss=array(); + $arrayjs=array(); llxHeader('','','','',0,0,$arrayjs,$arraycss); } @@ -79,14 +63,14 @@ else //--------- ?> -

    +

    This page is a sample of page using tables. It is designed to make test with
    - css (add parameter &theme=newtheme to test another theme or edit css of current theme)
    - jmobile (add parameter ">dol_use_jmobile=1&dol_optimize_smallscreen=1 and switch to small screen < 960 to enable view with jmobile)
    - no javascript / usage for bind people (add parameter ">nojs=1 to force disable javascript)
    - dataTables
    - tablednd
    -

    + diff --git a/htdocs/public/websites/index.php b/htdocs/public/websites/index.php index 8c83a1daebc..44789409058 100644 --- a/htdocs/public/websites/index.php +++ b/htdocs/public/websites/index.php @@ -144,6 +144,7 @@ if (! file_exists($original_file_osencoded)) // Output page content +define('USEDOLIBARRSERVER', 1); print "\n".''."\n"; include_once $original_file_osencoded; diff --git a/htdocs/resource/add.php b/htdocs/resource/add.php index 7608e1b6cf3..7c60bf8091d 100644 --- a/htdocs/resource/add.php +++ b/htdocs/resource/add.php @@ -27,6 +27,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load traductions files required by page $langs->load("resource"); @@ -60,6 +61,11 @@ if ($user->societe_id > 0) $object = new DolResource($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + if ($action == 'confirm_add_resource') { if (! $cancel) @@ -84,6 +90,12 @@ if ($action == 'confirm_add_resource') $object->description=$description; $object->fk_code_type_resource=$fk_code_type_resource; + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) { + $error ++; + } + $result=$object->create($user); if ($result > 0) { @@ -162,6 +174,15 @@ if (! $action) print '
    '; dol_fiche_end(''); diff --git a/htdocs/resource/card.php b/htdocs/resource/card.php index 95f5cf0574b..d2ec14efd71 100644 --- a/htdocs/resource/card.php +++ b/htdocs/resource/card.php @@ -29,9 +29,10 @@ if (! $res) $res=@include("../../main.inc.php"); // For "custom" directory if (! $res) die("Include of main fails"); require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; -require_once 'class/dolresource.class.php'; -require_once 'class/html.formresource.class.php'; +require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php'; +require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/resource.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; // Load traductions files requiredby by page $langs->load("resource"); @@ -58,6 +59,11 @@ if( ! $user->rights->resource->read) $object = new Dolresource($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + $hookmanager->initHooks(array('resource_card','globalcard')); $parameters=array('resource_id'=>$id); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks @@ -88,6 +94,12 @@ if (empty($reshook)) $object->description = $description; $object->fk_code_type_resource = $fk_code_type_resource; + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) { + $error ++; + } + $result=$object->update($user); if ($result > 0) { @@ -126,7 +138,7 @@ if (empty($reshook)) Header('Location: '.DOL_URL_ROOT.'/resource/list.php'); exit; } - else + else { setEventMessages($object->error, $object->errors, 'errors'); } @@ -188,6 +200,14 @@ if ( $object->fetch($id) > 0 ) print ''; print '
    '; dol_fiche_end(); @@ -235,6 +255,15 @@ if ( $object->fetch($id) > 0 ) print ''; print $object->description; print ''; + + // Other attributes + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields); + } + print ''; print ''; diff --git a/htdocs/resource/class/dolresource.class.php b/htdocs/resource/class/dolresource.class.php index 633be01aa1b..2cf93493739 100644 --- a/htdocs/resource/class/dolresource.class.php +++ b/htdocs/resource/class/dolresource.class.php @@ -63,7 +63,7 @@ class Dolresource extends CommonObject */ function create($user, $notrigger=0) { - global $conf, $langs; + global $conf, $langs, $hookmanager; $error=0; // Clean parameters @@ -107,14 +107,40 @@ class Dolresource extends CommonObject if (! $error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); + } + if (! $error) + { + $action='create'; + + // Actions on extra fields (by external module or standard code) + // TODO le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('actioncommdao')); + $parameters=array('actcomm'=>$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) + { if (! $notrigger) { //// Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('RESOURCE_CREATE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers('RESOURCE_CREATE',$this,$user,$langs,$conf); + if ($result < 0) { $error++; $this->errors=$interface->errors; } //// End call triggers } } @@ -177,6 +203,13 @@ class Dolresource extends CommonObject $this->note_private = $obj->note_private; $this->type_label = $obj->type_label; + // Retreive all extrafield for thirdparty + // fetch optionals attributes and labels + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); + } $this->db->free($resql); @@ -199,7 +232,7 @@ class Dolresource extends CommonObject */ function update($user=null, $notrigger=0) { - global $conf, $langs; + global $conf, $langs, $hookmanager; $error=0; // Clean parameters @@ -229,13 +262,35 @@ class Dolresource extends CommonObject // 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; } + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers('RESOURCE_MODIFY',$this,$user,$langs,$conf); + if ($result < 0) { $error++; $this->errors=$interface->errors; } //// End call triggers } } + if (! $error) + { + $action='update'; + + // Actions on extra fields (by external module or standard code) + // TODO le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('actioncommdao')); + $parameters=array('actcomm'=>$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++; + } // Commit or rollback if ($error) @@ -294,10 +349,12 @@ class Dolresource extends CommonObject $this->mandatory = $obj->mandatory; $this->fk_user_create = $obj->fk_user_create; - if($obj->resource_id && $obj->resource_type) + if($obj->resource_id && $obj->resource_type) { $this->objresource = fetchObjectByElement($obj->resource_id,$obj->resource_type); - if($obj->element_id && $obj->element_type) + } + if($obj->element_id && $obj->element_type) { $this->objelement = fetchObjectByElement($obj->element_id,$obj->element_type); + } } $this->db->free($resql); @@ -324,36 +381,57 @@ class Dolresource extends CommonObject $error=0; - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('RESOURCE_DELETE',$user); - if ($result < 0) return -1; - // End call triggers - } + $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql.= " WHERE rowid =".$rowid; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); + dol_syslog(get_class($this), LOG_DEBUG); if ($this->db->query($sql)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; $sql.= " WHERE element_type='resource' AND resource_id =".$this->db->escape($rowid); dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if ($this->db->query($sql)) + $resql=$this->db->query($sql); + if (!$resql) { - return 1; - } - else { - $this->error=$this->db->lasterror(); - return -1; + $this->error=$this->db->lasterror(); + $error++; } } else { $this->error=$this->db->lasterror(); - return -1; + $error++; + } + + // Removed extrafields + if (! $error) { + $result=$this->deleteExtraFields(); + if ($result < 0) + { + $error++; + dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); + } + } + + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('RESOURCE_DELETE',$user); + if ($result < 0) $error++; + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -1; } } @@ -377,9 +455,20 @@ class Dolresource extends CommonObject $sql.= " t.description,"; $sql.= " t.fk_code_type_resource,"; $sql.= " t.tms,"; + + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + if (is_array($extralabels) && count($extralabels)>0) { + foreach($extralabels as $label=>$code) { + $sql.= " ef.".$code." as extra_".$code.","; + } + } + $sql.= " ty.label as type_label"; $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_resource as ty ON ty.code=t.fk_code_type_resource"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$this->table_element."_extrafields as ef ON ef.fk_object=t.rowid"; $sql.= " WHERE t.entity IN (".getEntity('resource',1).")"; //Manage filter @@ -388,6 +477,9 @@ class Dolresource extends CommonObject if (strpos($key,'date')) { $sql.= ' AND '.$key.' = \''.$this->db->idate($value).'\''; } + elseif (strpos($key,'ef.')!==false){ + $sql.= $value; + } else { $sql.= ' AND '.$key.' LIKE \'%'.$value.'%\''; } @@ -419,6 +511,11 @@ class Dolresource extends CommonObject $line->fk_code_type_resource = $obj->fk_code_type_resource; $line->type_label = $obj->type_label; + // Retreive all extrafield for thirdparty + // fetch optionals attributes and labels + + $line->fetch_optionals($line->id,$extralabels); + $this->lines[] = $line; } $this->db->free($resql); diff --git a/htdocs/resource/element_resource.php b/htdocs/resource/element_resource.php index f8e9e052995..27451b07973 100644 --- a/htdocs/resource/element_resource.php +++ b/htdocs/resource/element_resource.php @@ -51,7 +51,7 @@ $hookmanager->initHooks(array('element_resource')); $object->available_resources = array('dolresource'); // Get parameters -$id = GETPOST('id','int'); +$id = GETPOST('id','int'); $action = GETPOST('action','alpha'); $mode = GETPOST('mode','alpha'); $lineid = GETPOST('lineid','int'); @@ -196,24 +196,105 @@ else dol_fiche_head($head, 'resources', $langs->trans("Action"),0,'action'); + $linkback =img_picto($langs->trans("BackToList"),'object_list','class="hideonsmartphone pictoactionview"'); + $linkback.= ''.$langs->trans("BackToList").''; + + // Link to other agenda views + $out=''; + $out.=img_picto($langs->trans("ViewPerUser"),'object_calendarperuser','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewPerUser").''; + $out.='
    '; + $out.=img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewCal").''; + $out.=img_picto($langs->trans("ViewWeek"),'object_calendarweek','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewWeek").''; + $out.=img_picto($langs->trans("ViewDay"),'object_calendarday','class="hideonsmartphone pictoactionview"'); + $out.=''.$langs->trans("ViewDay").''; + + $linkback.=$out; + + dol_banner_tab($act, 'element_id', $linkback, ($user->societe_id?0:1), 'id', 'ref', '', "&element=".$element); + + print '
    '; + + // Ref + /*print ''.$langs->trans("Ref").''; + print $form->showrefnav($act, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); + print '';*/ + // Affichage fiche action en mode visu print ''; - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - // Type if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) { - print ''; + print ''; } - // Title - print ''; + // Full day event + print ''; + + // Date start + print ''; + print ''; + + // Date end + print ''; + + // Status + /*print '';*/ + + // Location + if (empty($conf->global->AGENDA_DISABLE_LOCATION)) + { + print ''; + } + + // Assigned to + print ''; + print '
    '.$langs->trans("Ref").''; - print $form->showrefnav($act, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); - print '
    '.$langs->trans("Type").''.$act->type.'
    '.$langs->trans("Type").''.$act->type.'
    '.$langs->trans("Title").''.$act->label.'
    '.$langs->trans("EventOnFullDay").''.yn($act->fulldayevent, 3).'
    '.$langs->trans("DateActionStart").''; + if (! $act->fulldayevent) print dol_print_date($act->datep,'dayhour'); + else print dol_print_date($act->datep,'day'); + if ($act->percentage == 0 && $act->datep && $act->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); + print '
    '.$langs->trans("DateActionEnd").''; + if (! $act->fulldayevent) print dol_print_date($act->datef,'dayhour'); + else print dol_print_date($act->datef,'day'); + if ($act->percentage > 0 && $act->percentage < 100 && $act->datef && $act->datef < ($now- $delay_warning)) print img_warning($langs->trans("Late")); + print '
    '.$langs->trans("Status").' / '.$langs->trans("Percentage").''; + print $act->getLibStatut(4); + print '
    '.$langs->trans("Location").''.$act->location.'
    '.$langs->trans("ActionAffectedTo").''; + $listofuserid=array(); + if (empty($donotclearsession)) + { + if ($act->userownerid > 0) $listofuserid[$act->userownerid]=array('id'=>$act->userownerid,'transparency'=>$act->transparency); // Owner first + if (! empty($act->userassigned)) // Now concat assigned users + { + // Restore array with key with same value than param 'id' + $tmplist1=$act->userassigned; $tmplist2=array(); + foreach($tmplist1 as $key => $val) + { + if ($val['id'] && $val['id'] != $act->userownerid) $listofuserid[$val['id']]=$val; + } + } + $_SESSION['assignedtouser']=json_encode($listofuserid); + } + else + { + if (!empty($_SESSION['assignedtouser'])) + { + $listofuserid=json_decode($_SESSION['assignedtouser'], true); + } + } + print '
    '; + print $form->select_dolusers_forevent('view', 'assignedtouser', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + print '
    '; + if (in_array($user->id,array_keys($listofuserid))) + { + print '
    '; + print $langs->trans("MyAvailability").': '.(($act->userassigned[$user->id]['transparency'] > 0)?$langs->trans("Busy"):$langs->trans("Available")); // We show nothing if event is assigned to nobody + print '
    '; + } + print '
    '; dol_fiche_end(); @@ -225,38 +306,37 @@ else */ if ($element_id && $element == 'societe') { - $socstatic = fetchObjectByElement($element_id,$element); - if (is_object($socstatic)) - { - $savobject = $object; - - $object = $socstatic; - - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - $head = societe_prepare_head($socstatic); - - dol_fiche_head($head, 'resources', $langs->trans("ThirdParty"),0,'company'); - - dol_banner_tab($socstatic, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); - + $socstatic = fetchObjectByElement($element_id, $element); + if (is_object($socstatic)) { + $savobject = $object; + + $object = $socstatic; + + require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; + $head = societe_prepare_head($socstatic); + + dol_fiche_head($head, 'resources', $langs->trans("ThirdParty"), 0, 'company'); + + dol_banner_tab($socstatic, 'socid', '', ($user->societe_id ? 0 : 1), 'rowid', 'nom'); + print '
    '; - - print '
    '; + + print '
    '; print ''; - + // Alias name (commercial, trademark or alias name) - print '"; - - print '
    '.$langs->trans('AliasNames').''; + print '
    ' . $langs->trans('AliasNames') . ''; print $socstatic->name_alias; print "
    '; - - print '
    '; - - dol_fiche_end(); - - $object = $savobject; - } + + print ''; + + print '
    '; + + dol_fiche_end(); + + $object = $savobject; + } } /* @@ -303,13 +383,13 @@ else if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - //print load_fiche_titre($langs->trans('ResourcesLinkedToElement'),'',''); - - + //print load_fiche_titre($langs->trans('ResourcesLinkedToElement'),'',''); + print '
    '; + // Show list of resource links - foreach ($object->available_resources as $modresources => $resources) - { + foreach ($object->available_resources as $modresources => $resources) + { $resources=(array) $resources; // To be sure $resources is an array foreach($resources as $resource_obj) { @@ -327,13 +407,12 @@ else // If we have a specific template we use it if(file_exists(dol_buildpath($path.'/core/tpl/resource_'.$element_prop['element'].'_add.tpl.php'))) { - $res=include dol_buildpath($path.'/core/tpl/resource_'.$element_prop['element'].'_add.tpl.php'); + $res=include dol_buildpath($path.'/core/tpl/resource_'.$element_prop['element'].'_add.tpl.php'); } else { - $res=include DOL_DOCUMENT_ROOT . '/core/tpl/resource_add.tpl.php'; + $res=include DOL_DOCUMENT_ROOT . '/core/tpl/resource_add.tpl.php'; } - //var_dump($element_id); if ($mode != 'add' || $resource_obj != $resource_type) { diff --git a/htdocs/resource/list.php b/htdocs/resource/list.php index 90eed125284..3b6338f0fce 100644 --- a/htdocs/resource/list.php +++ b/htdocs/resource/list.php @@ -41,28 +41,103 @@ $resource_id = GETPOST('resource_id','int'); $sortorder = GETPOST('sortorder','alpha'); $sortfield = GETPOST('sortfield','alpha'); -$page = GETPOST('page','int'); + +// Initialize context for list +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'resourcelist'; $object = new Dolresource($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); +$search_ref=GETPOST("search_ref"); +$search_type=GETPOST("search_type"); + +$filter=array(); + +if ($search_ref != ''){ + $param.='&search_ref='.$search_ref; + $filter['t.ref']=$search_ref; +} +if ($search_type != ''){ + $param.='&search_type='.$search_type; + $filter['ty.label']=$search_type; +} +if ($search_label != '') $param.='&search_label='.$search_label; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $typ=$extrafields->attribute_type[$tmpkey]; + if ($val != '') { + $param.='&search_options_'.$tmpkey.'='.urlencode($val); + } + $mode=0; + if (in_array($typ, array('int','double'))) $mode=1; // Search on a numeric + if ($val && ( ($crit != '' && ! in_array($typ, array('select'))) || ! empty($crit))) + { + $filter['ef.'.$tmpkey]=natural_search('ef.'.$tmpkey, $crit, $mode); + } +} +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + + $hookmanager->initHooks(array('resource_list')); if (empty($sortorder)) $sortorder="ASC"; if (empty($sortfield)) $sortfield="t.rowid"; if (empty($arch)) $arch = 0; +$page = GETPOST('page','int'); if ($page == -1) { - $page = 0 ; + $page = 0 ; } - -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; -$offset = $limit * $page ; +$page = is_numeric($page) ? $page : 0; +$page = $page == -1 ? 0 : $page; +if (! $sortfield) $sortfield="p.ref"; +if (! $sortorder) $sortorder="ASC"; +$offset = $conf->liste_limit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; -if( ! $user->rights->resource->read) +if( ! $user->rights->resource->read) { accessforbidden(); +} +$arrayfields = array( + 't.ref' => array( + 'label' => $langs->trans("Ref"), + 'checked' => 1 + ), + 'ty.label' => array( + 'label' => $langs->trans("ResourceType"), + 'checked' => 1 + ), +); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { + foreach ( $extrafields->attribute_label as $key => $val ) { + $arrayfields["ef." . $key] = array( + 'label' => $extrafields->attribute_label[$key], + 'checked' => $extrafields->attribute_list[$key], + 'position' => $extrafields->attribute_pos[$key], + 'enabled' => $extrafields->attribute_perms[$key] + ); + } +} +include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + +// Do we click on purge search criteria ? +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $search_label=""; + $search_array_options=array(); + $filter=array(); +} /* * Action @@ -73,7 +148,6 @@ $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - /* * View */ @@ -86,11 +160,11 @@ llxHeader('',$pagetitle,''); // Confirmation suppression resource line if ($action == 'delete_resource') { - print $form->formconfirm($_SERVER['PHP_SELF']."?element=".$element."&element_id=".$element_id."&lineid=".$lineid,$langs->trans("DeleteResource"),$langs->trans("ConfirmDeleteResourceElement"),"confirm_delete_resource",'','',1); + print $form->formconfirm($_SERVER['PHP_SELF']."?element=".$element."&element_id=".$element_id."&lineid=".$lineid,$langs->trans("DeleteResource"),$langs->trans("ConfirmDeleteResourceElement"),"confirm_delete_resource",'','',1); } // Load object list -$ret = $object->fetch_all($sortorder, $sortfield, $limit, $offset); +$ret = $object->fetch_all($sortorder, $sortfield, $limit, $offset, $filter); if($ret == -1) { dol_print_error($db,$object->error); exit; @@ -100,11 +174,78 @@ if($ret == -1) { $var=true; +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); + +print '
    '; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + print ''."\n"; print ''; -print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'t.ref','',$param,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans('ResourceType'),$_SERVER['PHP_SELF'],'ty.code','',$param,'',$sortfield,$sortorder); -print_liste_field_titre('',"","","","",'width="60" align="center"',"",""); +if (! empty($arrayfields['t.ref']['checked'])) print_liste_field_titre($arrayfields['t.ref']['label'],$_SERVER["PHP_SELF"],"t.ref","",$param,"",$sortfield,$sortorder); +if (! empty($arrayfields['ty.label']['checked'])) print_liste_field_titre($arrayfields['ty.label']['label'],$_SERVER["PHP_SELF"],"t.code","",$param,"",$sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); +print "\n"; + +print ''; +if (! empty($arrayfields['t.ref']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['ty.label']['checked'])) +{ + print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Action column +print ''; print "\n"; if ($ret) @@ -118,13 +259,37 @@ if ($ret) print ''; - print ''; + if (! empty($arrayfields['t.ref']['checked'])) + { + print ''; + } - print ''; + if (! empty($arrayfields['ty.label']['checked'])) + { + print ''; + } + // Extra fields + if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) + { + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $resource->array_options[$tmpkey], '', 1); + print ''; + } + } + if (! $i) $totalarray['nbfield']++; + } print '
    '; + print ''; + print ''; + print ''; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; +$searchpitco=$form->showFilterAndCheckAddButtons(0); +print $searchpitco; +print '
    '; - print $resource->getNomUrl(5); - print ''; + print $resource->getNomUrl(5); + print ''; - print $resource->type_label; - print ''; + print $resource->type_label; + print ''; print ''; @@ -140,6 +305,7 @@ if ($ret) } print '
    '; + print "
    \n"; } else { diff --git a/htdocs/societe/agenda.php b/htdocs/societe/agenda.php index 4547c7d75da..f4c8f5c6dbc 100644 --- a/htdocs/societe/agenda.php +++ b/htdocs/societe/agenda.php @@ -34,11 +34,33 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->load("companies"); +if (GETPOST('actioncode','array')) +{ + $actioncode=GETPOST('actioncode','array',3); + if (! count($actioncode)) $actioncode='0'; +} +else +{ + $actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE)); +} +$search_agenda_label=GETPOST('search_agenda_label'); + // Security check $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'societe', $socid, '&societe'); +$limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if ($page == -1) { $page = 0; } +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) $sortfield='a.datep, a.id'; +if (! $sortorder) $sortorder='DESC'; + // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('agendathirdparty')); @@ -51,6 +73,13 @@ $parameters=array('id'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +{ + $actioncode=''; + $search_agenda_label=''; +} + /* @@ -81,42 +110,15 @@ if ($socid) dol_fiche_head($head, 'agenda', $langs->trans("ThirdParty"),0,'company'); - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; print '
    '; - print ''; - - if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { - print ''; - } - - if ($object->client) - { - print ''; - } - - if ($object->fournisseur) - { - print ''; - } - - print '
    '.$langs->trans('Prefix').''.$object->prefix_comm.'
    '; - print $langs->trans('CustomerCode').''; - print $object->code_client; - if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; - print '
    '; - print $langs->trans('SupplierCode').''; - print $object->code_fournisseur; - if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; - print '
    '; - - - print '
    '; - - $object->info($socid); + + $object->info($socid); print dol_print_object_info($object, 1); print '
    '; @@ -125,10 +127,8 @@ if ($socid) - /* - * Barre d'action - */ - + // Actions buttons + $objthirdparty=$object; $objcon=new stdClass(); @@ -144,6 +144,7 @@ if ($socid) //$out.=""; } + print '
    '; if (! empty($conf->agenda->enabled)) @@ -162,15 +163,25 @@ if ($socid) if (! empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read) )) { - print '
    '; - - print load_fiche_titre($langs->trans("ActionsOnCompany"),'',''); - + $param='&socid='.$socid; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + + + print load_fiche_titre($langs->trans("ActionsOnCompany"),'',''); + // List of todo actions - show_actions_todo($conf,$langs,$db,$object,null,0,1); - + //show_actions_todo($conf,$langs,$db,$object,null,0,$actioncode); + // List of done actions - show_actions_done($conf,$langs,$db,$object); + //show_actions_done($conf,$langs,$db,$object,null,0,$actioncode); + + // List of all actions + $filters=array(); + $filters['search_agenda_label']=$search_agenda_label; + + // TODO Replace this with smae code then into listactions.php + show_actions_done($conf,$langs,$db,$object,null,0,$actioncode, '', $filters, $sortfield, $sortorder); } } diff --git a/htdocs/societe/canvas/actions_card_common.class.php b/htdocs/societe/canvas/actions_card_common.class.php index 95d5b33e162..689771ad223 100644 --- a/htdocs/societe/canvas/actions_card_common.class.php +++ b/htdocs/societe/canvas/actions_card_common.class.php @@ -260,7 +260,6 @@ abstract class ActionsCardCommon return; } } - exit; } else { diff --git a/htdocs/societe/canvas/company/tpl/card_view.tpl.php b/htdocs/societe/canvas/company/tpl/card_view.tpl.php index 26c1e77742f..fa58b02413c 100644 --- a/htdocs/societe/canvas/company/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/company/tpl/card_view.tpl.php @@ -260,7 +260,7 @@ $urlsource=$_SERVER["PHP_SELF"]."?socid=".$socid; $genallowed=$user->rights->societe->creer; $delallowed=$user->rights->societe->supprimer; -$somethingshown=$formfile->show_documents('company',$socid,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,28,0,'',0,'',$objcanvas->control->object->default_lang); +print $formfile->showdocuments('company',$socid,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,28,0,'',0,'',$objcanvas->control->object->default_lang); ?> diff --git a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php index bc83f2955da..7249c752c1c 100644 --- a/htdocs/societe/canvas/individual/tpl/card_view.tpl.php +++ b/htdocs/societe/canvas/individual/tpl/card_view.tpl.php @@ -204,7 +204,7 @@ $urlsource=$_SERVER["PHP_SELF"]."?socid=".$socid; $genallowed=$user->rights->societe->creer; $delallowed=$user->rights->societe->supprimer; -$somethingshown=$formfile->show_documents('company',$socid,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,28,0,'',0,'',$objcanvas->control->object->default_lang); +print $formfile->showdocuments('company',$socid,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,28,0,'',0,'',$objcanvas->control->object->default_lang); ?> diff --git a/htdocs/societe/checkvat/checkVatPopup.php b/htdocs/societe/checkvat/checkVatPopup.php index 702dbb0a08a..4d3daf138b3 100644 --- a/htdocs/societe/checkvat/checkVatPopup.php +++ b/htdocs/societe/checkvat/checkVatPopup.php @@ -120,7 +120,7 @@ else { if ($result['requestDate']) print $langs->trans("Date").': '.$result['requestDate'].'
    '; print $langs->trans("VATIntraSyntaxIsValid").': '.$langs->trans("No").' (Might be a non europeen VAT)
    '; - print $langs->trans("VATIntraValueIsValid").': '.$langs->trans("No").' (Might be a non europeen VAT)
    '; + print $langs->trans("ValueIsValid").': '.$langs->trans("No").' (Might be a non europeen VAT)
    '; //$messagetoshow=$soapclient->response; } else @@ -128,7 +128,7 @@ else // Syntaxe ok if ($result['requestDate']) print $langs->trans("Date").': '.$result['requestDate'].'
    '; print $langs->trans("VATIntraSyntaxIsValid").': '.$langs->trans("Yes").'
    '; - print $langs->trans("VATIntraValueIsValid").': '; + print $langs->trans("ValueIsValid").': '; if (preg_match('/MS_UNAVAILABLE/i',$result['faultstring'])) { print ''.$langs->trans("ErrorVATCheckMS_UNAVAILABLE",$countryCode).'
    '; diff --git a/htdocs/societe/class/api_contacts.class.php b/htdocs/societe/class/api_contacts.class.php index cd0dd6ae38f..11cd1fee919 100644 --- a/htdocs/societe/class/api_contacts.class.php +++ b/htdocs/societe/class/api_contacts.class.php @@ -84,16 +84,17 @@ class Contacts extends DolibarrApi * * Get a list of contacts * - * @param int $socid ID of thirdparty to filter list * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @return array Array of contact objects + * @param int $socid ID of thirdparty to filter list + * @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 contact objects * * @throws RestException */ - function index($socid = 0, $sortfield = "c.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid = 0, $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -107,37 +108,36 @@ class Contacts extends DolibarrApi if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; - $sql = "SELECT c.rowid"; - $sql.= " FROM " . MAIN_DB_PREFIX . "socpeople as c"; + $sql = "SELECT t.rowid"; + $sql.= " FROM " . MAIN_DB_PREFIX . "socpeople as t"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { // We need this table joined to the select in order to filter by sale $sql.= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; } - $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON c.fk_soc = s.rowid"; - $sql.= ' WHERE c.entity IN (' . getEntity('contact', 1) . ')'; - if ($socid) - $sql.= " AND c.fk_soc = " . $socid; + $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON t.fk_soc = s.rowid"; + $sql.= ' WHERE t.entity IN (' . getEntity('contact', 1) . ')'; + if ($socid) $sql.= " AND t.fk_soc = " . $socid; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) - $sql.= " AND c.fk_soc = sc.fk_soc"; + $sql.= " AND t.fk_soc = sc.fk_soc"; if ($search_sale > 0) $sql.= " AND s.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; } - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - } - + // 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) @@ -154,7 +154,7 @@ class Contacts extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $contact_static = new Contact($db); @@ -321,7 +321,7 @@ class Contacts extends DolibarrApi /** * Validate fields before create or update object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * @throws RestException */ diff --git a/htdocs/societe/class/api_deprecated_contact.class.php b/htdocs/societe/class/api_deprecated_contact.class.php index 2a6a4b948b8..56ef1eec19a 100644 --- a/htdocs/societe/class/api_deprecated_contact.class.php +++ b/htdocs/societe/class/api_deprecated_contact.class.php @@ -167,7 +167,7 @@ class ContactApi extends DolibarrApi { $i = 0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $contact_static = new Contact($db); @@ -278,7 +278,7 @@ class ContactApi extends DolibarrApi /** * Validate fields before create or update object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * @throws RestException */ diff --git a/htdocs/societe/class/api_deprecated_thirdparty.class.php b/htdocs/societe/class/api_deprecated_thirdparty.class.php index 3e2f070b9de..3179cb697ce 100644 --- a/htdocs/societe/class/api_deprecated_thirdparty.class.php +++ b/htdocs/societe/class/api_deprecated_thirdparty.class.php @@ -213,7 +213,7 @@ class ThirdpartyApi extends DolibarrApi { $i = 0; $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $soc_static = new Societe($db); diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index 12fca598a81..de21e4fbbe0 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -87,17 +87,17 @@ class Thirdparties extends DolibarrApi * * Get a list of thirdparties * - * @param int $mode Set to 1 to show only customers - * Set to 2 to show only prospects - * Set to 3 to show only those are not customer neither prospect - * @param string $email Search by email filter * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @return array Array of thirdparty objects + * @param int $mode Set to 1 to show only customers + * Set to 2 to show only prospects + * Set to 3 to show only those are not customer neither prospect + * @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 thirdparty objects */ - function index($mode=0, $email=NULL, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $mode=0, $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -107,35 +107,37 @@ class Thirdparties extends DolibarrApi // If the internal user must only see his customers, force searching by him if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; - $sql = "SELECT s.rowid"; + $sql = "SELECT t.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."societe as s"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as t"; 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.= ", ".MAIN_DB_PREFIX."c_stcomm as st"; - $sql.= " WHERE s.fk_stcomm = st.id"; - if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; - if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; - if ($mode == 3) $sql.= " AND s.client IN (0)"; - $sql.= ' AND s.entity IN ('.getEntity('societe', 1).')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; - if ($email != NULL) $sql.= " AND s.email = \"".$email."\""; - if ($socid) $sql.= " AND s.rowid = ".$socid; - if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - + $sql.= " WHERE t.fk_stcomm = st.id"; + if ($mode == 1) $sql.= " AND t.client IN (1, 3)"; + if ($mode == 2) $sql.= " AND t.client IN (2, 3)"; + if ($mode == 3) $sql.= " AND t.client IN (0)"; + $sql.= ' AND t.entity IN ('.getEntity('societe', 1).')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; + //if ($email != NULL) $sql.= " AND s.email = \"".$email."\""; + if ($socid) $sql.= " AND t.rowid = ".$socid; + 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; } - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + // Add sql filters + if ($sqlfilters) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); + 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) { @@ -152,7 +154,7 @@ class Thirdparties extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < $num) + while ($i < min($num, ($limit <= 0 ? $num : $limit))) { $obj = $db->fetch_object($result); $soc_static = new Societe($db); diff --git a/htdocs/societe/class/companybankaccount.class.php b/htdocs/societe/class/companybankaccount.class.php index 61629e63838..68749713788 100644 --- a/htdocs/societe/class/companybankaccount.class.php +++ b/htdocs/societe/class/companybankaccount.class.php @@ -37,6 +37,8 @@ class CompanyBankAccount extends Account var $default_rib; var $frstrecur; + var $rum; + var $date_rum; var $datec; var $datem; @@ -110,6 +112,9 @@ class CompanyBankAccount extends Account { $this->create(); } + + if (dol_strlen($this->domiciliation) > 255) $this->domiciliation = dol_trunc($this->domiciliation, 254, 'right', 'UTF-8', 1); + if (dol_strlen($this->owner_address) > 255) $this->owner_address = dol_trunc($this->owner_address, 254, 'right', 'UTF-8', 1); $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib SET"; $sql.= " bank = '" .$this->db->escape($this->bank)."'"; @@ -126,6 +131,8 @@ class CompanyBankAccount extends Account if ($conf->prelevement->enabled) { $sql.= ",frstrecur = '".$this->db->escape($this->frstrecur)."'"; + $sql.= ",rum = '".$this->db->escape($this->rum)."'"; + $sql.= ",date_rum = ".($this->date_rum ? "'".$this->db->idate($this->date_rum)."'" : "null"); } if (trim($this->label) != '') $sql.= ",label = '".$this->db->escape($this->label)."'"; @@ -169,6 +176,8 @@ class CompanyBankAccount extends Account { $obj = $this->db->fetch_object($resql); + $this->ref = $obj->fk_soc.'-'.$obj->label; // Generate an artificial ref + $this->id = $obj->rowid; $this->socid = $obj->fk_soc; $this->bank = $obj->bank; @@ -299,5 +308,39 @@ class CompanyBankAccount extends Account return -1; } } + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + $this->specimen = 1; + $this->ref = 'CBA'; + $this->label = 'CustomerCorp Bank account'; + $this->bank = 'CustomerCorp Bank'; + $this->courant = Account::TYPE_CURRENT; + $this->clos = Account::STATUS_OPEN; + $this->code_banque = '123'; + $this->code_guichet = '456'; + $this->number = 'CUST12345'; + $this->cle_rib = 50; + $this->bic = 'CC12'; + $this->iban = 'FR999999999'; + $this->domiciliation = 'Bank address of customer corp'; + $this->proprio = 'Owner'; + $this->owner_address = 'Owner address'; + $this->country_id = 1; + + $this->rum = 'UMR-CU1212-0007-5-1475405262'; + $this->date_rum =dol_now() - 10000; + $this->frstrecur = 'FRST'; + + $this->socid = 0; + } + } diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 9be1124210f..c89be8f72d3 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1828,17 +1828,17 @@ class Societe extends CommonObject * @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only) * @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project') * @param int $maxlen Max length of name - * @param integer $notooltip 1=Disable tooltip + * @param int $notooltip 1=Disable tooltip * @return string String with URL */ function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0) { - global $conf,$langs, $hookmanager; + global $conf, $langs, $hookmanager; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips $name=$this->name?$this->name:$this->nom; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; - if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) { if (($this->client) && (! empty ( $this->code_client ))) { @@ -1853,46 +1853,46 @@ class Societe extends CommonObject if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')'; $result=''; $label=''; - $link=''; $linkend=''; + $linkstart=''; $linkend=''; $label.= '
    '; if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier') { $label.= '' . $langs->trans("ShowCustomer") . ''; - $link = 'global->SOCIETE_DISABLE_PROSPECTS)) { $label.= '' . $langs->trans("ShowProspect") . ''; - $link = 'trans("ShowSupplier") . ''; - $link = 'trans("ShowAgenda") . ''; - $link = 'trans("ShowProject") . ''; - $link = 'trans("ShowMargin") . ''; - $link = 'trans("ShowCompany") . ''; - $link = '' . $langs->trans('CustomerCode') . ': '. $this->code_client; if (! empty($this->code_fournisseur) && $this->fournisseur) $label.= '
    ' . $langs->trans('SupplierCode') . ': '. $this->code_fournisseur; - + if (! empty($conf->accounting->enabled) && $this->client) + $label.= '
    ' . $langs->trans('CustomerAccountancyCode') . ': '. $this->code_compta_client; + if (! empty($conf->accounting->enabled) && $this->fournisseur) + $label.= '
    ' . $langs->trans('SupplierAccountancyCode') . ': '. $this->code_compta_fournisseur; + if (! empty($this->logo)) { $label.= '
    '; @@ -1915,7 +1919,8 @@ class Societe extends CommonObject $label.= '
    '; // Add type of canvas - $link.=(!empty($this->canvas)?'&canvas='.$this->canvas:'').'"'; + $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'').'"'; + $linkclose=''; if (empty($notooltip)) { @@ -1928,22 +1933,21 @@ class Societe extends CommonObject $linkclose.=' class="classfortooltip"'; if (! is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); - } - $hookmanager->initHooks(array('societedao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - + { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager=new HookManager($this->db); + } + $hookmanager->initHooks(array('societedao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; } - $link.=$linkclose.'>'; + $linkstart.=$linkclose.'>'; $linkend='
    '; - if ($withpicto) $result.=($link.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip"')).$linkend); + if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$link.($maxlen?dol_trunc($name,$maxlen):$name).$linkend; + if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend; return $result; } @@ -1983,23 +1987,23 @@ class Societe extends CommonObject } if ($mode == 2) { - if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5').' '.$langs->trans("ActivityCeased"); - if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4').' '.$langs->trans("InActivity"); + if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased"); + if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity"); } if ($mode == 3) { - if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5'); - if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4'); + if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); + if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); } if ($mode == 4) { - if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5').' '.$langs->trans("ActivityCeased"); - if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4').' '.$langs->trans("InActivity"); + if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased"); + if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity"); } if ($mode == 5) { - if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5'); - if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4'); + if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"'); + if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"'); } } @@ -2181,7 +2185,7 @@ class Societe extends CommonObject * * @param int $rowid id of contact * @param string $mode 'email' or 'mobile' - * @return string email of contact + * @return string Email of contact with format: "Full name " */ function contact_get_property($rowid,$mode) { @@ -3408,29 +3412,43 @@ class Societe extends CommonObject * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information * @return int <0 if KO, >0 if OK */ - public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null) { global $conf,$user,$langs; - // Positionne le modele sur le nom du modele a utiliser - if (! dol_strlen($modele)) + if (! empty($moreparams) && ! empty($moreparams['use_companybankid'])) { - if (! empty($conf->global->COMPANY_ADDON_PDF)) - { - $modele = $conf->global->COMPANY_ADDON_PDF; - } - else - { - print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined"); - return 0; - } + $modelpath = "core/modules/bank/doc/"; + + include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; + $companybankaccount = new CompanyBankAccount($this->db); + $result = $companybankaccount->fetch($moreparams['use_companybankid']); + if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors); + $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + } + else + { + // Positionne le modele sur le nom du modele a utiliser + if (! dol_strlen($modele)) + { + if (! empty($conf->global->COMPANY_ADDON_PDF)) + { + $modele = $conf->global->COMPANY_ADDON_PDF; + } + else + { + print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined"); + return 0; + } + } + + $modelpath = "core/modules/societe/doc/"; + + $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } - - $modelpath = "core/modules/societe/doc/"; - - $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); return $result; } diff --git a/htdocs/societe/commerciaux.php b/htdocs/societe/commerciaux.php index e0f5ab7ec91..dd8802779b8 100644 --- a/htdocs/societe/commerciaux.php +++ b/htdocs/societe/commerciaux.php @@ -114,7 +114,9 @@ if (! empty($socid)) dol_fiche_head($head, 'salesrepresentative', $langs->trans("ThirdParty"),0,'company'); - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index eb912548caa..e46e0aa5848 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2013-2015 Juanjo Menent * Copyright (C) 2015 Marcos García * Copyright (C) 2015 Ferran Marcet @@ -57,7 +57,7 @@ $month = GETPOST('month','int'); $year = GETPOST('year','int'); // Clean up on purge search criteria ? -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { $sref=''; $sprod_fulldescr=''; @@ -114,7 +114,9 @@ if (empty($socid)) $head = societe_prepare_head($object); dol_fiche_head($head, 'consumption', $langs->trans("ThirdParty"),0,'company'); -dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); +$linkback = ''.$langs->trans("BackToList").''; + +dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; @@ -277,12 +279,12 @@ if ($type_element == 'contract') $thirdTypeSelect='customer'; } -if (!empty($sql_select)) +if (!empty($sql_select)) { $sql = $sql_select; $sql.= ' d.description as description,'; - if ($type_element != 'fichinter' && $type_element != 'contract') $sql.= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty,'; - if ($type_element == 'contract') $sql.= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty,'; + if ($type_element != 'fichinter' && $type_element != 'contract') $sql.= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + if ($type_element == 'contract') $sql.= ' d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; if ($type_element != 'fichinter') $sql.= ' p.ref as ref, p.rowid as prod_id, p.rowid as fk_product, p.fk_product_type as prod_type, p.fk_product_type as fk_product_type, p.entity as pentity,'; $sql.= " s.rowid as socid "; if ($type_element != 'fichinter') $sql.= ", p.ref as prod_ref, p.label as product_label"; @@ -311,10 +313,10 @@ if (!empty($sql_select)) $sql.=")"; } $sql.= $db->order($sortfield,$sortorder); - + $resql=$db->query($sql); $totalnboflines = $db->num_rows($resql); - + $sql.= $db->plimit($limit + 1, $offset); //print $sql; } @@ -332,6 +334,7 @@ $typeElementString = $form->selectarray("type_element", $elementTypeArray, GETPO $button = ''; $param="&sref=".$sref."&month=".$month."&year=".$year."&sprod_fulldescr=".$sprod_fulldescr."&socid=".$socid."&type_element=".$type_element; +$total_qty=0; if ($sql_select) { @@ -360,6 +363,8 @@ if ($sql_select) print_liste_field_titre($langs->trans('Status'),$_SERVER['PHP_SELF'],'fk_statut','',$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Product'),$_SERVER['PHP_SELF'],'','',$param,'align="left"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Quantity'),$_SERVER['PHP_SELF'],'prod_qty','',$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('TotalHT'),$_SERVER['PHP_SELF'],'total_ht','',$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('UnitPrice'),$_SERVER['PHP_SELF'],'','',$param,'align="right"',$sortfield,$sortorder); print "\n"; // Filters print ''; @@ -375,6 +380,10 @@ if ($sql_select) print ''; print ''; print ''; + print ''; + print ''; + print ''; + print ''; print ''; $searchpitco=$form->showFilterAndCheckAddButtons(0); print $searchpitco; @@ -552,11 +561,23 @@ if ($sql_select) //print ''.$prodreftxt.''; print ''.$objp->prod_qty.''; + $total_qty+=$objp->prod_qty; + + print ''.price($objp->total_ht).''; + $total_ht+=$objp->total_ht; + + print ''.price($objp->total_ht/(empty($objp->prod_qty)?1:$objp->prod_qty)).''; print "\n"; $i++; } + print ''; + print '' . $langs->trans('Total') . ''; + print ''; + print '' . $total_qty . ''; + print '' . price($total_ht) . ''; + print '' . price($total_ht/(empty($total_qty)?1:$total_qty)) . ''; print ""; if ($num > $limit) { diff --git a/htdocs/societe/document.php b/htdocs/societe/document.php index 4ad8abc9a43..d83822c2cd7 100644 --- a/htdocs/societe/document.php +++ b/htdocs/societe/document.php @@ -109,7 +109,9 @@ if ($object->id) $totalsize+=$file['size']; } - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; @@ -154,6 +156,7 @@ if ($object->id) $modulepart = 'societe'; $permission = $user->rights->societe->creer; + $permtoedit = $user->rights->societe->creer; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index af840283223..6acae492c33 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -6,6 +6,7 @@ * Copyright (C) 2013-2015 Raphaël Doursenaud * Copyright (C) 2015 Florian Henry * Copyright (C) 2016 Josep Lluis Amador + * Copyright (C) 2016 Ferran Marcet * * 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 @@ -169,7 +170,7 @@ $arrayfields=array( // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) + foreach($extrafields->attribute_label as $key => $val) { $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>$extrafields->attribute_list[$key], 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>$extrafields->attribute_perms[$key]); } @@ -180,54 +181,58 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab * Actions */ +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (empty($reshook)) { - if ($action == 'setstcomm') - { - $object = new Client($db); - $result=$object->fetch(GETPOST('stcommsocid')); - $object->stcomm_id=dol_getIdFromCode($db, GETPOST('stcomm','alpha'), 'c_stcomm'); - $result=$object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error,$object->errors,'errors'); + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - $action=''; - } -} + // Do we click on purge search criteria ? + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers + { + $search_nom=''; + $search_categ=0; + $search_sale=''; + $search_barcode=""; + $search_customer_code=''; + $search_supplier_code=''; + $search_account_customer_code=''; + $search_account_supplier_code=''; + $search_town=""; + $search_zip=""; + $search_state=""; + $search_country=''; + $search_idprof1=''; + $search_idprof2=''; + $search_idprof3=''; + $search_idprof4=''; + $search_idprof5=''; + $search_idprof6=''; + $search_type=''; + $search_type_thirdparty=''; + $search_status=''; + $search_stcomm=''; + $search_level_from=''; + $search_level_to=''; + $search_array_options=array(); + } -// Do we click on purge search criteria ? -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers -{ - $search_nom=''; - $search_categ=0; - $search_sale=''; - $search_barcode=""; - $search_customer_code=''; - $search_supplier_code=''; - $search_account_customer_code=''; - $search_account_supplier_code=''; - $search_town=""; - $search_zip=""; - $search_state=""; - $search_country=''; - $search_idprof1=''; - $search_idprof2=''; - $search_idprof3=''; - $search_idprof4=''; - $search_idprof5=''; - $search_idprof6=''; - $search_type=''; - $search_type_thirdparty=''; - $search_status=''; - $search_stcomm=''; - $search_level_from=''; - $search_level_to=''; - $search_array_options=array(); + if ($action == 'setstcomm') + { + $object = new Client($db); + $result=$object->fetch(GETPOST('stcommsocid')); + $object->stcomm_id=dol_getIdFromCode($db, GETPOST('stcomm','alpha'), 'c_stcomm'); + $result=$object->update($object->id, $user); + if ($result < 0) setEventMessages($object->error,$object->errors,'errors'); + + $action=''; + } } if ($search_status=='') $search_status=1; // always display active thirdparty first @@ -340,8 +345,9 @@ else dol_print_error($db); $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.barcode, s.town, s.zip, s.datec, s.code_client, s.code_fournisseur, "; $sql.= " st.libelle as stcomm, s.fk_stcomm as stcomm_id, s.fk_prospectlevel, s.prefix_comm, s.client, s.fournisseur, s.canvas, s.status as status,"; -$sql.= " s.siren as idprof1, s.siret as idprof2, ape as idprof3, idprof4 as idprof4, s.fk_pays,"; +$sql.= " s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4 as idprof4, s.fk_pays,"; $sql.= " s.tms as date_update, s.datec as date_creation,"; +$sql.= " s.code_compta,s.code_compta_fournisseur,"; $sql.= " typent.code as typent_code,"; $sql.= " state.code_departement as state_code, state.nom as state_name"; // We'll need these fields in order to filter by sale (including the case where the user can only see his prospects) @@ -407,7 +413,7 @@ foreach ($search_array_options as $key => $val) $typ=$extrafields->attribute_type[$tmpkey]; $mode=0; if (in_array($typ, array('int','double'))) $mode=1; // Search on a numeric - if ($val && ( ($crit != '' && ! in_array($typ, array('select'))) || ! empty($crit))) + if ($val && ( ($crit != '' && ! in_array($typ, array('select'))) || ! empty($crit))) { $sql .= natural_search('ef.'.$tmpkey, $crit, $mode); } @@ -437,9 +443,8 @@ if (! $resql) } $num = $db->num_rows($resql); -$i = 0; -if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE)) +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && $action != 'list') { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -453,6 +458,7 @@ llxHeader('',$langs->trans("ThirdParty"),$help_url); $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($search_all != '') $param = "&sall=".urlencode($search_all); if ($sall != '') $param .= "&sall=".urlencode($sall); if ($search_categ > 0) $param.='&search_categ='.urlencode($search_categ); if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); @@ -535,6 +541,17 @@ if ($type == 'c' || $type == 'p') $moreforfilter.='
    '; } } +if ($type == 'f') +{ + if (! empty($conf->categorie->enabled)) + { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
    '; + $moreforfilter.=$langs->trans('Categories'). ': '; + $moreforfilter.=$formother->select_categories('supplier',$search_categ,'search_categ',1); + $moreforfilter.='
    '; + } +} // If the user can view prospects other than his' if ($user->rights->societe->client->voir || $socid) @@ -544,17 +561,6 @@ if ($user->rights->societe->client->voir || $socid) $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user, 0, 1, 'maxwidth300'); $moreforfilter.='
    '; } -if ($type == 'f') -{ - if (! empty($conf->categorie->enabled)) - { - require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; - $moreforfilter.='
    '; - $moreforfilter.=$langs->trans('Categories'). ': '; - $moreforfilter.=$formother->select_categories('supplier',$search_categ,'search_categ',1); - $moreforfilter.='
    '; - } -} if (! empty($moreforfilter)) { print '
    '; @@ -846,7 +852,7 @@ print ''; print "\n"; $var=True; - +$i = 0; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -978,6 +984,7 @@ while ($i < min($num, $limit)) print $s; print ''; } + if (! empty($arrayfields['s.fk_prospectlevel']['checked'])) { // Prospect level @@ -985,6 +992,7 @@ while ($i < min($num, $limit)) print $companystatic->getLibProspLevel(); print ""; } + if (! empty($arrayfields['s.fk_stcomm']['checked'])) { // Prospect status @@ -1002,9 +1010,9 @@ while ($i < min($num, $limit)) // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { - foreach($extrafields->attribute_label as $key => $val) + foreach($extrafields->attribute_label as $key => $val) { - if (! empty($arrayfields["ef.".$key]['checked'])) + if (! empty($arrayfields["ef.".$key]['checked'])) { print 'getAlignFlag($key); diff --git a/htdocs/societe/note.php b/htdocs/societe/note.php index 5c9bc15328f..e88f94e4287 100644 --- a/htdocs/societe/note.php +++ b/htdocs/societe/note.php @@ -73,12 +73,14 @@ if ($id > 0) dol_fiche_head($head, 'note', $langs->trans("ThirdParty"),0,'company'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); - print '
    '; - print ''; - - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); - + $cssclass='titlefield'; + //if ($action == 'editnote_public') $cssclass='titlefieldcreate'; + //if ($action == 'editnote_private') $cssclass='titlefieldcreate'; + print '
    '; print '
    '; @@ -86,12 +88,12 @@ if ($id > 0) if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { - print ''.$langs->trans('Prefix').''.$object->prefix_comm.''; + print ''.$langs->trans('Prefix').''.$object->prefix_comm.''; } if ($object->client) { - print ''; + print ''; print $langs->trans('CustomerCode').''; print $object->code_client; if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; @@ -100,7 +102,7 @@ if ($id > 0) if ($object->fournisseur) { - print ''; + print ''; print $langs->trans('SupplierCode').''; print $object->code_fournisseur; if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; @@ -111,13 +113,11 @@ if ($id > 0) print '
    '; - print '
    '; + //print '
    '; - //$colwidth='25'; - $cssclass='titlefield'; + //print '
    '; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; - dol_fiche_end(); } diff --git a/htdocs/societe/notify/card.php b/htdocs/societe/notify/card.php index 39a0ee2371b..bc754d8e9a4 100644 --- a/htdocs/societe/notify/card.php +++ b/htdocs/societe/notify/card.php @@ -155,7 +155,9 @@ if ($result > 0) dol_fiche_head($head, 'notify', $langs->trans("ThirdParty"),0,'company'); - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; @@ -165,12 +167,12 @@ if ($result > 0) // Prefix if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { - print ''.$langs->trans('Prefix').''.$object->prefix_comm.''; + print ''.$langs->trans('Prefix').''.$object->prefix_comm.''; } if ($object->client) { - print ''; + print ''; print $langs->trans('CustomerCode').''; print $object->code_client; if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; @@ -179,14 +181,14 @@ if ($result > 0) if ($object->fournisseur) { - print ''; + print ''; print $langs->trans('SupplierCode').''; print $object->code_fournisseur; if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; print ''; } - print ''.$langs->trans("NbOfActiveNotifications").''; + print ''.$langs->trans("NbOfActiveNotifications").''; print ''; $notify=new Notify($db); $tmparray = $notify->getNotificationsArray('', $object->id); diff --git a/htdocs/societe/price.php b/htdocs/societe/price.php index 4c988603417..9236fc35f6f 100644 --- a/htdocs/societe/price.php +++ b/htdocs/societe/price.php @@ -151,7 +151,9 @@ $head = societe_prepare_head($object); dol_fiche_head($head, 'price', $langs->trans("ThirdParty"), 0, 'company'); -dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); +$linkback = ''.$langs->trans("BackToList").''; + +dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; diff --git a/htdocs/societe/project.php b/htdocs/societe/project.php index f99bd517975..fe206dd4cc5 100644 --- a/htdocs/societe/project.php +++ b/htdocs/societe/project.php @@ -81,7 +81,9 @@ if ($socid) dol_fiche_head($head, 'project', $langs->trans("ThirdParty"),0,'company'); - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; diff --git a/htdocs/societe/rib.php b/htdocs/societe/rib.php index d31226ac052..1d8e9348f72 100644 --- a/htdocs/societe/rib.php +++ b/htdocs/societe/rib.php @@ -1,7 +1,7 @@ * Copyright (C) 2003 Jean-Louis Bergamo - * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2013 Peter Fontaine * Copyright (C) 2015-2016 Marcos García @@ -29,6 +29,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; @@ -38,203 +39,269 @@ $langs->load("banks"); $langs->load("bills"); // Security check -$socid = GETPOST("socid"); +$socid = GETPOST("socid","int"); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'societe','',''); +$id=GETPOST("id","int"); +$ribid=GETPOST("ribid","int"); +$action=GETPOST("action", 'alpha', 3); + $object = new Societe($db); $object->fetch($socid); -$id=GETPOST("id","int"); -$ribid=GETPOST("ribid","int"); -$action=GETPOST("action"); +$account = new CompanyBankAccount($db); +$prelevement = new BonPrelevement($db); + +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('thirdpartybancard','globalcard')); + /* * Actions */ -if ($action == 'update' && ! $_POST["cancel"]) +$parameters=array('id'=>$socid, 'objcanvas'=>$objcanvas); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) { - // Modification - $account = new CompanyBankAccount($db); - - - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='update'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='update'; - $error++; - } - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='update'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='update'; - $error++; - } - } - - $account->fetch($id); - if (! $error) + if ($cancel) { - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur','alpha'); - - $result = $account->update($user); - if (! $result) - { - setEventMessages($account->error, $account->errors, 'errors'); - } - else - { - // If this account is the default bank account, we disable others - if ($account->default_rib) - { - $account->setAsDefault($id); // This will make sure there is only one default rib - } - - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } + $action=''; + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } } -} -if ($action == 'add' && ! $_POST["cancel"]) -{ - $error=0; - - if (! GETPOST('label')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bank')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); - $action='create'; - $error++; - } - if ($account->needIBAN() == 1) - { - if (! GETPOST('iban')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); - $action='create'; - $error++; - } - if (! GETPOST('bic')) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); - $action='create'; - $error++; - } - } - - if (! $error) - { - // Ajout - $account = new CompanyBankAccount($db); - - $account->socid = $object->id; - - $account->bank = GETPOST('bank','alpha'); - $account->label = GETPOST('label','alpha'); - $account->courant = GETPOST('courant','alpha'); - $account->clos = GETPOST('clos','alpha'); - $account->code_banque = GETPOST('code_banque','alpha'); - $account->code_guichet = GETPOST('code_guichet','alpha'); - $account->number = GETPOST('number','alpha'); - $account->cle_rib = GETPOST('cle_rib','alpha'); - $account->bic = GETPOST('bic','alpha'); - $account->iban = GETPOST('iban','alpha'); - $account->domiciliation = GETPOST('domiciliation','alpha'); - $account->proprio = GETPOST('proprio','alpha'); - $account->owner_address = GETPOST('owner_address','alpha'); - $account->frstrecur = GETPOST('frstrecur'); - - $result = $account->update($user); // TODO Use create and include update into create method - if (! $result) - { - setEventMessages($account->error, $account->errors, 'errors'); - $_GET["action"]='create'; // Force chargement page création - } - else - { - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; - } - } -} - -if ($action == 'setasdefault') -{ - $account = new CompanyBankAccount($db); - $res = $account->setAsDefault(GETPOST('ribid','int')); - if ($res) + + if ($action == 'update' && ! $_POST["cancel"]) { - $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; - header('Location: '.$url); - exit; + // Modification + if (! GETPOST('label')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + $action='update'; + $error++; + } + if (! GETPOST('bank')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + $action='update'; + $error++; + } + if ($account->needIBAN() == 1) + { + if (! GETPOST('iban')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); + $action='update'; + $error++; + } + if (! GETPOST('bic')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); + $action='update'; + $error++; + } + } + + $account->fetch($id); + if (! $error) + { + $account->socid = $object->id; + + $account->bank = GETPOST('bank','alpha'); + $account->label = GETPOST('label','alpha'); + $account->courant = GETPOST('courant','alpha'); + $account->clos = GETPOST('clos','alpha'); + $account->code_banque = GETPOST('code_banque','alpha'); + $account->code_guichet = GETPOST('code_guichet','alpha'); + $account->number = GETPOST('number','alpha'); + $account->cle_rib = GETPOST('cle_rib','alpha'); + $account->bic = GETPOST('bic','alpha'); + $account->iban = GETPOST('iban','alpha'); + $account->domiciliation = GETPOST('domiciliation','alpha'); + $account->proprio = GETPOST('proprio','alpha'); + $account->owner_address = GETPOST('owner_address','alpha'); + $account->frstrecur = GETPOST('frstrecur','alpha'); + $account->rum = GETPOST('rum','alpha'); + if (empty($account->rum)) + { + $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + $account->date_rum = dol_now(); + } + + $result = $account->update($user); + if (! $result) + { + setEventMessages($account->error, $account->errors, 'errors'); + } + else + { + // If this account is the default bank account, we disable others + if ($account->default_rib) + { + $account->setAsDefault($id); // This will make sure there is only one default rib + } + + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + } } - else + + if ($action == 'add' && ! $_POST["cancel"]) { - setEventMessages($db->lasterror, null, 'errors'); + $error=0; + + if (! GETPOST('label')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + $action='create'; + $error++; + } + if (! GETPOST('bank')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankName")), null, 'errors'); + $action='create'; + $error++; + } + + if (! $error) + { + // Ajout + $account = new CompanyBankAccount($db); + + $account->socid = $object->id; + + $account->bank = GETPOST('bank','alpha'); + $account->label = GETPOST('label','alpha'); + $account->courant = GETPOST('courant','alpha'); + $account->clos = GETPOST('clos','alpha'); + $account->code_banque = GETPOST('code_banque','alpha'); + $account->code_guichet = GETPOST('code_guichet','alpha'); + $account->number = GETPOST('number','alpha'); + $account->cle_rib = GETPOST('cle_rib','alpha'); + $account->bic = GETPOST('bic','alpha'); + $account->iban = GETPOST('iban','alpha'); + $account->domiciliation = GETPOST('domiciliation','alpha'); + $account->proprio = GETPOST('proprio','alpha'); + $account->owner_address = GETPOST('owner_address','alpha'); + $account->frstrecur = GETPOST('frstrecur'); + + // This test can be done only once properties were set + if ($account->needIBAN() == 1) + { + if (! GETPOST('iban')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("IBAN")), null, 'errors'); + $action='create'; + $error++; + } + if (! GETPOST('bic')) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BIC")), null, 'errors'); + $action='create'; + $error++; + } + } + + if (! $error) + { + if (empty($account->rum)) + { + $account->rum = $prelevement->buildRumNumber($object->code_client, $account->datec, $account->id); + $account->date_rum = dol_now(); + } + + $result = $account->update($user); // This will set the UMR number. + // TODO Use create and include update into create method + if (! $result) + { + setEventMessages($account->error, $account->errors, 'errors'); + $_GET["action"]='create'; // Force chargement page création + } + else + { + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + } + } } + + if ($action == 'setasdefault') + { + $account = new CompanyBankAccount($db); + $res = $account->setAsDefault(GETPOST('ribid','int')); + if ($res) + { + $url=DOL_URL_ROOT.'/societe/rib.php?socid='.$object->id; + header('Location: '.$url); + exit; + } + else + { + setEventMessages($db->lasterror, null, 'errors'); + } + } + + if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') + { + $account = new CompanyBankAccount($db); + if ($account->fetch($ribid?$ribid:$id)) + { + $result = $account->delete($user); + if ($result > 0) + { + $url = $_SERVER['PHP_SELF']."?socid=".$object->id; + header('Location: '.$url); + exit; + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + } + } + else + { + setEventMessages($account->error, $account->errors, 'errors'); + } + } + + $savid=$id; + + // Actions to build doc + if ($action == 'builddocrib') + { + $action = 'builddoc'; + $moreparams = array( + 'use_companybankid'=>GETPOST('companybankid'), + 'force_dir_output'=>$conf->societe->dir_output.'/'.dol_sanitizeFileName($object->id) + ); + $_POST['lang_id'] = GETPOST('lang_idrib'.GETPOST('companybankid')); + $_POST['model'] = GETPOST('modelrib'.GETPOST('companybankid')); + } + $id = $socid; + $upload_dir = $conf->societe->dir_output; + $permissioncreate=$user->rights->societe->creer; + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + $id = $savid; } -if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') -{ - $account = new CompanyBankAccount($db); - if ($account->fetch($ribid?$ribid:$id)) - { - $result = $account->delete($user); - if ($result > 0) - { - $url = $_SERVER['PHP_SELF']."?socid=".$object->id; - header('Location: '.$url); - exit; - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } - } - else - { - setEventMessages($account->error, $account->errors, 'errors'); - } -} /* @@ -242,21 +309,18 @@ if ($action == 'confirm_delete' && $_GET['confirm'] == 'yes') */ $form = new Form($db); -$prelevement = new BonPrelevement($db); +$formfile = new FormFile($db); llxHeader(); -$head=societe_prepare_head2($object); +$head=societe_prepare_head($object); - -$account = new CompanyBankAccount($db); if (! $id) $account->fetch(0,$object->id); else $account->fetch($id); if (empty($account->socid)) $account->socid=$object->id; - if ($socid && $action == 'edit' && $user->rights->societe->creer) { print ''; @@ -283,7 +347,9 @@ if ($socid && $action != 'edit' && $action != "create") print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id."&ribid=".($ribid?$ribid:$id), $langs->trans("DeleteARib"), $langs->trans("ConfirmDeleteRib", $account->getRibLabel()), "confirm_delete", '', 0, 1); } - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; @@ -299,8 +365,7 @@ if ($socid && $action != 'edit' && $action != "create") print ''.$account->bank.''; // Show fields of bank account - - foreach($account->getFieldsToShow() as $val) + foreach($account->getFieldsToShow(1) as $val) { if ($val == 'BankCode') { $content = $account->code_banque; @@ -308,24 +373,31 @@ if ($socid && $action != 'edit' && $action != "create") $content = $account->code_guichet; } elseif ($val == 'BankAccountNumber') { $content = $account->number; + if (! empty($account->label)) { + if (! checkBanForAccount($account)) { + $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); + } else { + $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); + } + } } elseif ($val == 'BankAccountNumberKey') { $content = $account->cle_rib; - }elseif ($val == 'IBAN') { + } elseif ($val == 'IBAN') { $content = $account->iban; if (! empty($account->iban)) { if (! checkIbanForAccount($account)) { - $content.= img_picto($langs->trans("IbanNotValid"),'warning'); + $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); } else { - $content.= img_picto($langs->trans("IbanValid"),'info'); + $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); } } - }elseif ($val == 'BIC') { + } elseif ($val == 'BIC') { $content = $account->bic; if (! empty($account->bic)) { if (! checkSwiftForAccount($account)) { - $content.= img_picto($langs->trans("SwiftNotValid"),'warning'); + $content.= ' '.img_picto($langs->trans("ValueIsNotValid"),'warning'); } else { - $content.= img_picto($langs->trans("SwiftValid"),'info'); + $content.= ' '.img_picto($langs->trans("ValueIsValid"),'info'); } } } @@ -335,26 +407,20 @@ if ($socid && $action != 'edit' && $action != "create") print ''; } - print ''.$langs->trans("BankAccountDomiciliation").''; + print ''.$langs->trans("BankAccountDomiciliation").''; print $account->domiciliation; print "\n"; - print ''.$langs->trans("BankAccountOwner").''; + print ''.$langs->trans("BankAccountOwner").''; print $account->proprio; print "\n"; - print ''.$langs->trans("BankAccountOwnerAddress").''; + print ''.$langs->trans("BankAccountOwnerAddress").''; print $account->owner_address; print "\n"; print ''; - // Check BBAN - if ($account->label && ! checkBanForAccount($account)) - { - print '
    '.$langs->trans("RIBControlError").'
    '; - } - print "
    "; dol_fiche_end(); @@ -380,10 +446,11 @@ if ($socid && $action != 'edit' && $action != "create") print_liste_field_titre($langs->trans("BIC")); if (! empty($conf->prelevement->enabled)) { - print 'RUM'; - print ''.$langs->trans("WithdrawMode").''; + print print_liste_field_titre($langs->trans("RUM")); + print print_liste_field_titre($langs->trans("WithdrawMode")); } print_liste_field_titre($langs->trans("DefaultRIB"), '', '', '', '', 'align="center"'); + print_liste_field_titre('', '', '', '', '', 'align="center"'); print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; @@ -395,16 +462,53 @@ if ($socid && $action != 'edit' && $action != "create") // Bank name print ''.$rib->bank.''; // Account number - print ''.$rib->getRibLabel(false).''; + print ''; + $string=''; + foreach ($rib->getFieldsToShow() as $val) { + + if ($val == 'BankCode') { + $string .= $rib->code_banque.' '; + } elseif ($val == 'BankAccountNumber') { + $string .= $rib->number.' '; + } elseif ($val == 'DeskCode') { + $string .= $rib->code_guichet.' '; + } elseif ($val == 'BankAccountNumberKey') { + $string .= $rib->cle_rib.' '; + /* Already output after + }elseif ($val == 'BIC') { + $string .= $rib->bic.' '; + }elseif ($val == 'IBAN') { + $string .= $rib->iban.' ';*/ + } + } + print $string; + print ''; // IBAN - print ''.$rib->iban.''; + print ''.$rib->iban; + if (! empty($rib->iban)) { + if (! checkIbanForAccount($rib)) { + print ' '.img_picto($langs->trans("IbanNotValid"),'warning'); + } else { + print ' '.img_picto($langs->trans("IbanValid"),'info'); + } + } + print ''; // BIC - print ''.$rib->bic.''; + print ''.$rib->bic; + if (! empty($rib->bic)) { + if (! checkSwiftForAccount($rib)) { + print ' '.img_picto($langs->trans("SwiftNotValid"),'warning'); + } else { + print ' '.img_picto($langs->trans("SwiftValid"),'info'); + } + } + print ''; if (! empty($conf->prelevement->enabled)) { // RUM - print ''.$prelevement->buildRumNumber($object->code_client, $rib->datec, $rib->id).''; + //print ''.$prelevement->buildRumNumber($object->code_client, $rib->datec, $rib->id).''; + print ''.$rib->rum.''; // FRSTRECUR print ''.$rib->frstrecur.''; @@ -420,7 +524,60 @@ if ($socid && $action != 'edit' && $action != "create") print img_picto($langs->trans("Enabled"),'on'); } print ''; - + + // Generate doc + print ''; + + $buttonlabel = $langs->trans("BuildDoc"); + $forname='builddocrib'.$rib->id; + + include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; + $modellist=ModeleBankAccountDoc::liste_modeles($db); + $out = ''; + if (is_array($modellist) && count($modellist)) + { + $out.= ''; + $out.= ''; + $out.= ''; + $out.= ''; + $out.= ''; + + if (is_array($modellist) && count($modellist) == 1) // If there is only one element + { + $arraykeys=array_keys($modellist); + $modelselected=$arraykeys[0]; + } + $out.= $form->selectarray('modelrib'.$rib->id, $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out.= ajax_combobox('modelrib'.$rib->id); + + // Language code (if multilang) + if ($conf->global->MAIN_MULTILANGS) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin=new FormAdmin($db); + $defaultlang=$codelang?$codelang:$langs->getDefaultLang(); + $morecss='maxwidth150'; + if (! empty($conf->browser->phone)) $morecss='maxwidth100'; + $out.= $formadmin->select_language($defaultlang, 'lang_idrib'.$rib->id, 0, 0, 0, 0, 0, $morecss); + } + // 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.= ''; + } + print $out; + print ''; + // Edit/Delete print ''; if ($user->rights->societe->creer) @@ -436,12 +593,13 @@ if ($socid && $action != 'edit' && $action != "create") print ''; } print ''; + print ''; } if (count($rib_list) == 0) { - $colspan=7; + $colspan=8; if (! empty($conf->prelevement->enabled)) $colspan+=2; print ''.$langs->trans("NoBANRecord").''; } @@ -451,6 +609,68 @@ if ($socid && $action != 'edit' && $action != "create") dol_print_error($db); } + + if ($socid && $action != 'edit' && $action != 'create') + { + /* + * Barre d'actions + */ + print '
    '; + + if ($user->rights->societe->creer) + { + print ''.$langs->trans("Add").''; + } + + print '
    '; + } + + + + + if (empty($conf->global->SOCIETE_DISABLE_BUILDDOC)) + { + print '
    '; + print ''; // ancre + + /* + * Documents generes + */ + $filedir=$conf->societe->multidir_output[$object->entity].'/'.$object->id; + $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id; + $genallowed=$user->rights->societe->creer; + $delallowed=$user->rights->societe->supprimer; + + $var=true; + + print $formfile->showdocuments('company', $object->id, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 0, 0, 0, 28, 0, '', 0, '', $object->default_lang); + + print '
    '; + + + print '
    '; + + print '
    '; + } + /* + include_once DOL_DOCUMENT_ROOT.'/core/modules/bank/modules_bank.php'; + $modellist=ModeleBankAccountDoc::liste_modeles($db); + //print ''; + 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, 0, 0, 0, '', 0, 0, 0, '', 'minwidth100'); + $out.= ajax_combobox('model'); + //print $out; + $buttonlabel=$langs->trans("Generate"); + $genbutton = ''; // TODO Add link to generate doc + */ } // Edit @@ -458,21 +678,23 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) { dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; print '
    '; print ''; - print ''; + print ''; print ''; print ''; print ''; // Show fields of bank account - foreach ($account->getFieldsToShow() as $val) { + foreach ($account->getFieldsToShow(1) as $val) { $require=false; if ($val == 'BankCode') { @@ -509,7 +731,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) } print '"; @@ -518,7 +740,7 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) print "\n"; print '"; @@ -534,11 +756,11 @@ if ($socid && $action == 'edit' && $user->rights->societe->creer) // RUM print ''; - print ''; + print ''; // FRSTRECUR print ''; - print ''; + print ''; print '
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("LabelRIB").'
    '.$langs->trans("BankName").'
    '.$langs->trans("BankAccountDomiciliation").''; - print '
    '.$langs->trans("BankAccountOwnerAddress").''; - print "
    '.$langs->trans("RUM").''.$account->rum.'
    '.$langs->trans("WithdrawMode").'
    '; } @@ -560,7 +782,9 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) { dol_fiche_head($head, 'rib', $langs->trans("ThirdParty"),0,'company'); - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; @@ -603,14 +827,14 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) } // IBAN - print 'needIBAN()?' class="fieldrequired" ':'').'>'.$langs->trans("IBAN").''; + print 'needIBAN()?' class="fieldrequired" ':'').'>'.$langs->trans("IBAN").''; print ''; - print 'needIBAN()?' class="fieldrequired" ':'').'>'.$langs->trans("BIC").''; + print 'needIBAN()?' class="fieldrequired" ':'').'>'.$langs->trans("BIC").''; print ''; print ''.$langs->trans("BankAccountDomiciliation").''; - print '"; @@ -619,7 +843,7 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) print "\n"; print ''.$langs->trans("BankAccountOwnerAddress").''; - print '"; @@ -663,23 +887,6 @@ if ($socid && $action == 'create' && $user->rights->societe->creer) } - -if ($socid && $action != 'edit' && $action != 'create') -{ - /* - * Barre d'actions - */ - print '
    '; - - if ($user->rights->societe->creer) - { - print ''.$langs->trans("Add").''; - } - - print '
    '; -} - - llxFooter(); $db->close(); diff --git a/htdocs/societe/soc.php b/htdocs/societe/soc.php index f6315c75833..0220f775d7b 100644 --- a/htdocs/societe/soc.php +++ b/htdocs/societe/soc.php @@ -228,14 +228,14 @@ if (empty($reshook)) //obtidre selected del combobox $value=GETPOST('lt1'); $object->fetch($socid); - $res=$object->setValueFrom('localtax1_value', $value); + $res=$object->setValueFrom('localtax1_value', $value, '', null, 'text', '', $user, 'COMPANY_MODIFY'); } if($action=='set_localtax2') { //obtidre selected del combobox $value=GETPOST('lt2'); $object->fetch($socid); - $res=$object->setValueFrom('localtax2_value', $value); + $res=$object->setValueFrom('localtax2_value', $value, '', null, 'text', '', $user, 'COMPANY_MODIFY'); } // Add new or update third party @@ -712,6 +712,7 @@ if (empty($reshook)) $trigger_name='COMPANY_SENTBYMAIL'; $paramname='socid'; $mode='emailfromthirdparty'; + $trackid='thi'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Actions to build doc @@ -764,7 +765,7 @@ else * Creation */ $private=GETPOST("private","int"); - if (! empty($conf->global->MAIN_THIRDPARTY_CREATION_INDIVIDUAL) && ! isset($_GET['private']) && ! isset($_POST['private'])) $private=1; + if (! empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT) && ! isset($_GET['private']) && ! isset($_POST['private'])) $private=1; if (empty($private)) $private=0; // Load object modCodeTiers @@ -813,7 +814,8 @@ else if(empty($duplicate_code_error)) { $object->code_client = GETPOST('code_client', 'alpha'); $object->fournisseur = GETPOST('fournisseur')?GETPOST('fournisseur'):$object->fournisseur; - } else { + } + else { setEventMessages($langs->trans('NewCustomerSupplierCodeProposed'),'', 'warnings'); } @@ -939,13 +941,13 @@ else print ''; print '     '; print ''; @@ -981,7 +983,7 @@ else print ''.fieldLabel('ThirdPartyName','name').''; } print 'global->SOCIETE_USEPREFIX)?' colspan="3"':'').'>'; - print ''; + print ''; if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field { print ''.$langs->trans('Prefix').''; @@ -992,16 +994,17 @@ else if ($conf->use_javascript_ajax) { print ''.fieldLabel('FirstName','firstname').''; - print ''; + print ''; print ''; - print ''.fieldLabel('UserTitle','civility_id').''; - print $formcompany->select_civility($object->civility_id).''; + // Title + print ''.fieldLabel('UserTitle','civility_id').''; + print $formcompany->select_civility($object->civility_id, 'civility_id', 'maxwidth100').''; print ''; } // Alias names (commercial, trademark or alias names) print ''; - print ''; + print ''; // Prospect/Customer print ''.fieldLabel('ProspectCustomer','customerprospect',1).''; @@ -1015,11 +1018,11 @@ else print ''; print ''; - print ''.fieldLabel('CustomerCode','customer_code').''; + print ''.fieldLabel('CustomerCode','customer_code').''; print '
    '; $tmpcode=$object->code_client; if (empty($tmpcode) && ! empty($modCodeClient->code_auto)) $tmpcode=$modCodeClient->getNextValue($object,0); - print ''; + print ''; print ''; $s=$modCodeClient->getToolTip($langs,$object,0); print $form->textwithpicto('',$s,1); @@ -1039,7 +1042,7 @@ else print ''; // Country - print ''; @@ -1090,22 +1093,22 @@ else // Email web print ''; - print ''; + print ''; print ''; - print ''; - + print ''; + // Skype if (! empty($conf->skype->enabled)) { print ''; - print ''; + print ''; } // Phone / Fax print ''; - print ''; + print ''; print ''; - print ''; + print ''; // Prof ids $i=1; $j=0; @@ -1130,14 +1133,14 @@ else } if ($j % 2 == 1) print ''; - // Assujeti TVA + // Vat is used print ''; print ''; print ''; print ''; print ''; + // Local Taxes + //TODO: Place into a function to control showing by country or study better option + if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + { + print ''; + + } + elseif($mysoc->localtax1_assuj=="1") + { + print ''; + } + elseif($mysoc->localtax2_assuj=="1") + { + print ''; + } + // Type - Size print ''; - // Local Taxes - //TODO: Place into a function to control showing by country or study better option - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") - { - print ''; - - } - elseif($mysoc->localtax1_assuj=="1") - { - print ''; - } - elseif($mysoc->localtax2_assuj=="1") - { - print ''; - } - if (! empty($conf->global->MAIN_MULTILANGS)) { print ''; print ''; } @@ -1510,11 +1513,11 @@ else // Name print ''; - print ''; + print ''; // Alias names (commercial, trademark or alias names) print ''; - print ''; + print ''; // Prefix if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field @@ -1541,7 +1544,7 @@ else if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) print ''; print ''; print ''; - print '
    '; $tmpcode=$object->code_fournisseur; if (empty($tmpcode) && ! empty($modCodeFournisseur->code_auto)) $tmpcode=$modCodeFournisseur->getNextValue($object,1); - print ''; + print ''; print ''; $s=$modCodeFournisseur->getToolTip($langs,$object,1); print $form->textwithpicto('',$s,1); @@ -1068,13 +1071,13 @@ else // Zip / Town print '
    '.fieldLabel('Zip','zipcode').''; - print $formcompany->select_ziptown($object->zip,'zipcode',array('town','selectcountry_id','state_id'),6); + print $formcompany->select_ziptown($object->zip,'zipcode',array('town','selectcountry_id','state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent'); print ''.fieldLabel('Town','town').''; - print $formcompany->select_ziptown($object->town,'town',array('zipcode','selectcountry_id','state_id')); + print $formcompany->select_ziptown($object->town,'town',array('zipcode','selectcountry_id','state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent'); print '
    '.fieldLabel('Country','selectcountry_id').''; + print '
    '.fieldLabel('Country','selectcountry_id').''; print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id)); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); print '
    '.fieldLabel('EMail','email').(! empty($conf->global->SOCIETE_MAIL_REQUIRED)?'*':'').'
    '.fieldLabel('Web','url').'
    '.fieldLabel('Skype','skype').'
    '.fieldLabel('Phone','phone').''.fieldLabel('Fax','fax').'
    '.fieldLabel('VATIsUsed','assujtva_value').''; - print $form->selectyesno('assujtva_value',1,1); // Assujeti par defaut en creation + print $form->selectyesno('assujtva_value',(isset($conf->global->THIRDPARTY_DEFAULT_USEVAT)?$conf->global->THIRDPARTY_DEFAULT_USEVAT:1),1); // Assujeti par defaut en creation print ''.fieldLabel('VATIntra','intra_vat').''; - $s = ''; + $s = ''; if (empty($conf->global->MAIN_DISABLEVATCHECK)) { @@ -1164,6 +1167,30 @@ else print '
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; + print $form->selectyesno('localtax1assuj_value',(isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1:0),1); + print ''.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; + print $form->selectyesno('localtax2assuj_value',(isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2:0),1); + print '
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; + print $form->selectyesno('localtax1assuj_value',(isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1:0),1); + print '
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; + print $form->selectyesno('localtax2assuj_value',(isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2)?$conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2:0),1); + print '
    '.fieldLabel('ThirdPartyType','typent_id').''."\n"; $sortparam=(empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. @@ -1193,34 +1220,10 @@ else print ' '; print ''.$langs->trans("Currency".$conf->currency).'
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; - print $form->selectyesno('localtax1assuj_value',0,1); - print ''.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; - print $form->selectyesno('localtax2assuj_value',0,1); - print '
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; - print $form->selectyesno('localtax1assuj_value',0,1); - print '
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; - print $form->selectyesno('localtax2assuj_value',0,1); - print '
    '.fieldLabel('DefaultLang','default_lang').''."\n"; - print $formadmin->select_language(($object->default_lang?$object->default_lang:$conf->global->MAIN_LANG_DEFAULT),'default_lang',0,0,1); + print $formadmin->select_language(($object->default_lang?$object->default_lang:$conf->global->MAIN_LANG_DEFAULT),'default_lang',0,0,1,0,0,'maxwidth200onsmartphone'); print '
    '.fieldLabel('ThirdPartyName','name',1).'
    '.fieldLabel('CustomerCode','customer_code').''; + print ''.fieldLabel('CustomerCode','customer_code').''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; // Prof ids $i=1; $j=0; @@ -1686,15 +1689,65 @@ else } if ($j % 2 == 1) print ''; - // VAT payers - print ''; + // Local Taxes + //TODO: Place into a function to control showing by country or study better option + if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + { + print ''; + + } + elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1") + { + print ''; + + } + elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1") + { + print ''; + } + // VAT Code print ''; - print ''; print ''; - // Local Taxes - //TODO: Place into a function to control showing by country or study better option - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") - { - print ''; - - } - elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1") - { - print ''; - - } - elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1") - { - print ''; - } - // Type - Size print ''; - // VAT payers + // VAT is used print ''; print ''; + // Local Taxes + //TODO: Place into a function to control showing by country or study better option + if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + { + print ''; + + if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1))) + { + print ''; + print ''; + print ''; + print ''; + if($action == 'editRE') + { + print ''; + } + else + { + print ''; + } + print ''; + } + if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2))) + { + print ''; + print ''; + print ''; + print ''; + if($action == 'editIRPF'){ + print ''; + }else{ + print ''; + } + print ''; + } + } + elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1") + { + print ''; + if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1))) + { + print ''; + print ''; + print ''; + print ''; + if($action == 'editRE'){ + print ''; + }else{ + print ''; + } + print ''; + + } + } + elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1") + { + print ''; + if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2))) + { + + print ''; + print ''; + print ''; + print ''; + if($action == 'editIRPF'){ + print ''; + }else{ + print ''; + } + print ''; + + } + } + /* + if ($mysoc->country_code=='ES' && $mysoc->localtax2_assuj!="1" && ! empty($conf->fournisseur->enabled) && $object->fournisseur==1) + { + print ''; + } + */ + // VAT Code print ''; print ''; print ''; - // Local Taxes - //TODO: Place into a function to control showing by country or study better option - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") - { - print ''; - - if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1))) - { - print ''; - print ''; - print ''; - print ''; - if($action == 'editRE') - { - print ''; - } - else - { - print ''; - } - print ''; - } - if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2))) - { - print ''; - print ''; - print ''; - print ''; - if($action == 'editIRPF'){ - print ''; - }else{ - print ''; - } - print ''; - } - } - elseif($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj!="1") - { - print ''; - if($object->localtax1_assuj=="1" && (! isOnlyOneLocalTax(1))) - { - print ''; - print ''; - print ''; - print ''; - if($action == 'editRE'){ - print ''; - }else{ - print ''; - } - print ''; - - } - } - elseif($mysoc->localtax2_assuj=="1" && $mysoc->localtax1_assuj!="1") - { - print ''; - if($object->localtax2_assuj=="1" && (! isOnlyOneLocalTax(2))) - { - - print ''; - print ''; - print ''; - print ''; - if($action == 'editIRPF'){ - print ''; - }else{ - print ''; - } - print ''; - - } - } -/* - if ($mysoc->country_code=='ES' && $mysoc->localtax2_assuj!="1" && ! empty($conf->fournisseur->enabled) && $object->fournisseur==1) - { - print ''; - } -*/ // Type + Staff $arr = $formcompany->typent_array(1); $object->typent= $arr[$object->typent_code]; @@ -2183,6 +2187,26 @@ else print '
    '; print '
    '; if ((!$object->code_client || $object->code_client == -1) && $modCodeClient->code_auto) @@ -1656,9 +1659,9 @@ else // Phone / Fax print '
    '.fieldLabel('Phone','phone').''.fieldLabel('Fax','fax').'
    '.fieldLabel('VATIsUsed','assujtva_value').''; + // VAT is used + print '
    '.fieldLabel('VATIsUsed','assujtva_value').''; print $form->selectyesno('assujtva_value',$object->tva_assuj,1); print '
    '.fieldLabel($langs->transcountry("LocalTax1IsUsed",$mysoc->country_code),'localtax1assuj_value').''; + print $form->selectyesno('localtax1assuj_value',$object->localtax1_assuj,1); + if(! isOnlyOneLocalTax(1)) + { + print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; + $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); + print ''; + } + + print ''.fieldLabel($langs->transcountry("LocalTax2IsUsed",$mysoc->country_code),'localtax2assuj_value').''; + print $form->selectyesno('localtax2assuj_value',$object->localtax2_assuj,1); + if (! isOnlyOneLocalTax(2)) + { + print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; + $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); + print ''; + } + print '
    '.fieldLabel($langs->transcountry("LocalTax1IsUsed",$mysoc->country_code),'localtax1assuj_value').''; + print $form->selectyesno('localtax1assuj_value',$object->localtax1_assuj,1); + if(! isOnlyOneLocalTax(1)) + { + print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; + $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); + print ''; + } + print '
    '.fieldLabel($langs->transcountry("LocalTax2IsUsed",$mysoc->country_code),'localtax2assuj_value').''; + print $form->selectyesno('localtax2assuj_value',$object->localtax2_assuj,1); + if(! isOnlyOneLocalTax(2)) + { + print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; + $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); + print ''; + } + print '
    '.fieldLabel('VATIntra','intra_vat').''; - $s =''; + print ''; + $s =''; if (empty($conf->global->MAIN_DISABLEVATCHECK)) { @@ -1721,56 +1774,6 @@ else print '
    '.fieldLabel($langs->transcountry("LocalTax1IsUsed",$mysoc->country_code),'localtax1assuj_value').''; - print $form->selectyesno('localtax1assuj_value',$object->localtax1_assuj,1); - if(! isOnlyOneLocalTax(1)) - { - print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; - $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); - print ''; - } - - print ''.fieldLabel($langs->transcountry("LocalTax2IsUsed",$mysoc->country_code),'localtax2assuj_value').''; - print $form->selectyesno('localtax2assuj_value',$object->localtax2_assuj,1); - if (! isOnlyOneLocalTax(2)) - { - print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; - $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); - print ''; - } - print '
    '.fieldLabel($langs->transcountry("LocalTax1IsUsed",$mysoc->country_code),'localtax1assuj_value').''; - print $form->selectyesno('localtax1assuj_value',$object->localtax1_assuj,1); - if(! isOnlyOneLocalTax(1)) - { - print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; - $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); - print ''; - } - print '
    '.fieldLabel($langs->transcountry("LocalTax2IsUsed",$mysoc->country_code),'localtax2assuj_value').''; - print $form->selectyesno('localtax2assuj_value',$object->localtax2_assuj,1); - if(! isOnlyOneLocalTax(2)) - { - print ' '.$langs->transcountry("Type",$mysoc->country_code).': '; - $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); - print ''; - } - print '
    '.fieldLabel('ThirdPartyType','typent_id').''; print $form->selectarray("typent_id",$formcompany->typent_array(0), $object->typent_id, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); @@ -1929,7 +1932,7 @@ else ) ); - print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id, $langs->trans("MergeThirdparties"), $langs->trans("ConfirmMergeThirdparties"), "confirm_merge", $formquestion, 'no', 1, 190); + print $form->formconfirm($_SERVER["PHP_SELF"]."?socid=".$object->id, $langs->trans("MergeThirdparties"), $langs->trans("ConfirmMergeThirdparties"), "confirm_merge", $formquestion, 'no', 1, 200); } dol_htmloutput_errors($error,$errors); @@ -2025,7 +2028,7 @@ else } //if ($j % 2 == 1) print '
    '; print $langs->trans('VATIsUsed'); print ''; @@ -2033,6 +2036,104 @@ else print '
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; + print yn($object->localtax1_assuj); + print '
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; + print yn($object->localtax2_assuj); + print '
    '.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).' id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; + $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); + print ''.$object->localtax1_value.'
    '.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).'id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; + $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); + print ''.$object->localtax2_value.'
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; + print yn($object->localtax1_assuj); + print '
    '.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).'id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; + $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); + print ''.$object->localtax1_value.'
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; + print yn($object->localtax2_assuj); + print '
    '.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).' id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; + $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); + print ''.$object->localtax2_value.'
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; + print yn($object->localtax2_assuj); + print '
    '.$langs->trans('VATIntra').''; @@ -2040,7 +2141,7 @@ else { $s=''; $s.=$object->tva_intra; - $s.=''; + $s.=''; if (empty($conf->global->MAIN_DISABLEVATCHECK)) { @@ -2072,103 +2173,6 @@ else print '
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; - print yn($object->localtax1_assuj); - print '
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; - print yn($object->localtax2_assuj); - print '
    '.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).' id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; - $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); - print ''.$object->localtax1_value.'
    '.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).'id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; - $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); - print ''.$object->localtax2_value.'
    '.$langs->transcountry("LocalTax1IsUsed",$mysoc->country_code).''; - print yn($object->localtax1_assuj); - print '
    '.$langs->transcountry("TypeLocaltax1", $mysoc->country_code).'id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; - $formcompany->select_localtax(1,$object->localtax1_value, "lt1"); - print ''.$object->localtax1_value.'
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; - print yn($object->localtax2_assuj); - print '
    '.$langs->transcountry("TypeLocaltax2", $mysoc->country_code).' id.'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; - $formcompany->select_localtax(2,$object->localtax2_value, "lt2"); - print ''.$object->localtax2_value.'
    '.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; - print yn($object->localtax2_assuj); - print '
    '; + // Tags / categories + if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) + { + // Customer + if ($object->prospect || $object->client) { + print ''; + print '"; + } + + // Supplier + if ($object->fournisseur) { + print ''; + print '"; + } + } + // Legal print ''; @@ -2205,26 +2229,6 @@ else print ''; } - // Tags / categories - if (! empty($conf->categorie->enabled) && ! empty($user->rights->categorie->lire)) - { - // Customer - if ($object->prospect || $object->client) { - print ''; - print '"; - } - - // Supplier - if ($object->fournisseur) { - print ''; - print '"; - } - } - // Incoterms if (!empty($conf->incoterm->enabled)) { @@ -2267,22 +2271,6 @@ else print $object->showOptionals($extrafields); } - // Ban - if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) - { - print ''; - print ''; - } - // Parent company if (empty($conf->global->SOCIETE_DISABLE_PARENTCOMPANY)) { @@ -2434,10 +2422,12 @@ else 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 = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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='thi'.$object->id; if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { @@ -2555,7 +2545,6 @@ else } } } - } diff --git a/htdocs/societe/societecontact.php b/htdocs/societe/societecontact.php index 69298f263e8..876c383031a 100644 --- a/htdocs/societe/societecontact.php +++ b/htdocs/societe/societecontact.php @@ -149,7 +149,9 @@ if ($id > 0 || ! empty($ref)) print ''; print ''; - dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'socid', $linkback, ($user->societe_id?0:1), 'rowid', 'nom'); print '
    '; @@ -211,7 +213,7 @@ if ($id > 0 || ! empty($ref)) $sql = "SELECT d.rowid, d.login, d.lastname, d.firstname, d.societe as company, d.fk_soc,"; $sql.= " d.datefin,"; $sql.= " d.email, d.fk_adherent_type as type_id, d.morphy, d.statut,"; - $sql.= " t.libelle as type, t.cotisation"; + $sql.= " t.libelle as type, t.subscription"; $sql.= " FROM ".MAIN_DB_PREFIX."adherent as d"; $sql.= ", ".MAIN_DB_PREFIX."adherent_type as t"; $sql.= " WHERE d.fk_soc=".$id; @@ -290,7 +292,7 @@ if ($id > 0 || ! empty($ref)) // Statut print '
    "; // End of subscription date @@ -306,7 +308,7 @@ if ($id > 0 || ! empty($ref)) else { print '
    ' . $langs->trans("CustomersCategoriesShort") . ''; + print $form->showCategories($object->id, 'customer', 1); + print "
    ' . $langs->trans("SuppliersCategoriesShort") . ''; + print $form->showCategories($object->id, 'supplier', 1); + print "
    '.$langs->trans('JuridicalStatus').''.$object->forme_juridique.'
    ' . $langs->trans("CustomersCategoriesShort") . ''; - print $form->showCategories($object->id, 'customer', 1); - print "
    ' . $langs->trans("SuppliersCategoriesShort") . ''; - print $form->showCategories($object->id, 'supplier', 1); - print "
    '; - print '
    '; - print $langs->trans('RIB'); - print ''; - if ($user->rights->societe->creer) print ''.img_edit().''; - else print ' '; - print '
    '; - print '
    '; - print $object->display_rib(); - print '
    '; - print $memberstatic->LibStatut($objp->statut,$objp->cotisation,$datefin,2); + print $memberstatic->LibStatut($objp->statut,$objp->subscription,$datefin,2); print "'; - if ($objp->cotisation == 'yes') + if ($objp->subscription == 'yes') { print $langs->trans("SubscriptionNotReceived"); if ($objp->statut > 0) print " ".img_warning(); diff --git a/htdocs/supplier_proposal/card.php b/htdocs/supplier_proposal/card.php index 30700695b00..3ab1c159545 100644 --- a/htdocs/supplier_proposal/card.php +++ b/htdocs/supplier_proposal/card.php @@ -25,10 +25,15 @@ * along with this program. If not, see . */ +/** + * \file htdocs/supplier_proposal/card.php + * \ingroup supplier_proposal + * \brief Card supplier proposal + */ + require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT . '/core/class/html.formsupplier_proposal.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php'; require_once DOL_DOCUMENT_ROOT . '/supplier_proposal/class/supplier_proposal.class.php'; require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; @@ -96,6 +101,8 @@ if ($id > 0 || ! empty($ref)) { $hookmanager->initHooks(array('supplier_proposalcard','globalcard')); $permissionnote = $user->rights->supplier_proposal->creer; // Used by the include of actions_setnotes.inc.php +$permissiondellink=$user->rights->supplier_proposal->creer; // Used by the include of actions_dellink.inc.php +$permissiontoedit=$user->rights->supplier_proposal->creer; // Used by the include of actions_lineupdown.inc.php /* @@ -282,16 +289,6 @@ if (empty($reshook)) $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); } - for($i = 1; $i <= $conf->global->PRODUCT_SHOW_WHEN_CREATE; $i ++) - { - if ($_POST['idprod' . $i]) { - $xid = 'idprod' . $i; - $xqty = 'qty' . $i; - $xremise = 'remise' . $i; - $object->add_product($_POST[$xid], $_POST[$xqty], $_POST[$xremise]); - } - } - // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels, $object); if ($ret < 0) { @@ -354,10 +351,10 @@ if (empty($reshook)) // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) { $lines[$i]->fetch_optionals($lines[$i]->rowid); - $array_option = $lines[$i]->array_options; + $array_options = $lines[$i]->array_options; } - $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, 'HT', 0, $lines[$i]->info_bits, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_option); + $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, 'HT', 0, $lines[$i]->info_bits, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options); if ($result > 0) { $lineid = $result; @@ -477,6 +474,7 @@ if (empty($reshook)) $trigger_name='SUPPLIER_PROPOSAL_SENTBYMAIL'; $paramname='id'; $mode='emailfromsupplierproposal'; + $trackid='spr'.$object->id; include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; @@ -511,22 +509,28 @@ if (empty($reshook)) } } - // Add line - else if ($action == 'addline' && $user->rights->supplier_proposal->creer) { + // Add a product line + if ($action == 'addline' && $user->rights->supplier_proposal->creer) + { + $langs->load('errors'); + $error = 0; // Set if we used free entry or predefined product $predef=''; $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); - $price_ht = GETPOST('price_ht'); - + $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 (GETPOST('prod_entry_mode') == 'free') { $idprod=0; + $price_ht = GETPOST('price_ht'); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { $idprod=GETPOST('idprod', 'int'); + $price_ht = ''; $tva_tx = ''; } @@ -536,7 +540,7 @@ if (empty($reshook)) // Extrafields $extrafieldsline = new ExtraFields($db); $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); // Unset extrafield if (is_array($extralabelsline)) { // Get extra fields @@ -559,8 +563,7 @@ if (empty($reshook)) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); $error ++; } - - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) { + if (! $error && ($qty >= 0)) { $pu_ht = 0; $pu_ttc = 0; $price_min = 0; @@ -571,150 +574,140 @@ if (empty($reshook)) // Ecrase $pu par celui du produit // Ecrase $desc par celui du produit // Ecrase $txtva par celui du produit - if (! empty($idprod)) { - $prod = new Product($db); - $prod->fetch($idprod); + if ((GETPOST('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_PROPOSAL_WITH_NOPRICEDEFINED)) + { + $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)) + { + $idprod=$reg[1]; + $res=$productsupplier->fetch($idprod); + // Call to init properties of $productsupplier + // 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) + { + //$idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qty); // Just to see if a price exists for the quantity. Not used to found vat. + $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), -1); // We force qty to -1 to be sure to find if a supplier price exist + $res=$productsupplier->fetch($idprod); + } + + if ($idprod > 0) + { + $pu_ht = $productsupplier->fourn_pu; + $price_base_type = $productsupplier->fourn_price_base_type; + $type = $productsupplier->type; + $label = $productsupplier->label; + $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, 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); - $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); + $result=$object->addline( + $desc, + $pu_ht, + $qty, + $tva_tx, + $localtax1_tx, + $localtax2_tx, + $productsupplier->id, + $remise_percent, + $price_base_type, + $pu_ttc, + $tva_npr, + $type, + -1, + 0, + GETPOST('fk_parent_line'), + $fournprice, + $buyingprice, + $label, + $array_options, + $ref_fourn + ); + //var_dump($tva_tx);var_dump($productsupplier->fourn_pu);var_dump($price_base_type);exit; + } + 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((GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='') && empty($error)) // Free product + { + $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); + $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); + $desc = $product_desc; + $type = GETPOST('type'); - // If prices fields are update - $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; - - //On garde le prix indiqué dans l'input pour la demande de prix fournisseur - //$pu_ht = $prod->price; - $pu_ht = price2num($price_ht, 'MU'); - //$pu_ttc = $prod->price_ttc; - $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU'); - - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; - - // On defini prix unitaire - if (! empty($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]; - 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]; - } - elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { - require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; - - $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; - $prod->tva_tx = $prodcustprice->lines [0]->tva_tx; - } - } - } - - // if price ht is forced (ie: calculated by margin rate and cost price) - if (! empty($price_ht)) { - $pu_ht = price2num($price_ht, 'MU'); - $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 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 ($tva_tx != $prod->tva_tx) { - if ($price_base_type != 'HT') { - $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); - } else { - $pu_ttc = price2num($pu_ht * (1 + ($tva_tx / 100)), 'MU'); - } - } - - $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')) - $newlang = GETPOST('lang_id'); - 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 = 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); - } - - $type = $prod->type; - } 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); - $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); - $desc = $product_desc; - $type = GETPOST('type'); + $fk_unit= GETPOST('units', 'alpha'); + + $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); + + 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'; + } + + $result = $object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $ttc, $info_bits, $type, - 1, 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, $ref_fourn); + //$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); } - // Margin - $fournprice = (GETPOST('fournprice' . $predef) ? GETPOST('fournprice' . $predef) : ''); - $buyingprice = (GETPOST('buying_price' . $predef) ? GETPOST('buying_price' . $predef) : ''); - // Local Taxes - $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty); - $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty); - - $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 - $ref_fourn = GETPOST('fourn_ref'); - $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $pu_ttc, $info_bits, $type, - 1, 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_option, $ref_fourn); - - if ($result > 0) { + if (! $error && $result > 0) + { $db->commit(); - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - // Define output language + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } + $model=$object->modelpdf; $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); } unset($_POST['prod_entry_mode']); @@ -722,18 +715,23 @@ if (empty($reshook)) 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($_POST['product_ref']); unset($_POST['product_label']); unset($_POST['product_desc']); unset($_POST['fournprice']); unset($_POST['buying_price']); + unset($localtax1_tx); + unset($localtax2_tx); unset($_POST['np_marginRate']); unset($_POST['np_markRate']); unset($_POST['dp_desc']); + unset($_POST['idprodfournprice']); unset($_POST['idprod']); unset($_POST['date_starthour']); @@ -748,12 +746,14 @@ if (empty($reshook)) unset($_POST['date_endday']); unset($_POST['date_endmonth']); unset($_POST['date_endyear']); - } else { - $db->rollback(); + } + else + { + $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } + setEventMessages($object->error, $object->errors, 'errors'); } + //} } } @@ -781,7 +781,7 @@ if (empty($reshook)) // Extrafields $extrafieldsline = new ExtraFields($db); $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); - $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline); // Unset extrafield if (is_array($extralabelsline)) { // Get extra fields @@ -826,7 +826,7 @@ if (empty($reshook)) if (! $error) { $db->begin(); $ref_fourn = GETPOST('fourn_ref'); - $result = $object->updateline(GETPOST('lineid'), $pu_ht, GETPOST('qty'), GETPOST('remise_percent'), $vat_rate, $localtax1_rate, $localtax2_rate, $description, 'HT', $info_bits, $special_code, GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $type, $array_option, $ref_fourn); + $result = $object->updateline(GETPOST('lineid'), $pu_ht, GETPOST('qty'), GETPOST('remise_percent'), $vat_rate, $localtax1_rate, $localtax2_rate, $description, 'HT', $info_bits, $special_code, GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $type, $array_options, $ref_fourn); if ($result >= 0) { $db->commit(); @@ -996,9 +996,9 @@ llxHeader('', $langs->trans('CommRequests'), 'EN:Ask_Price_Supplier|FR:Demande_d $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); -$formsupplier_proposal = new FormSupplierProposal($db); $formmargin = new FormMargin($db); $companystatic = new Societe($db); +if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } $now = dol_now(); @@ -1207,9 +1207,10 @@ if ($action == 'create') if (empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) print ''; - if (! empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE) || ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) print '
    '; if (! empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) { + print '
    '; + // For backward compatibility print ''; print ''; @@ -1242,42 +1243,11 @@ if ($action == 'create') } print ''; - if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) - print ''; - print ''; print ''; } - if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) - { - print ''; - } - if (! empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE) || ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) print '
     
    ' . $langs->trans("CreateEmptyAsk") . '
    '; - if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) { - $lib = $langs->trans("ProductsAndServices"); - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - for($i = 1; $i <= $conf->global->PRODUCT_SHOW_WHEN_CREATE; $i ++) { - print ''; - print ''; - print ''; - print ''; - } - print "
    ' . $lib . '' . $langs->trans("Qty") . '' . $langs->trans("ReductionShort") . '
    '; - // multiprix - if ($conf->global->PRODUIT_MULTIPRICES && $soc->price_level) - $form->select_produits('', "idprod" . $i, '', $conf->product->limit_size, $soc->price_level); - else - $form->select_produits('', "idprod" . $i, '', $conf->product->limit_size); - print '%
    "; - } - print '
    '; + if (! empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) print '
    '; dol_fiche_end(); @@ -1383,11 +1353,63 @@ if ($action == 'create') // Print form confirm print $formconfirm; + + // Supplier proposal card + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
    '; + // Ref supplier + //$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', 0, 1); + //$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->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->supplier_proposal->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); + + + print '
    '; + print '
    '; + print '
    '; + print ''; - $linkback = '' . $langs->trans("BackToList") . ''; - // Ref + /* print ''; @@ -1395,9 +1417,10 @@ if ($action == 'create') // Company print ''; print ''; - + */ + // Payment term - print ''; - } else { - print ''; - } - } - print ''; - } - // Multicurrency if (! empty($conf->multicurrency->enabled)) { @@ -1559,73 +1548,77 @@ if ($action == 'create') // Other attributes $cols = 2; - if (empty($conf->margin->enabled)) $cols++; - include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - // Amount HT - print ''; - print ''; + print '
    ' . $langs->trans('Ref') . ''; print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); print '
    ' . $langs->trans('Supplier') . '' . $soc->getNomUrl(1) . '
    '; + print '
    '; print ''; @@ -1453,40 +1476,6 @@ if ($action == 'create') } print ''; - // Project - if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - print ''; - } else { - print '
    '; print $langs->trans('PaymentConditionsShort'); print '
    '; - print ''; - if ($user->rights->supplier_proposal->creer) { - if ($action != 'classify') - print ''; - print '
    '; - print $langs->trans('Project') . '' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '
    '; - print '
    '; - if ($action == 'classify') { - $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid'); - } else { - $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none'); - } - print '
    '; - if (! empty($object->fk_project)) { - print '
    '; - $proj = new Project($db); - $proj->fetch($object->fk_project); - print ''; - print $proj->ref; - print ''; - print ' 
    ' . $langs->trans('AmountHT') . '' . price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency) . '
    '; + + print '
    '; + print '
    '; + print '
    '; + print '
    '; + + print ''; + + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) + { + // Multicurrency Amount HT + print ''; + print ''; + print ''; - // Margin Infos - if (! empty($conf->margin->enabled)) { - $rowspan=4; - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) $rowspan++; - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) $rowspan++; - if (!empty($conf->multicurrency->enabled)) $rowspan+=3; - print ''; + // Multicurrency Amount VAT + print ''; + print ''; + print ''; + + // Multicurrency Amount TTC + print ''; + print ''; + print ''; } + + // Amount HT + print ''; + print ''; print ''; // Amount VAT - print ''; - print ''; + print ''; + print ''; print ''; // Amount Local Taxes if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { - print ''; - print ''; + print ''; + print ''; print ''; } if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 { print ''; - print ''; + print ''; print ''; } // Amount TTC print ''; - print ''; + print ''; print ''; - if (!empty($conf->multicurrency->enabled)) - { - // Multicurrency Amount HT - print ''; - print ''; - print ''; - - // Multicurrency Amount VAT - print ''; - print ''; - print ''; - - // Multicurrency Amount TTC - print ''; - print ''; - print ''; - } - - // Statut - 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)) . '
    '; - $formmargin->displayMarginInfos($object); - print '
    ' . 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)) . '
    ' . $langs->trans('AmountHT') . '' . price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountVAT') . '' . price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountVAT') . '' . price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
    ' . $langs->trans('AmountTTC') . '' . price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency) . '' . price($object->total_ttc, '', $langs, 0, - 1, - 1, $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('MulticurrencyAmountTTC','multicurrency_total_ttc') . '' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '
    ' . $langs->trans('Status') . '' . $object->getLibStatut(4) . '

    '; + print '
    '; + + // Margin Infos + /*if (! empty($conf->margin->enabled)) { + $formmargin->displayMarginInfos($object); + }*/ + print ''; + print ''; + print ''; + + print '

    '; + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); @@ -1658,8 +1651,12 @@ if ($action == 'create') print ''; + // Add free products/services form + global $forceall, $senderissupplier, $dateSelector; + $forceall=1; $senderissupplier=2; $dateSelector=0; // $senderissupplier=2 is same than 1 but disable test on minimum qty. + if (! empty($object->lines)) - $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1); + $ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, 1); // Form to add new line if ($object->statut == 0 && $user->rights->supplier_proposal->creer) @@ -1669,7 +1666,7 @@ if ($action == 'create') $var = true; // Add products/services form - $object->formAddObjectLine(1, $mysoc, $soc); + $object->formAddObjectLine(1, $soc, $mysoc); $parameters = array(); $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook @@ -1803,7 +1800,7 @@ if ($action == 'create') $var = true; - $somethingshown = $formfile->show_documents('supplier_proposal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + print $formfile->showdocuments('supplier_proposal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); // Show links to link elements @@ -1873,10 +1870,12 @@ if ($action == 'create') 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 = 'user'; - $formmail->fromid = $user->id; - $formmail->fromname = $user->getFullName($langs); - $formmail->frommail = $user->email; + $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='spr'.$object->id; if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set { diff --git a/htdocs/supplier_proposal/class/supplier_proposal.class.php b/htdocs/supplier_proposal/class/supplier_proposal.class.php index 09fa2dc69e9..1d249ad627d 100644 --- a/htdocs/supplier_proposal/class/supplier_proposal.class.php +++ b/htdocs/supplier_proposal/class/supplier_proposal.class.php @@ -48,7 +48,8 @@ class SupplierProposal extends CommonObject public $table_element_line='supplier_proposaldet'; public $fk_element='fk_supplier_proposal'; protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe - + public $picto='propal'; + /** * {@inheritdoc} */ @@ -727,7 +728,7 @@ class SupplierProposal extends CommonObject * this->ref can be set or empty. If empty, we will use "(PROVid)" * * @param User $user User that create - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >=0 if OK */ function create($user, $notrigger=0) @@ -926,7 +927,7 @@ class SupplierProposal extends CommonObject if (! $notrigger) { // Call trigger - $result=$this->call_trigger('SUPPLIER_PROPOSAL_CREATE',$user); + $result=$this->call_trigger('PROPAL_SUPPLIER_CREATE',$user); if ($result < 0) { $error++; } // End call triggers } @@ -1334,7 +1335,7 @@ class SupplierProposal extends CommonObject * Set status to validated * * @param User $user Object user that validate - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >=0 if OK */ function valid($user, $notrigger=0) @@ -1542,7 +1543,7 @@ class SupplierProposal 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= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function reopen($user, $statut, $note='', $notrigger=0) @@ -1890,7 +1891,7 @@ class SupplierProposal extends CommonObject * Delete askprice * * @param User $user Object user that delete - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int 1 if ok, otherwise if error */ function delete($user, $notrigger=0) @@ -2094,11 +2095,12 @@ class SupplierProposal extends CommonObject if ($mode == 0) return $this->labelstatut[$statut]; if ($mode == 1) return $this->labelstatut_short[$statut]; - if ($mode == 2) return img_picto($this->labelstatut_short[$statut], $statuttrans).' '.$this->labelstatut_short[$statut]; + if ($mode == 2) return img_picto($this->labelstatut[$statut], $statuttrans).' '.$this->labelstatut_short[$statut]; if ($mode == 3) return img_picto($this->labelstatut[$statut], $statuttrans); if ($mode == 4) return img_picto($this->labelstatut[$statut],$statuttrans).' '.$this->labelstatut[$statut]; - if ($mode == 5) return ''.$this->labelstatut_short[$statut].' '.img_picto($this->labelstatut_short[$statut],$statuttrans); - } + if ($mode == 5) return ''.$this->labelstatut_short[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); + if ($mode == 6) return ''.$this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],$statuttrans); + } /** @@ -2367,31 +2369,60 @@ class SupplierProposal extends CommonObject * @param int $withpicto Add picto into link * @param string $option Where point the link ('compta', 'expedition', 'document', ...) * @param string $get_params Parametres added to url + * @param int $notooltip 1=Disable tooltip * @return string String with URL */ - function getNomUrl($withpicto=0,$option='', $get_params='') + function getNomUrl($withpicto=0,$option='', $get_params='', $notooltip=0) { - global $langs; + global $langs, $conf, $user; + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $url=''; $result=''; - $label=$langs->trans("ShowSupplierProposal").': '.$this->ref; - $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; + + $label=''.$langs->trans("ShowSupplierProposal").''; + if (! empty($this->ref)) + $label.= '
    '.$langs->trans('Ref').': '.$this->ref; + if (! empty($this->ref_fourn)) + $label.= '
    '.$langs->trans('RefSupplier').': '.$this->ref_fourn; + if (! empty($this->total_ht)) + $label.= '
    ' . $langs->trans('AmountHT') . ': ' . price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_tva)) + $label.= '
    ' . $langs->trans('VAT') . ': ' . price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + if (! empty($this->total_ttc)) + $label.= '
    ' . $langs->trans('AmountTTC') . ': ' . price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); if ($option == '') { - $link = 'rights->propal->lire) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowSupplierProposal"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } + + $linkstart = ''; $linkend=''; $picto='supplier_proposal'; if ($withpicto) - $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + $result.=($linkstart.img_object(($notooltip?'':$label), $picto, ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto && $withpicto != 2) $result.=' '; - $result.=$link.$this->ref.$linkend; + $result.=$linkstart.$this->ref.$linkend; return $result; } @@ -2724,7 +2755,7 @@ class SupplierProposalLine extends CommonObject /** * Insert object line propal in database * - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if KO, >0 if OK */ function insert($notrigger=0) @@ -2906,7 +2937,7 @@ class SupplierProposalLine extends CommonObject /** * Update propal line object into DB * - * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <0 if ko, >0 if ok */ function update($notrigger=0) diff --git a/htdocs/supplier_proposal/document.php b/htdocs/supplier_proposal/document.php index 77844225720..d8c51a45152 100644 --- a/htdocs/supplier_proposal/document.php +++ b/htdocs/supplier_proposal/document.php @@ -115,6 +115,7 @@ if ($object->id > 0) $modulepart = 'supplier_proposal'; $permission = $user->rights->supplier_proposal->creer; + $permtoedit = $user->rights->supplier_proposal->creer; $param = '&id=' . $object->id; include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; } diff --git a/htdocs/supplier_proposal/list.php b/htdocs/supplier_proposal/list.php index c17cf9f8757..a50e8509ba5 100644 --- a/htdocs/supplier_proposal/list.php +++ b/htdocs/supplier_proposal/list.php @@ -9,7 +9,8 @@ * Copyright (C) 2010-2011 Philippe Grand * Copyright (C) 2012 Christophe Battarel * Copyright (C) 2013 Cédric Salvador -* + * Copyright (C) 2016 Ferran Marcet + * * 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 @@ -33,8 +34,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsupplier_proposal.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formpropal.class.php'; require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; @@ -190,7 +191,7 @@ llxHeader('',$langs->trans('CommRequest'),'EN:Ask_Price_Supplier|FR:Demande_de_p $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); -$formsupplier_proposal = new FormSupplierProposal($db); +$formpropal = new FormPropal($db); $companystatic=new Societe($db); $now=dol_now(); @@ -281,6 +282,7 @@ if ($result) $param='&socid='.$socid.'&viewstatut='.$viewstatut; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if ($sall) $param.='&sall='.$sall; if ($month) $param.='&month='.$month; if ($year) $param.='&year='.$year; if ($search_ref) $param.='&search_ref=' .$search_ref; @@ -386,7 +388,7 @@ if ($result) print ''; print ''; print ''; // Check boxes print '"; print ''; + // Payment term + print ''; + print ''; print ''; diff --git a/htdocs/theme/eldy/ckeditor/config.js b/htdocs/theme/eldy/ckeditor/config.js index f01fde4dabb..eb88af48a04 100644 --- a/htdocs/theme/eldy/ckeditor/config.js +++ b/htdocs/theme/eldy/ckeditor/config.js @@ -39,17 +39,17 @@ CKEDITOR.editorConfig = function( config ) ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['BidiLtr', 'BidiRtl'], ['Link','Unlink','Anchor'], - ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'], + ['Image','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'], ['Styles','Format','Font','FontSize'], ['TextColor','BGColor'], - ['Maximize', 'ShowBlocks','-','About'] + ['Maximize', 'ShowBlocks'] ]; // Used for mailing fields config.toolbar_dolibarr_mailings = [ ['Source','Maximize','Preview'], - ['Cut','Copy','Paste','-','SpellChecker'], + ['Cut','Copy','Paste','-','SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace'], ['Format','Font','FontSize'], ['Bold','Italic','Underline','Strike','Subscript','Superscript','-','TextColor','RemoveFormat'], @@ -62,7 +62,7 @@ CKEDITOR.editorConfig = function( config ) config.toolbar_dolibarr_notes = [ ['Source','Maximize'], - ['Cut','Copy','Paste','-','SpellChecker'], + ['Cut','Copy','Paste','-','SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace'], ['Format','Font','FontSize'], ['Bold','Italic','Underline','Strike','Subscript','Superscript','-','TextColor','RemoveFormat'], @@ -75,7 +75,7 @@ CKEDITOR.editorConfig = function( config ) config.toolbar_dolibarr_details = [ ['Source','Maximize'], - ['Cut','Copy','Paste','-','SpellChecker'], + ['Cut','Copy','Paste','-','SpellChecker', 'Scayt'], ['Format','Font','FontSize'], ['Bold','Italic','Underline','Strike','Subscript','Superscript','-','TextColor','RemoveFormat'], ['NumberedList','BulletedList','Outdent','Indent'], diff --git a/htdocs/theme/eldy/img/playdisabled.png b/htdocs/theme/eldy/img/playdisabled.png new file mode 100644 index 00000000000..1cf122679e2 Binary files /dev/null and b/htdocs/theme/eldy/img/playdisabled.png differ diff --git a/htdocs/theme/eldy/img/preview.png b/htdocs/theme/eldy/img/preview.png new file mode 100644 index 00000000000..9040bf963f7 Binary files /dev/null and b/htdocs/theme/eldy/img/preview.png differ diff --git a/htdocs/theme/eldy/img/preview_ext.png b/htdocs/theme/eldy/img/preview_ext.png new file mode 100644 index 00000000000..8bf0c65a7c0 Binary files /dev/null and b/htdocs/theme/eldy/img/preview_ext.png differ diff --git a/htdocs/theme/eldy/img/statut0.png b/htdocs/theme/eldy/img/statut0.png index d11252783a4..f5fce354236 100644 Binary files a/htdocs/theme/eldy/img/statut0.png and b/htdocs/theme/eldy/img/statut0.png differ diff --git a/htdocs/theme/eldy/img/statut0_40x40.png b/htdocs/theme/eldy/img/statut0_40x40.png new file mode 100644 index 00000000000..591aac8e9de Binary files /dev/null and b/htdocs/theme/eldy/img/statut0_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut1.png b/htdocs/theme/eldy/img/statut1.png index 88f3b3c53a0..87b09403e68 100644 Binary files a/htdocs/theme/eldy/img/statut1.png and b/htdocs/theme/eldy/img/statut1.png differ diff --git a/htdocs/theme/eldy/img/statut1_40x40.png b/htdocs/theme/eldy/img/statut1_40x40.png new file mode 100644 index 00000000000..6def06ceaff Binary files /dev/null and b/htdocs/theme/eldy/img/statut1_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut2.png b/htdocs/theme/eldy/img/statut2.png deleted file mode 100644 index ad5a7084474..00000000000 Binary files a/htdocs/theme/eldy/img/statut2.png and /dev/null differ diff --git a/htdocs/theme/eldy/img/statut3.png b/htdocs/theme/eldy/img/statut3.png index e7515796683..bf4f7b8e854 100644 Binary files a/htdocs/theme/eldy/img/statut3.png and b/htdocs/theme/eldy/img/statut3.png differ diff --git a/htdocs/theme/eldy/img/statut3_40x40.png b/htdocs/theme/eldy/img/statut3_40x40.png new file mode 100644 index 00000000000..f71ef4eb962 Binary files /dev/null and b/htdocs/theme/eldy/img/statut3_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut4.png b/htdocs/theme/eldy/img/statut4.png index 6dc05edeba7..7a680ad2b2d 100644 Binary files a/htdocs/theme/eldy/img/statut4.png and b/htdocs/theme/eldy/img/statut4.png differ diff --git a/htdocs/theme/eldy/img/statut4_40x40.png b/htdocs/theme/eldy/img/statut4_40x40.png new file mode 100644 index 00000000000..2da24b66484 Binary files /dev/null and b/htdocs/theme/eldy/img/statut4_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut5.png b/htdocs/theme/eldy/img/statut5.png index 53264a0515d..98bb941a0e5 100644 Binary files a/htdocs/theme/eldy/img/statut5.png and b/htdocs/theme/eldy/img/statut5.png differ diff --git a/htdocs/theme/eldy/img/statut5_40x40.png b/htdocs/theme/eldy/img/statut5_40x40.png new file mode 100644 index 00000000000..7cac0ad23ee Binary files /dev/null and b/htdocs/theme/eldy/img/statut5_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut6.png b/htdocs/theme/eldy/img/statut6.png index c76ab86fe60..fe93f1a0bcc 100644 Binary files a/htdocs/theme/eldy/img/statut6.png and b/htdocs/theme/eldy/img/statut6.png differ diff --git a/htdocs/theme/eldy/img/statut6_40x40.png b/htdocs/theme/eldy/img/statut6_40x40.png new file mode 100644 index 00000000000..0b847c322e2 Binary files /dev/null and b/htdocs/theme/eldy/img/statut6_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut7.png b/htdocs/theme/eldy/img/statut7.png index 8871a45519f..77476349d6d 100644 Binary files a/htdocs/theme/eldy/img/statut7.png and b/htdocs/theme/eldy/img/statut7.png differ diff --git a/htdocs/theme/eldy/img/statut7_40x40.png b/htdocs/theme/eldy/img/statut7_40x40.png new file mode 100644 index 00000000000..48314ccb183 Binary files /dev/null and b/htdocs/theme/eldy/img/statut7_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut8.png b/htdocs/theme/eldy/img/statut8.png index c24d4a9dac2..2627aab8710 100644 Binary files a/htdocs/theme/eldy/img/statut8.png and b/htdocs/theme/eldy/img/statut8.png differ diff --git a/htdocs/theme/eldy/img/statut8_40x40.png b/htdocs/theme/eldy/img/statut8_40x40.png new file mode 100644 index 00000000000..0546ac2c773 Binary files /dev/null and b/htdocs/theme/eldy/img/statut8_40x40.png differ diff --git a/htdocs/theme/eldy/img/statut9.png b/htdocs/theme/eldy/img/statut9.png index 9aa2ae34620..e5304dd791b 100644 Binary files a/htdocs/theme/eldy/img/statut9.png and b/htdocs/theme/eldy/img/statut9.png differ diff --git a/htdocs/theme/eldy/img/statut9_40x40.png b/htdocs/theme/eldy/img/statut9_40x40.png new file mode 100644 index 00000000000..445eac35387 Binary files /dev/null and b/htdocs/theme/eldy/img/statut9_40x40.png differ diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php index 43f4ddc70c4..6b540b7c2c5 100644 --- a/htdocs/theme/eldy/style.css.php +++ b/htdocs/theme/eldy/style.css.php @@ -101,6 +101,7 @@ $usegradienttop=(isset($conf->global->THEME_ELDY_TOPMENU_BACK1)?0:1); $usegradienttitle=(isset($conf->global->THEME_ELDY_BACKTITLE1)?0:1); $useboldtitle=(isset($conf->global->THEME_ELDY_USEBOLDTITLE)?$conf->global->THEME_ELDY_USEBOLDTITLE:1); $borderwith=2; +$noborderline=0; // Case of option always editable if (! isset($conf->global->THEME_ELDY_BACKBODY)) $conf->global->THEME_ELDY_BACKBODY=$colorbackbody; @@ -256,6 +257,10 @@ a.tab { font-weight: bold !important; } a:link, a:visited, a:hover, a:active { font-family: ; font-weight: normal; color: rgb(); text-decoration: none; } a:hover { text-decoration: underline; color: rgb(); } +input, input.flat, textarea, textarea.flat, form.flat select, select, select.flat, .dataTables_length label select { + background-color: #FFF; +} + input:focus, textarea:focus, button:focus, select:focus { @@ -269,14 +274,12 @@ textarea.cke_source:focus input, input.flat, textarea, textarea.flat, form.flat select, select, select.flat, .dataTables_length label select { font-size: px; font-family: ; - background: #FFF; - /* color: #111; */ border: 1px solid #C0C0C0; margin: 0px 0px 0px 0px; } input, textarea, select { - border-radius:4px; + border-radius: 2px; border:solid 1px rgba(0,0,0,.3); border-top:solid 1px rgba(0,0,0,.3); border-bottom:solid 1px rgba(0,0,0,.2); @@ -333,18 +336,19 @@ input.removedfile { textarea:disabled { background:#ddd; } +input[type=file ] { background-color: transparent; border-top: none; border-left: none; border-right: none; box-shadow: none; } input[type=checkbox] { background-color: transparent; border: none; box-shadow: none; } input[type=radio] { background-color: transparent; border: none; box-shadow: none; } input[type=image] { background-color: transparent; border: none; box-shadow: none; } -input[type=text] { min-width: 20px; } input:-webkit-autofill { background-color: !important; background-image:none !important; -webkit-box-shadow: 0 0 0 50px inset; } ::-webkit-input-placeholder { color:#ccc; } -::-moz-placeholder { color:#ccc; } /* firefox 19+ */ -:-ms-input-placeholder { color:#ccc; } /* ie */ +:-moz-placeholder { color:#bbb; } /* firefox 18- */ +::-moz-placeholder { color:#bbb; } /* firefox 19+ */ +:-ms-input-placeholder { color:#ccc; } /* ie */ input:-moz-placeholder { color:#ccc; } @@ -379,9 +383,9 @@ fieldset { border: 1px solid #AAAAAA !important; } filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border: 1px solid #bbbbbb; border-bottom-color: #a2a2a2; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + border-radius: 2px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); @@ -529,25 +533,14 @@ div.confirmmessage { div.myavailability { padding-top: 6px; } -/* Style to move picto into left of button */ -/* -.buttonactionview { - padding-left: 15px; -} -.pictoactionview { - padding-left: 10px; - margin-right: -24px; - z-index: 999999; -} -*/ .googlerefreshcal { padding-top: 4px; padding-bottom: 4px; } .checkallactions { vertical-align: top; - margin-top: 6px; - margin-left: 4px; + margin-top: 6px; + margin-left: 4px; } .selectlimit { margin-right: 10px !important; @@ -555,6 +548,7 @@ div.myavailability { .strikefordisabled { text-decoration: line-through; } +/* using a tdoverflowxxx make the min-with not working */ .tdoverflow { max-width: 0; overflow: hidden; @@ -580,6 +574,20 @@ div.myavailability { .tablelistofcalendars { margin-top: 25px !important; } +.amountalreadypaid { +} +.amountpaymentcomplete { + color: #008800; + font-weight: bold; +} +.amountremaintopay { + color: #880000; + font-weight: bold; +} +.savingdocmask { + margin-top: 6px; + margin-bottom: 12px; +} /* DOL_XXX for future usage (when left menu has been removed). If we do not use datatable */ .table-responsive { @@ -598,17 +606,22 @@ div.myavailability { .clearboth { clear:both; } .hideobject { display: none; } .minwidth50 { min-width: 50px; } -.minwidth100 { min-width: 100px; } -.minwidth200 { min-width: 200px; } -.minwidth300 { min-width: 300px; } -.minwidth400 { min-width: 400px; } -.minwidth500 { min-width: 500px; } -.minwidth50imp { min-width: 50px !important; } -.minwidth100imp { min-width: 100px !important; } -.minwidth200imp { min-width: 200px !important; } -.minwidth300imp { min-width: 300px !important; } -.minwidth400imp { min-width: 400px !important; } -.minwidth500imp { min-width: 500px !important; } +/* rule to reduce top menu - 3rd reduction */ +@media only screen and (min-width: px) +{ + .minwidth100 { min-width: 100px; } + .minwidth200 { min-width: 200px; } + .minwidth300 { min-width: 300px; } + .minwidth400 { min-width: 400px; } + .minwidth500 { min-width: 500px; } + .minwidth50imp { min-width: 50px !important; } + .minwidth100imp { min-width: 100px !important; } + .minwidth200imp { min-width: 200px !important; } + .minwidth300imp { min-width: 300px !important; } + .minwidth400imp { min-width: 400px !important; } + .minwidth500imp { min-width: 500px !important; } +} +.maxwidth50 { max-width: 50px; } .maxwidth100 { max-width: 100px; } .maxwidth150 { max-width: 150px; } .maxwidth200 { max-width: 200px; } @@ -617,10 +630,11 @@ div.myavailability { .maxwidth500 { max-width: 500px; } .minheight20 { min-height: 20px; } .minheight40 { min-height: 40px; } -.titlefield { width: 25%; } .titlefieldcreate { width: 20%; } +.titlefield { width: 25%; } +.titlefieldmiddle { width: 50%; } -/* Force values for small screen */ +/* Force values for small screen 1400 */ @media only screen and (max-width: 1400px) { .titlefield { width: 30% !important; } @@ -633,7 +647,8 @@ div.myavailability { .minwidth500imp { min-width: 300px !important; } } -@media only screen and (max-width: 960px) +/* Force values for small screen 1000 */ +@media only screen and (max-width: 1000px) { .maxwidthonsmartphone { max-width: 100px; } .minwidth50imp { min-width: 50px !important; } @@ -644,12 +659,26 @@ div.myavailability { .minwidth500imp { min-width: 100px !important; } } -/* Force values for small screen */ +/* Force values for small screen 570 */ @media only screen and (max-width: 570px) { + div.titre { + line-height: 2em; + } + + input[type=text], select, textarea { + min-width: 20px; + min-height: 1.4em; + line-height: 1.4em; + margin: .5em 0; + padding: .4em .1em; + border: 1px solid #BBB; + } + .hideonsmartphone { display: none; } .noenlargeonsmartphone { width : 50px !important; display: inline !important; } .maxwidthonsmartphone { max-width: 100px; } + .maxwidth50onsmartphone { max-width: 50px; } .maxwidth100onsmartphone { max-width: 100px; } .maxwidth150onsmartphone { max-width: 150px; } .maxwidth200onsmartphone { max-width: 200px; } @@ -812,7 +841,7 @@ div.ficheaddleft { else print "margin-top: 10px;\n"; ?> } /* Force values on one colum for small screen */ -@media only screen and (max-width: 960px) +@media only screen and (max-width: 1000px) { div.fiche { margin-: px; @@ -871,6 +900,11 @@ div.nopadding { padding-left: 2px; padding-right: 2px; } +.pictostatus { + width: 15px; + vertical-align: middle; + margin-top: -3px +} .pictowarning, .pictopreview { padding-: 3px; } @@ -902,12 +936,12 @@ div.divphotoref { } div.statusref { float: right; - padding-right: 12px; - margin-top: 6px; + padding-left: 12px; + margin-top: 8px; margin-bottom: 10px; clear: both; } -img.photoref { +img.photoref, div.photoref { border: 1px solid #CCC; -moz-box-shadow: 3px 3px 4px #DDD; -webkit-box-shadow: 3px 3px 4px #DDD; @@ -917,6 +951,12 @@ img.photoref { width: 80px; object-fit: contain; } +div.photoref { + display:table-cell; + vertical-align:middle; + text-align:center; +} + img.photorefnoborder { padding: 2px; height: 48px; @@ -940,7 +980,7 @@ $minwidthtmenu=66; /* minimum width for one top menu entry */ $heightmenu=46; /* height of top menu, part with image */ $heightmenu2=48; /* height of top menu, part with login */ $disableimages = 0; -$maxwidthloginblock = 110; +$maxwidthloginblock = 130; if (! empty($conf->global->THEME_TOPMENU_DISABLE_IMAGE)) { $disableimages = 1; $maxwidthloginblock = 180; $minwidthtmenu=0; } ?> @@ -1227,7 +1267,7 @@ $mainmenuusedarray=array_unique(explode(',',$mainmenuused)); $generic=1; // Put here list of menu entries when the div.mainmenu.menuentry was previously defined -$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','holiday','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','webservices','websites'); +$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','webservices','websites'); // Put here list of menu entries we are sure we don't want $divnotrequired=array('multicurrency','salaries','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); foreach($mainmenuusedarray as $val) @@ -1363,7 +1403,7 @@ table.login_table_securitycode tr td { div.login_block { position: absolute; - text-align: right; + text-align: ; : 5px; top: 3px; font-weight: bold; @@ -1392,6 +1432,9 @@ div.login a:hover { } div.login_block_user { display: inline-block; + global->THEME_TOPMENU_DISABLE_IMAGE)) { ?> + min-width: 120px; + } div.login_block_other { display: inline-block; @@ -1401,7 +1444,7 @@ div.login_block_other { padding-top: 3px; text-align: right; } .login_block_elem { float: right; vertical-align: top; - padding: 0px 0px 0px 4px !important; + padding: 0px 3px 0px 4px !important; height: 16px; } .atoplogin, .atoplogin:hover { @@ -1772,7 +1815,7 @@ img.toolbarbutton { } /* hide the toggler-button when the pane is 'slid open' */ -.ui-layout-resizer-sliding .ui-layout-toggler { +.ui-layout-resizer-sliding .ui-layout-toggler { display: none; } @@ -1870,17 +1913,18 @@ div.tabsElem { div.tabBar { color: #; padding-top: 16px; - padding-left: 18px; - padding-right: 18px; + padding-left: 0px; padding-right: 0px; + /*padding-left: 18px; + padding-right: 18px;*/ padding-bottom: 14px; margin: 0px 0px 14px 0px; - -moz-border-radius:4px; + /*-moz-border-radius:4px; -webkit-border-radius: 4px; border-radius: 4px; border-right: 1px solid #AAA; - border-bottom: 1px solid #AAA; - border-left: 1px solid #AAA; + border-left: 1px solid #AAA; */ border-top: 1px solid #BBB; + border-bottom: 1px solid #AAA; width: auto; background: rgb(); @@ -1998,7 +2042,9 @@ span.tabspan { /* Boutons actions */ /* ============================================================================== */ -div.divButAction { margin-bottom: 1.4em; } +div.divButAction { + margin-bottom: 1.4em; +} span.butAction, span.butActionDelete { cursor: pointer; @@ -2063,9 +2109,9 @@ span.butAction, span.butActionDelete { filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border: 1px solid #bbbbbb; border-bottom-color: #a2a2a2; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + border-radius: 2px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); @@ -2218,7 +2264,7 @@ a.butAction:link, a.butAction:visited, a.butAction:hover, a.butAction:active { } End bootstrap */ -global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { ?> +global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (! $user->admin)) { ?> .butActionRefused { display: none; } @@ -2278,7 +2324,9 @@ tr.nocellnopadd td.nobordernopadding, tr.nocellnopadd td.nocellnopadd table.border, table.dataTable, .table-border, .table-border-col, .table-key-border-col, .table-val-border-col, div.border { + border: 1px solid #E0E0E0; + border-collapse: collapse !important; padding: 1px 2px 1px 3px; /* t r b l */ } @@ -2301,8 +2349,16 @@ div .tdtop { } table.border td, div.border div div.tagtd { + padding: 2px 2px 2px 2px; border: 1px solid #E0E0E0; + + padding: 3px 2px 3px 2px; + border-bottom: 1px solid #E0E0E0; + + padding: 3px 2px 3px 2px; + /* border: 1px solid #E0E0E0; */ + border-collapse: collapse; } @@ -2355,7 +2411,7 @@ table.liste, table.noborder, table.formdoc, div.noborder { -webkit-border-radius: 0.2em; border-radius: 0.2em;*/ } -.liste_titre_add td, .liste_titre_add .tagtd +.liste_titre_add td, .liste_titre_add th, .liste_titre_add .tagtd { border-top-width: 2px; border-top-color: rgb(); @@ -2410,7 +2466,7 @@ table.listwithfilterbefore { /* Pagination */ div.refidpadding { - padding-top: dol_use_jmobile)?'3':'7'; ?>px; + padding-top: dol_use_jmobile != 4)?'3':'7'; ?>px; } div.refid { font-weight: bold; @@ -2422,6 +2478,10 @@ div.refidno { font-weight: normal; color: #444; font-size: px; + line-height: 21px; +} +div.refidno form { + display: inline-block; } div.pagination { @@ -2442,7 +2502,7 @@ div.pagination li { display: inline-block; padding-left: 0px; padding-right: 0px; -dol_use_jmobile)) { ?> +dol_use_jmobile != 4) { ?> padding-top: 6px; padding-bottom: 5px; @@ -2454,20 +2514,20 @@ div.pagination li { } div.pagination li.pagination a, div.pagination li.pagination span { -dol_use_jmobile)) { ?> +dol_use_jmobile != 4) { ?> padding: 6px 12px; - border-color: #ccc; margin-left: -1px; line-height: 1.42857143; color: #000; text-decoration: none; - + /* + border-color: #ccc; background-color: #f5f5f5; background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); - background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); + background-image: linear-gradient(to bottom, #ffffff, #e6e6e6);*/ background-repeat: repeat-x; } @@ -2501,13 +2561,13 @@ div.pagination li.litext a:hover { background-color: transparent; background-image: none; } -dol_use_jmobile)) { ?> +dol_use_jmobile == 4) { ?> div.pagination li.litext { padding-top: 13px; vertical-align: top; } -dol_use_jmobile)) { ?> +dol_use_jmobile != 4) { ?> div.pagination li.noborder a:hover { border: none; background-color: transparent; @@ -2515,7 +2575,7 @@ div.pagination li.noborder a:hover { div.pagination li a, div.pagination li span { background-color: #fff; - border: 1px solid #ddd; + /* border: 1px solid #ddd; */ } div.pagination li:first-child a, div.pagination li:first-child span { @@ -2651,8 +2711,6 @@ table.dataTable td { } tr.even td, tr.pair td, tr.odd td, tr.impair td, form.odd div.tagtd, form.impair div.tagtd, form.pair div.tagtd, div.impair div.tagtd, div.pair div.tagtd, div.liste_titre div.tagtd { padding: 5px 2px 5px 3px; -} -tr.even td, tr.pair td, tr.odd td, tr.impair td, form.odd div.tagtd, form.impair div.tagtd, form.pair div.tagtd, div.impair div.tagtd, div.pair div.tagtd, div.liste_titre div.tagtd { border-bottom: 1px solid #ddd; } tr.even:last-of-type td, tr.pair:last-of-type td, tr.odd:last-of-type td, tr.impair:last-of-type td { @@ -2705,11 +2763,6 @@ tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel, tabl } div.liste_titre, tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel, table.dataTable thead tr { - /* TO MATCH BOOTSTRAP */ - /*background: #ddd; - color: #000 !important;*/ - - /* TO MATCH ELDY */ background-image: -o-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(,0.4) 100%); background-image: -moz-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(,0.4) 100%); @@ -2748,6 +2801,13 @@ tr.liste_titre_topborder td { text-shadow: none !important; color: rgb(); } +.liste_titre td a.notasortlink { + color: rgb(); +} +.liste_titre td a.notasortlink:hover { + background: transparent; +} + tr.liste_titre_sel th, th.liste_titre_sel, tr.liste_titre_sel td, td.liste_titre_sel, form.liste_titre_sel div { font-family: ; @@ -2789,6 +2849,7 @@ tr.liste_sub_total, tr.liste_sub_total td { border-top-width: px !important; border-top-color: rgb() !important; border-top-style: solid !important; + margin: 0px 0px 0px 0px !important; } .paymenttable tr td:first-child, .margintable tr td:first-child { @@ -3312,11 +3373,19 @@ td.hidden { } .websitetools { float: right; - padding-top: 2px; + height: 28px; +} +.websiteinputurl { + display: inline-block; + vertical-align: top; } .websiteiframenoborder { border: 0px; } +a.websitebuttonsitepreview img { + width: 26px; + display: inline-block; +} /* ============================================================================== */ @@ -3789,6 +3858,7 @@ div.ecmjqft { text-align: center; min-width: px; width: auto; + max-width: 1024px; padding-left: 10px !important; padding-right: 10px !important; } @@ -3912,8 +3982,18 @@ div.dataTables_length select { /* Select2 */ /* ============================================================================== */ +.select2-container .select2-choice > .select2-chosen { + margin-right: 23px; +} +.select2-container .select2-choice .select2-arrow { + border-radius: 0; +} +.select2-container-multi .select2-choices { + background-image: none; +} .select2-container .select2-choice { color: #000; + border-radius: 0; } .selectoptiondisabledwhite { background: #FFFFFF !important; @@ -4240,23 +4320,45 @@ ul.ulmenu { } /* Style for first level menu with jmobile */ +.ui-li .ui-btn-inner a.ui-link-inherit, .ui-li-static.ui-li { + padding: 1em 15px; + display: block; +} +.ui-btn-up-c { + font-weight: normal; +} +.ui-focus, .ui-btn:focus { + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} +.ui-bar-b { + /*border: 1px solid #888;*/ + border: none; + background: none; + text-shadow: none; + color: rgb() !important; +} .ui-bar-b, .lilevel0 { - border: 1px solid #888 !important; - background: rgb(); background-repeat: repeat-x; + border: none; + background: none; + text-shadow: none; + color: rgb() !important; +} +.alilevel0 { + font-weight: normal !important; +} - background-image: -o-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: -moz-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: -webkit-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: -ms-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - font-weight: bold; - - color: rgb() !important; +.ui-li.ui-last-child, .ui-li.ui-field-contain.ui-last-child { + border-bottom-width: 0px !important; } .alilevel0 { color: rgb() !important; - text-shadow: 1px 0px 1px #; +} +.ulmenu { + box-shadow: none !important; + border-bottom: 1px solid #444; } .ui-btn-icon-right { border-right: 1px solid #ccc !important; @@ -4266,7 +4368,7 @@ ul.ulmenu { text-shadow: none; } .ui-btn-up-c, .ui-btn-hover-c { - border: 1px solid #ccc; + /* border: 1px solid #ccc; */ text-shadow: none; } .ui-body-c .ui-link, .ui-body-c .ui-link:visited, .ui-body-c .ui-link:hover { @@ -4284,6 +4386,7 @@ ul.ulmenu { div.tabsElem a.tab { background: transparent; } + /*.ui-controlgroup-horizontal .ui-btn.ui-first-child { -webkit-border-top-left-radius: 6px; border-top-left-radius: 6px; @@ -4292,25 +4395,26 @@ border-top-left-radius: 6px; -webkit-border-top-right-radius: 6px; border-top-right-radius: 6px; }*/ + .alilevel1 { - color: rgb() !important; - text-shadow: 1px 0px 1px #; + color: rgb() !important; } .lilevel1 { - background-image: -webkit-gradient(linear,left top,left bottom,from( #ddd ),to( #d1d1d1 )) !important; - background-image: -webkit-linear-gradient( #ddd,#d1d1d1 ) !important; - background-image: -moz-linear-gradient( #ddd,#d1d1d1 ) !important; - background-image: -ms-linear-gradient( #ddd,#d1d1d1 ) !important; - background-image: -o-linear-gradient( #ddd,#d1d1d1 ) !important; - background-image: linear-gradient( #ddd,#d1d1d1 ) !important; + border-top: 2px solid #444; + background: #fff ! important; +} +.lilevel1 div div a { + font-weight: bold !important; } .lilevel2 { padding-left: 22px; + background: #fff ! important; } .lilevel3 { padding-left: 54px; + background: #fff ! important; } @@ -4346,15 +4450,17 @@ border-top-right-radius: 6px; .menu li.menu_choix1 { padding-top: 6px; padding-right: 10px; + padding-bottom: 2px; } .menu li.menu_choix2 { padding-top: 6px; padding-right: 10px; + padding-bottom: 2px; } @media only screen and (max-width: 767px) { .menu_choix1 a, .menu_choix2 a { - background-size: 30px 30px; + background-size: 36px 36px; height: 30px; padding-left: 40px; } @@ -4438,7 +4544,7 @@ img.demothumb { /* nboftopmenuentries = , fontsize= */ /* rule to reduce top menu - 1st reduction */ -@media only screen and (max-width: px) +@media only screen and (max-width: px) { div.tmenucenter { max-width: px; /* size of viewport */ @@ -4486,7 +4592,7 @@ img.demothumb { } } /* rule to reduce top menu - 3rd reduction */ -@media only screen and (max-width: 660px) +@media only screen and (max-width: px) { /* Reduce login top right info */ .usertextatoplogin { @@ -4504,6 +4610,9 @@ img.demothumb { padding-: 78px; } + div.login_block_user { + min-width: 0; + } div.login_block { top: 2px; @@ -4512,6 +4621,9 @@ img.demothumb { max-width: 82px; } + .login_block_elem { + padding: 0 !important; + } li.tmenu, li.tmenusel { min-width: 32px; } @@ -4533,6 +4645,25 @@ img.demothumb { position: absolute; width: px; } + select { + width: 98%; + dol_use_jmobile)) { ?>max-width: 100px; + min-width: 40px; + } + div.divphotoref { + padding-right: 5px; + } + img.photoref, div.photoref { + border: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; + padding: 4px; + height: 20px; + width: 20px; + object-fit: contain; + } + } ; font-weight: normal; color: rgb(); text-decoration: none; } a:hover { text-decoration: underline; color: rgb(); } +input, input.flat, textarea, textarea.flat, form.flat select, select, select.flat, .dataTables_length label select { + background-color: #FDFDFD; +} + input:focus, textarea:focus, button:focus, select:focus { @@ -264,7 +274,6 @@ textarea.cke_source:focus input, input.flat, textarea, textarea.flat, form.flat select, select, select.flat, .dataTables_length label select { font-size: px; font-family: ; - background: #FDFDFD; border: 1px solid #C0C0C0; margin: 0px 0px 0px 0px; } @@ -286,7 +295,7 @@ input.removedassigned { vertical-align: text-bottom; margin-bottom: -3px; } -input.smallpadd { +input.smallpadd { /* Used for timesheet input */ padding-left: 1px !important; padding-right: 1px !important; } @@ -304,9 +313,6 @@ span.timesheetalreadyrecorded input { select.flat, form.flat select { font-weight: normal; } -input:disabled { - background:#f4f4f4; -} .optiongrey, .opacitymedium { opacity: 0.5; } @@ -316,6 +322,10 @@ input:disabled { .opacitytransp { opacity: 0; } +select:invalid { color: gray; } +input:disabled { + background:#f4f4f4; +} input.liste_titre { box-shadow: none !important; @@ -331,6 +341,7 @@ input.removedfile { textarea:disabled { background:#f4f4f4; } +input[type=file ] { background-color: transparent; border-top: none; border-left: none; border-right: none; box-shadow: none; } input[type=checkbox] { background-color: transparent; border: none; box-shadow: none; } input[type=radio] { background-color: transparent; border: none; box-shadow: none; } input[type=image] { background-color: transparent; border: none; box-shadow: none; } @@ -341,8 +352,9 @@ input:-webkit-autofill { -webkit-box-shadow: 0 0 0 50px inset; } ::-webkit-input-placeholder { color:#ccc; } -::-moz-placeholder { color:#ccc; } /* firefox 19+ */ -:-ms-input-placeholder { color:#ccc; } /* ie */ +:-moz-placeholder { color:#bbb; } /* firefox 18- */ +::-moz-placeholder { color:#bbb; } /* firefox 19+ */ +:-ms-input-placeholder { color:#ccc; } /* ie */ input:-moz-placeholder { color:#ccc; } @@ -528,17 +540,6 @@ div.confirmmessage { div.myavailability { padding-top: 6px; } -/* Style to move picto into left of button */ -/* -.buttonactionview { - padding-left: 15px; -} -.pictoactionview { - padding-left: 10px; - margin-right: -24px; - z-index: 999999; -} -*/ .googlerefreshcal { padding-top: 4px; padding-bottom: 4px; @@ -579,8 +580,22 @@ div.myavailability { .tablelistofcalendars { margin-top: 25px !important; } +.amountalreadypaid { +} +.amountpaymentcomplete { + color: #008800; + font-weight: bold; +} +.amountremaintopay { + color: #880000; + font-weight: bold; +} +.savingdocmask { + margin-top: 6px; + margin-bottom: 12px; +} -/* for future usage (when left menu has been removed) */ +/* DOL_XXX for future usage (when left menu has been removed). If we do not use datatable */ .table-responsive { width: calc(100% - 330px); margin-bottom: 15px; @@ -596,17 +611,22 @@ div.myavailability { .clearboth { clear:both; } .hideobject { display: none; } .minwidth50 { min-width: 50px; } -.minwidth100 { min-width: 100px; } -.minwidth200 { min-width: 200px; } -.minwidth300 { min-width: 300px; } -.minwidth400 { min-width: 400px; } -.minwidth500 { min-width: 500px; } -.minwidth50imp { min-width: 50px !important; } -.minwidth100imp { min-width: 100px !important; } -.minwidth200imp { min-width: 200px !important; } -.minwidth300imp { min-width: 300px !important; } -.minwidth400imp { min-width: 400px !important; } -.minwidth500imp { min-width: 500px !important; } +/* rule to reduce top menu - 3rd reduction */ +@media only screen and (min-width: px) +{ + .minwidth100 { min-width: 100px; } + .minwidth200 { min-width: 200px; } + .minwidth300 { min-width: 300px; } + .minwidth400 { min-width: 400px; } + .minwidth500 { min-width: 500px; } + .minwidth50imp { min-width: 50px !important; } + .minwidth100imp { min-width: 100px !important; } + .minwidth200imp { min-width: 200px !important; } + .minwidth300imp { min-width: 300px !important; } + .minwidth400imp { min-width: 400px !important; } + .minwidth500imp { min-width: 500px !important; } +} +.maxwidth50 { max-width: 50px; } .maxwidth100 { max-width: 100px; } .maxwidth150 { max-width: 150px; } .maxwidth200 { max-width: 200px; } @@ -615,10 +635,11 @@ div.myavailability { .maxwidth500 { max-width: 500px; } .minheight20 { min-height: 20px; } .minheight40 { min-height: 40px; } -.titlefield { width: 30%; } .titlefieldcreate { width: 20%; } +.titlefield { width: 25%; } +.titlefieldmiddle { width: 50%; } -/* Force values for small screen */ +/* Force values for small screen 1400 */ @media only screen and (max-width: 1400px) { .titlefield { width: 30% !important; } @@ -631,7 +652,8 @@ div.myavailability { .minwidth500imp { min-width: 300px !important; } } -@media only screen and (max-width: 960px) +/* Force values for small screen 1000 */ +@media only screen and (max-width: 1000px) { .maxwidthonsmartphone { max-width: 100px; } .minwidth50imp { min-width: 50px !important; } @@ -642,12 +664,26 @@ div.myavailability { .minwidth500imp { min-width: 100px !important; } } -/* Force values for small screen */ +/* Force values for small screen 570 */ @media only screen and (max-width: 570px) { + div.titre { + line-height: 2em; + } + + input[type=text], select, textarea { + min-width: 20px; + min-height: 1.4em; + line-height: 1.4em; + margin: .5em 0; + padding: .4em .1em; + border: 1px solid #BBB; + } + .hideonsmartphone { display: none; } .noenlargeonsmartphone { width : 50px !important; display: inline !important; } .maxwidthonsmartphone { max-width: 100px; } + .maxwidth50onsmartphone { max-width: 50px; } .maxwidth100onsmartphone { max-width: 100px; } .maxwidth150onsmartphone { max-width: 150px; } .maxwidth200onsmartphone { max-width: 200px; } @@ -849,7 +885,7 @@ div.ficheaddleft { browser->layout != 'phone') { print "padding-".$left.": 16px;\n"; } else print "margin-top: 10px;\n"; ?> } -/* Force values for small screen */ +/* Force values on one colum for small screen */ @media only screen and (max-width: 900px) { div.fiche { @@ -914,6 +950,11 @@ table.noborder tr.liste_titre td { padding-left: 2px; padding-right: 2px; } +.pictostatus { + width: 15px; + vertical-align: middle; + margin-top: -3px +} .pictowarning, .pictopreview { padding-: 3px; } @@ -937,26 +978,34 @@ div.arearef { margin-bottom: 10px; } div.heightref { - min-height: 74px; + min-height: 80px; } div.divphotoref { padding-right: 20px; } div.statusref { float: right; - padding-right: 12px; + padding-left: 12px; margin-top: 8px; margin-bottom: 10px; clear: both; } -img.photoref { - height: 80px; - width: 80px; +img.photoref, div.photoref { border: 1px solid #CCC; -moz-box-shadow: 3px 3px 4px #DDD; -webkit-box-shadow: 3px 3px 4px #DDD; box-shadow: 3px 3px 4px #DDD; + padding: 4px; + height: 80px; + width: 80px; + object-fit: contain; } +div.photoref { + display:table-cell; + vertical-align:middle; + text-align:center; +} + img.photorefnoborder { padding: 2px; height: 48px; @@ -1167,7 +1216,7 @@ div.mainmenu { div.mainmenu.home{ background-image: url(); - background-position-x: middle; + background-position-x: center; } div.mainmenu.accountancy { @@ -1255,7 +1304,7 @@ $mainmenuusedarray=array_unique(explode(',',$mainmenuused)); $generic=1; // Put here list of menu entries when the div.mainmenu.menuentry was previously defined -$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','holiday','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','webservices','websites'); +$divalreadydefined=array('home','companies','products','commercial','externalsite','accountancy','project','tools','members','agenda','ftp','holiday','hrm','bookmark','cashdesk','ecm','geoipmaxmind','gravatar','clicktodial','paypal','webservices','websites'); // Put here list of menu entries we are sure we don't want $divnotrequired=array('multicurrency','salaries','margin','opensurvey','paybox','expensereport','incoterm','prelevement','propal','workflow','notification','supplier_proposal','cron','product','productbatch','expedition'); foreach($mainmenuusedarray as $val) @@ -1281,7 +1330,7 @@ foreach($mainmenuusedarray as $val) $url=dol_buildpath($path.'/theme/'.$theme.'/img/menus/generic'.$generic.".png",1); $found=1; if ($generic < 4) $generic++; - print "/* A mainmenu entry but img file ".$val.".png not found (check /".$val."/img/".$val.".png), so we use a generic one */\n"; + print "/* A mainmenu entry was found but img file ".$val.".png not found (check /".$val."/img/".$val.".png), so we use a generic one */\n"; } if ($found) { @@ -1777,7 +1826,7 @@ img.toolbarbutton { } /* hide the toggler-button when the pane is 'slid open' */ -.ui-layout-resizer-sliding ui-layout-toggler { +.ui-layout-resizer-sliding .ui-layout-toggler { display: none; } @@ -2016,8 +2065,8 @@ span.tabspan { /* Boutons actions */ /* ============================================================================== */ -div.divButAction { - margin-bottom: 1.4em; +div.divButAction { + margin-bottom: 1.4em; vertical-align: top; } @@ -2065,7 +2114,7 @@ span.butAction, span.butActionDelete { color: #ffffff !important; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); background-color: #006dcc; - dol_use_jmobile)) { ?> + dol_use_jmobile != 4)) { ?> background-image: -moz-linear-gradient(top, #0088cc, #0044cc); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); @@ -2186,10 +2235,15 @@ tr.nocellnopadd td.nobordernopadding, tr.nocellnopadd td.nocellnopadd table.border, table.dataTable, .table-border, .table-border-col, .table-key-border-col, .table-val-border-col, div.border { + border: 1px solid #f4f4f4; + border-collapse: collapse !important; padding: 1px 2px 1px 3px; /* t r b l */ } +table.borderplus { + border: 1px solid #BBB; +} .border tbody tr, .border tbody tr td { height: 20px; @@ -2212,7 +2266,7 @@ td.border, div.tagtable div div.border { } .table-key-border-col { - width: 25%; + /* width: 25%; */ vertical-align:top; } .table-val-border-col { @@ -2274,12 +2328,18 @@ table.noborder tr, div.noborder form { min-height: 26px; } -.liste_titre_add td, .liste_titre_add .tagtd +.liste_titre_add td, .liste_titre_add th, .liste_titre_add .tagtd { border-top-width: 2px; border-top-color: rgb(); border-top-style: solid; } +.liste_titre_add td, .liste_titre_add .tagtd +{ + border-top-width: 1px; + border-top-color: rgb(); + border-top-style: solid; +} table.liste th, table.noborder th, table.noborder tr.liste_titre td { padding: 8px 2px 8px 3px; /* t r b l */ @@ -2322,7 +2382,7 @@ table.listwithfilterbefore { /* Pagination */ div.refidpadding { - padding-top: dol_use_jmobile)?'3':'14'; ?>px; + padding-top: dol_use_jmobile != 4)?'3':'14'; ?>px; } div.refid { font-weight: bold; @@ -2334,6 +2394,10 @@ div.refidno { font-weight: normal; color: #444; font-size: px; + line-height: 21px; +} +div.refidno form { + display: inline-block; } div.pagination { @@ -2354,7 +2418,7 @@ div.pagination li { display: inline-block; padding-left: 0px; padding-right: 0px; -dol_use_jmobile)) { ?> +dol_use_jmobile != 4)) { ?> padding-top: 6px; padding-bottom: 5px; @@ -2367,7 +2431,7 @@ div.pagination li { div.pagination li.pagination a, div.pagination li.pagination span { -dol_use_jmobile)) { ?> +dol_use_jmobile != 4) { ?> padding: 6px 12px; margin-left: -1px; line-height: 1.42857143; @@ -2394,13 +2458,13 @@ border: none; padding-left: 4px; font-weight: bold; } -dol_use_jmobile)) { ?> +dol_use_jmobile == 4) { ?> div.pagination li.litext { padding-top: 13px; vertical-align: top; } -dol_use_jmobile)) { ?> +dol_use_jmobile != 4) { ?> div.pagination li.noborder a:hover { border: none; background-color: transparent; @@ -2495,8 +2559,6 @@ div.pagination li.paginationafterarrows { { background: rgb() !important; - - /* background: rgba(0, 0, 0, 0.05) !important; */ } @@ -2571,7 +2633,7 @@ div.liste_titre { border-top-style: solid; } div.liste_titre_bydiv { - border-top-width: px; + border-top-width: px; border-top-color: rgb(); border-top-style: solid; @@ -2579,7 +2641,7 @@ div.liste_titre_bydiv { border-collapse: collapse; display: table; padding: 2px 0px 2px 0; - width: 100%; /* 1px more, i don't know why */ + width: 100%; } tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel, table.dataTable.tr { @@ -2587,10 +2649,6 @@ tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel, tabl } div.liste_titre, tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel, table.dataTable thead tr { - /* TO MATCH BOOTSTRAP */ - /* background: #ddd; */ - - /* TO MATCH ELDY */ background-image: -o-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(250,250,250,0.3) 100%); background-image: -moz-linear-gradient(bottom, rgba(0,0,0,0.1) 0%, rgba(250,250,250,0.3) 100%); @@ -2629,6 +2687,12 @@ tr.liste_titre_topborder td { text-shadow: none !important; color: rgb(); } +.liste_titre td a.notasortlink { + color: rgb(); +} +.liste_titre td a.notasortlink:hover { + background: transparent; +} div.liste_titre { padding-left: 3px; } @@ -2670,6 +2734,7 @@ tr.liste_sub_total, tr.liste_sub_total td { border-top-width: px !important; border-top-color: rgb() !important; border-top-style: solid !important; + margin: 0px 0px 0px 0px !important; } .paymenttable tr td:first-child, .margintable tr td:first-child { @@ -2798,8 +2863,13 @@ tr.box_pair { tr.box_pair td, tr.box_impair td { padding: 4px; +} +tr.box_pair:not(:last-child) td, tr.box_impair:not(:last-child) td { border-bottom: 1px solid #f4f4f4; } +.noborderbottom { + border-bottom: none !important; +} .formboxfilter { vertical-align: middle; @@ -3210,7 +3280,18 @@ td.hidden { } .websitetools { float: right; - padding-top: 2px; + height: 28px; +} +.websiteinputurl { + display: inline-block; + vertical-align: top; +} +.websiteiframenoborder { + border: 0px; +} +a.websitebuttonsitepreview img { + width: 26px; + display: inline-block; } .websiteiframenoborder { border: 0px; @@ -3627,7 +3708,7 @@ ul.filedirelem li { border: solid 1px #f4f4f4; } -ui-layout-north { +.ui-layout-north { } @@ -3689,6 +3770,7 @@ div.ecmjqft { text-align: center; min-width: px; width: auto; + max-width: 1024px; padding-left: 10px !important; padding-right: 10px !important; } @@ -3813,6 +3895,12 @@ div.dataTables_length select { /* Select2 */ /* ============================================================================== */ +.select2-container .select2-choice > .select2-chosen { + margin-right: 23px; +} +.select2-container .select2-choice .select2-arrow { + border-radius: 0; +} .select2-container .select2-choice { color: #000; } @@ -4018,6 +4106,9 @@ li.ui-li-divider .ui-link { a.ui-link, a.ui-link:hover, .ui-btn:hover, span.ui-btn-text:hover, span.ui-btn-inner:hover { text-decoration: none !important; } +.ui-body-c { + background: #fff; +} .ui-btn-inner { min-width: .4em; @@ -4052,7 +4143,7 @@ select { /* display: inline-block; */ /* We can't set this. This disable ability to make */ /* TODO modified by jmobile, replace jmobile with pure css*/ overflow:hidden; - white-space: nowrap; + white-space: nowrap; /* Enabling this make behaviour strange when selecting the empty value if this empty value is '' instead of ' ' */ text-overflow: ellipsis; } .fiche .ui-controlgroup { @@ -4085,7 +4176,7 @@ a.tab span.ui-btn-inner color: rgb(); } .liste_titre .ui-link { - color: rgb() !important; + color: rgb() !important; } a.ui-link { @@ -4097,7 +4188,7 @@ a.ui-link { { white-space: normal; overflow: hidden; - text-overflow: hidden; + text-overflow: clip; /* "hidden" : do not exists as a text-overflow value (https://developer.mozilla.org/fr/docs/Web/CSS/text-overflow) */ } /* Warning: setting this may make screen not beeing refreshed after a combo selection */ @@ -4137,23 +4228,45 @@ ul.ulmenu { } /* Style for first level menu with jmobile */ +.ui-li .ui-btn-inner a.ui-link-inherit, .ui-li-static.ui-li { + padding: 1em 15px; + display: block; +} +.ui-btn-up-c { + font-weight: normal; +} +.ui-focus, .ui-btn:focus { + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} +.ui-bar-b { + /*border: 1px solid #888;*/ + border: none; + background: none; + text-shadow: none; + color: rgb() !important; +} .ui-bar-b, .lilevel0 { - border: 1px solid #888 !important; - background: rgb(); background-repeat: repeat-x; + border: none; + background: none; + text-shadow: none; + color: rgb() !important; +} +.alilevel0 { + font-weight: normal !important; +} - background-image: -o-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: -moz-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: -webkit-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: -ms-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - background-image: linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%); - font-weight: bold; - - color: rgb() !important; +.ui-li.ui-last-child, .ui-li.ui-field-contain.ui-last-child { + border-bottom-width: 0px !important; } .alilevel0 { color: rgb() !important; - text-shadow: 1px 0px 1px #; +} +.ulmenu { + box-shadow: none !important; + border-bottom: 1px solid #444; } .ui-btn-icon-right { border-right: 1px solid #ccc !important; @@ -4163,7 +4276,7 @@ ul.ulmenu { text-shadow: none; } .ui-btn-up-c, .ui-btn-hover-c { - border: 1px solid #ccc; + /* border: 1px solid #ccc; */ text-shadow: none; } .ui-body-c .ui-link, .ui-body-c .ui-link:visited, .ui-body-c .ui-link:hover { @@ -4173,33 +4286,43 @@ ul.ulmenu { color: # !important; text-shadow: none !important; } -.ui-controlgroup-horizontal .ui-btn.ui-first-child { +/* +.ui-btn-up-c { + background: transparent; +} +*/ +div.tabsElem a.tab { + background: transparent; +} + +/*.ui-controlgroup-horizontal .ui-btn.ui-first-child { -webkit-border-top-left-radius: 6px; border-top-left-radius: 6px; } .ui-controlgroup-horizontal .ui-btn.ui-last-child { -webkit-border-top-right-radius: 6px; border-top-right-radius: 6px; -} +}*/ + .alilevel1 { - color: rgb() !important; - text-shadow: 1px 0px 1px #; + color: rgb() !important; } .lilevel1 { - background-image: -webkit-gradient(linear,left top,left bottom,from( #f4f4f4 ),to( #d1d1d1 )) !important; - background-image: -webkit-linear-gradient( #f4f4f4,#d1d1d1 ) !important; - background-image: -moz-linear-gradient( #f4f4f4,#d1d1d1 ) !important; - background-image: -ms-linear-gradient( #f4f4f4,#d1d1d1 ) !important; - background-image: -o-linear-gradient( #f4f4f4,#d1d1d1 ) !important; - background-image: linear-gradient( #f4f4f4,#d1d1d1 ) !important; + border-top: 2px solid #444; + background: #fff ! important; +} +.lilevel1 div div a { + font-weight: bold !important; } .lilevel2 { padding-left: 22px; + background: #fff ! important; } .lilevel3 { padding-left: 54px; + background: #fff ! important; } @@ -4235,7 +4358,31 @@ border-top-right-radius: 6px; .menu_choix1 a:hover,.menu_choix2 a:hover { color: #6d3f6d; } - +.menu li.menu_choix1 { + padding-top: 6px; + padding-right: 10px; + padding-bottom: 2px; +} +.menu li.menu_choix2 { + padding-top: 6px; + padding-right: 10px; + padding-bottom: 2px; +} +@media only screen and (max-width: 767px) +{ + .menu_choix1 a, .menu_choix2 a { + background-size: 36px 36px; + background-position-y: 6px; + padding-left: 40px; + } + .menu li.menu_choix1, .menu li.menu_choix2 { + padding-left: 4px; + padding-right: 0; + } + .liste_articles { + margin-right: 0 !important; + } +} @@ -4246,6 +4393,8 @@ border-top-right-radius: 6px; img.demothumb { box-shadow: 2px 2px 8px #888; margin-bottom: 4px; + margin-right: 20px; + margin-left: 10px; } @@ -4280,7 +4429,9 @@ img.demothumb { -/***** CSS style used for small screen *****/ +/* ============================================================================== */ +/* CSS style used for small screen */ +/* ============================================================================== */ .imgopensurveywizard { @@ -4295,6 +4446,13 @@ img.demothumb { width: px; } + img.demothumb { + box-shadow: 1px 1px 4px #BBB; + margin-right: 6px; + margin-left: 4px; + width: 80px; + } + div.tabBar { padding-left: 0px; padding-right: 0px; @@ -4383,6 +4541,25 @@ img.demothumb { position: absolute; width: px; } + select { + width: 98%; + dol_use_jmobile)) { ?>max-width: 100px; + min-width: 0 !important; + } + div.divphotoref { + padding-right: 5px; + } + img.photoref, div.photoref { + border: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; + padding: 4px; + height: 20px; + width: 20px; + object-fit: contain; + } + } diff --git a/htdocs/user/card.php b/htdocs/user/card.php index 032628e4e67..d2c96ab7950 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -216,6 +216,8 @@ if (empty($reshook)) { $object->weeklyhours = GETPOST("weeklyhours") != '' ? GETPOST("weeklyhours") : ''; $object->color = GETPOST("color") != '' ? GETPOST("color") : ''; + $dateemployment = dol_mktime(0, 0, 0, GETPOST('dateemploymentmonth'), GETPOST('dateemploymentday'), GETPOST('dateemploymentyear')); + $object->dateemployment = $dateemployment; // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost($extralabels, $object); @@ -263,10 +265,7 @@ if (empty($reshook)) { { $langs->load("errors"); $db->rollback(); - if (is_array($object->errors) && count($object->errors)) - { - setEventMessages($object->error, $object->errors, 'errors'); - } + setEventMessages($object->error, $object->errors, 'errors'); $action = "create"; // Go back to create page } } @@ -360,6 +359,8 @@ if (empty($reshook)) { $object->weeklyhours = GETPOST("weeklyhours") != '' ? GETPOST("weeklyhours") : ''; $object->color = GETPOST("color") != '' ? GETPOST("color") : ''; + $dateemployment = dol_mktime(0, 0, 0, GETPOST('dateemploymentmonth'), GETPOST('dateemploymentday'), GETPOST('dateemploymentyear')); + $object->dateemployment = $dateemployment; if (! empty($conf->multicompany->enabled)) { @@ -753,7 +754,7 @@ if (($action == 'create') || ($action == 'adduserldap')) // Employee print ''; print ''; // Position/Job @@ -1060,6 +1061,13 @@ if (($action == 'create') || ($action == 'adduserldap')) print ''; print ''; print "\n"; + + // Date employment + print ''; + print ''; + print "\n"; // Accountancy code if ($conf->accounting->enabled) @@ -1131,6 +1139,10 @@ else $object->fetch($id); if ($res < 0) { dol_print_error($db,$object->error); exit; } $res=$object->fetch_optionals($object->id,$extralabels); + + // Check if user has rights + $object->getrights(); + if(empty($object->nb_rights)) setEventMessages($langs->trans('UserHasNoPermissions'), null, 'warnings'); // Connexion ldap // pour recuperer passDoNotExpire et userChangePassNextLogon @@ -1415,6 +1427,13 @@ else print ''; } + // Date employment + print ''; + print ''; + print "\n"; + print '
    '; - $formsupplier_proposal->selectSupplierProposalStatus($viewstatut,1); + $formpropal->selectProposalStatus($viewstatut,1,0,1,'supplier'); print ''; diff --git a/htdocs/supplier_proposal/note.php b/htdocs/supplier_proposal/note.php index a3799c0eb29..981b654599d 100644 --- a/htdocs/supplier_proposal/note.php +++ b/htdocs/supplier_proposal/note.php @@ -92,6 +92,16 @@ if ($id > 0 || ! empty($ref)) print "
    ".$langs->trans("Supplier")."'.$object->thirdparty->getNomUrl(1).'
    '; + print ''; + print '
    '; + print $langs->trans('PaymentConditionsShort'); + print '
    '; + print '
    '; + $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'none', 1); + print '
    '.$langs->trans('SupplierProposalDate').''; print dol_print_date($object->date_livraison,'daytext'); print '
    '.fieldLabel('Employee','employee',0).''; - print $form->selectyesno("employee",(isset($_POST['employee'])?GETPOST('employee'):0),1); + print $form->selectyesno("employee",(GETPOST('employee')?GETPOST('employee'):0),1); print '
    '.$langs->trans("DateEmployment").''; + echo $form->select_date(GETPOST('dateemployment'),'dateemployment',0,0,1,'form'.'dateemployment',1,0,1); + print '
    '.$object->accountancy_code.'
    '.$langs->trans("DateEmployment").''; + print dol_print_date($object->dateemployment); + print '
    '; print ''; @@ -1765,15 +1784,6 @@ else dol_fiche_head($head, 'user', $title, 0, 'user'); - $rowspan=22; - if (isset($conf->file->main_authentication) && preg_match('/openid/',$conf->file->main_authentication) && ! empty($conf->global->MAIN_OPENIDURL_PERUSER)) $rowspan++; - if (! empty($conf->societe->enabled)) $rowspan++; - if (! empty($conf->adherent->enabled)) $rowspan++; - if (! empty($conf->skype->enabled)) $rowspan++; - if (! empty($conf->salaries->enabled) && ! empty($user->rights->salaries->read)) $rowspan = $rowspan+3; - if (! empty($conf->agenda->enabled)) $rowspan++; - if (! empty($conf->accounting->enabled)) $rowspan++; - print ''; // Ref/ID @@ -1800,12 +1810,6 @@ else print $object->lastname; } print ''; - - // Photo - print ''; - print ''; // Firstname @@ -1822,6 +1826,14 @@ else } print ''; + // Photo + print ''; + print ''; + print ''; + print ''; + // Employee print ''; print ''; print "\n"; + // Date employment + print ''; + print ''; + print "\n"; + // Accountancy code if ($conf->accounting->enabled) { diff --git a/htdocs/user/class/api_deprecated_user.class.php b/htdocs/user/class/api_deprecated_user.class.php index c9fcb2b0dd7..f080e8a3b45 100644 --- a/htdocs/user/class/api_deprecated_user.class.php +++ b/htdocs/user/class/api_deprecated_user.class.php @@ -256,7 +256,7 @@ class UserApi extends DolibarrApi /** * Validate fields before create or update object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * @throws RestException */ diff --git a/htdocs/user/class/api_users.class.php b/htdocs/user/class/api_users.class.php index a9eb7771d9d..e177b4d52ec 100644 --- a/htdocs/user/class/api_users.class.php +++ b/htdocs/user/class/api_users.class.php @@ -49,6 +49,82 @@ class Users extends DolibarrApi $this->useraccount = new User($this->db); } + + /** + * List Users + * + * Get a list of Users + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $user_ids User ids filter field. 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 User objects + */ + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $user_ids = 0, $sqlfilters = '') { + global $db, $conf; + + $obj_ret = array(); + + if(! DolibarrApiAccess::$user->rights->user->user->lire) { + throw new RestException(401, "You are not allowed to read list of users"); + } + + // case of external user, $societe param is ignored and replaced by user's socid + //$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe; + + $sql = "SELECT t.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as t"; + $sql.= ' WHERE t.entity IN ('.getEntity('user', 1).')'; + if ($user_ids) $sql.=" AND t.rowid IN (".$user_ids.")"; + // Add sql filters + if ($sqlfilters) + { + if (! DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql.= $db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; + + $sql.= $db->plimit($limit + 1, $offset); + } + + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + while ($i < min($num, ($limit <= 0 ? $num : $limit))) + { + $obj = $db->fetch_object($result); + $user_static = new User($db); + if($user_static->fetch($obj->rowid)) { + $obj_ret[] = parent::_cleanObjectDatas($user_static); + } + $i++; + } + } + else { + throw new RestException(503, 'Error when retrieve User list'); + } + if( ! count($obj_ret)) { + throw new RestException(404, 'No User found'); + } + return $obj_ret; + } + /** * Get properties of an user object * @@ -201,7 +277,7 @@ class Users extends DolibarrApi /** * Validate fields before create or update object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * @throws RestException */ diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index 144f9ee7891..997933e234b 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -107,6 +107,7 @@ class User extends CommonObject var $rights; // Array of permissions user->rights->permx var $all_permissions_are_loaded; /**< \private all_permissions_are_loaded */ private $_tab_loaded=array(); // Array of cache of already loaded permissions + var $nb_rights; // Number of rights granted to the user var $conf; // To store personal config var $oldcopy; // To contains a clone of this when we need to save old properties of object @@ -115,13 +116,17 @@ class User extends CommonObject var $parentof; // To store an array of all parents for all ids. var $accountancy_code; // Accountancy code in prevision of the complete accountancy module - var $thm; // Average cost of employee + + var $thm; // Average cost of employee - Used for valuation of time spent var $tjm; // Average cost of employee - var $salary; // Monthly salary - var $salaryextra; // Monthly salary extra - var $weeklyhours; // Weekly hours + + var $salary; // Monthly salary - Denormalized value from llx_user_employment + var $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment + var $weeklyhours; // Weekly hours - Denormalized value from llx_user_employment var $color; // Define background color for user in agenda + + var $dateemployment; // Define date of employment by company /** * Constructor de la classe @@ -138,6 +143,7 @@ class User extends CommonObject // For cache usage $this->all_permissions_are_loaded = 0; + $this->nb_rights = 0; // Force some default values $this->admin = 0; @@ -187,6 +193,7 @@ class User extends CommonObject $sql.= " u.salaryextra,"; $sql.= " u.weeklyhours,"; $sql.= " u.color,"; + $sql.= " u.dateemployment,"; $sql.= " u.ref_int, u.ref_ext,"; $sql.= " c.code as country_code, c.label as country,"; $sql.= " d.code_departement as state_code, d.nom as state"; @@ -286,6 +293,7 @@ class User extends CommonObject $this->salaryextra = $obj->salaryextra; $this->weeklyhours = $obj->weeklyhours; $this->color = $obj->color; + $this->dateemployment = $this->db->jdate($obj->dateemployment); $this->datec = $this->db->jdate($obj->datec); $this->datem = $this->db->jdate($obj->datem); @@ -629,10 +637,12 @@ class User extends CommonObject if ($subperms) { if (! isset($this->rights->$module->$perms) || ! is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass(); + if(empty($this->rights->$module->$perms->$subperms)) $this->nb_rights++; $this->rights->$module->$perms->$subperms = 1; } else { + if(empty($this->rights->$module->$perms)) $this->nb_rights++; $this->rights->$module->$perms = 1; } @@ -679,10 +689,12 @@ class User extends CommonObject if ($subperms) { if (! isset($this->rights->$module->$perms) || ! is_object($this->rights->$module->$perms)) $this->rights->$module->$perms = new stdClass(); + if(empty($this->rights->$module->$perms->$subperms)) $this->nb_rights++; $this->rights->$module->$perms->$subperms = 1; } else { + if(empty($this->rights->$module->$perms)) $this->nb_rights++; $this->rights->$module->$perms = 1; } @@ -1260,6 +1272,7 @@ class User extends CommonObject $this->town = empty($this->town)?'':$this->town; $this->accountancy_code = trim($this->accountancy_code); $this->color = empty($this->color)?'':$this->color; + $this->dateemployment = empty($this->dateemployment)?'':$this->dateemployment; // Check parameters if (! empty($conf->global->USER_MAIL_REQUIRED) && ! isValidEMail($this->email)) @@ -1300,6 +1313,7 @@ class User extends CommonObject $sql.= ", signature = '".$this->db->escape($this->signature)."'"; $sql.= ", accountancy_code = '".$this->db->escape($this->accountancy_code)."'"; $sql.= ", color = '".$this->db->escape($this->color)."'"; + $sql.= ", dateemployment=".(strval($this->dateemployment)!='' ? "'".$this->db->idate($this->dateemployment)."'" : 'null'); $sql.= ", note = '".$this->db->escape($this->note)."'"; $sql.= ", photo = ".($this->photo?"'".$this->db->escape($this->photo)."'":"null"); $sql.= ", openid = ".($this->openid?"'".$this->db->escape($this->openid)."'":"null"); @@ -1311,7 +1325,7 @@ class User extends CommonObject $sql.= ", weeklyhours= ".($this->weeklyhours != ''?"'".$this->db->escape($this->weeklyhours)."'":"null"); $sql.= ", entity = '".$this->db->escape($this->entity)."'"; $sql.= " WHERE rowid = ".$this->id; - + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) @@ -2032,7 +2046,7 @@ class User extends CommonObject { $paddafterimage=''; if (abs($withpictoimg) == 1) $paddafterimage='style="margin-right: 3px;"'; - if ($withpictoimg > 0) $picto='
    '.img_object('', 'user', $paddafterimage.' '.($notooltip?'':'class="classfortooltip"')).'
    '; + if ($withpictoimg > 0) $picto='
    '.img_object('', 'user', $paddafterimage.' '.($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).'
    '; else $picto='
    '.Form::showphoto('userphoto', $this, 0, 0, 0, 'loginphoto', 'mini', 0, 1).'
    '; $result.=$picto; } @@ -2112,23 +2126,23 @@ class User extends CommonObject } if ($mode == 2) { - if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); - if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4','class="pictostatus"').' '.$langs->trans('Enabled'); + if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5','class="pictostatus"').' '.$langs->trans('Disabled'); } if ($mode == 3) { - if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4'); - if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5'); + if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4','class="pictostatus"'); + if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5','class="pictostatus"'); } if ($mode == 4) { - if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); - if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + if ($statut == 1) return img_picto($langs->trans('Enabled'),'statut4','class="pictostatus"').' '.$langs->trans('Enabled'); + if ($statut == 0) return img_picto($langs->trans('Disabled'),'statut5','class="pictostatus"').' '.$langs->trans('Disabled'); } if ($mode == 5) { - if ($statut == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4'); - if ($statut == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5'); + if ($statut == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4','class="pictostatus"'); + if ($statut == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5','class="pictostatus"'); } } diff --git a/htdocs/user/index.php b/htdocs/user/index.php index 5d8f02e1c32..f5d9407d2e3 100644 --- a/htdocs/user/index.php +++ b/htdocs/user/index.php @@ -57,8 +57,11 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield="u.login"; if (! $sortorder) $sortorder="ASC"; +// Initialize context for list +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'userlist'; + // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('userlist')); +$hookmanager->initHooks(array($contextpage)); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -131,45 +134,49 @@ if ($mode == 'employee') $search_employee=1; /* * Actions */ - + +if (GETPOST('cancel')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction=''; } + $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +if (empty($reshook)) { - $search_user=""; - $search_login=""; - $search_lastname=""; - $search_firstname=""; - $search_gender=""; - $search_employee=""; - $search_accountancy_code=""; - $search_email=""; - $search_statut=""; - $search_thirdparty=""; - $search_supervisor=""; - $search_datelastlogin=""; - $search_datepreviouslogin=""; - $search_date_creation=""; - $search_date_update=""; - $search_array_options=array(); + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All test are required to be compatible with all browsers + { + $search_user=""; + $search_login=""; + $search_lastname=""; + $search_firstname=""; + $search_gender=""; + $search_employee=""; + $search_accountancy_code=""; + $search_email=""; + $search_statut=""; + $search_thirdparty=""; + $search_supervisor=""; + $search_datelastlogin=""; + $search_datepreviouslogin=""; + $search_date_creation=""; + $search_date_update=""; + $search_array_options=array(); + } } - /* * View */ -llxHeader('',$langs->trans("ListOfUsers")); $buttonviewhierarchy=''; -print load_fiche_titre($langs->trans("ListOfUsers"), $buttonviewhierarchy); - $sql = "SELECT u.rowid, u.lastname, u.firstname, u.admin, u.fk_soc, u.login, u.email, u.accountancy_code, u.gender, u.employee, u.photo,"; $sql.= " u.datelastlogin, u.datepreviouslogin,"; $sql.= " u.ldap_sid, u.statut, u.entity,"; @@ -227,156 +234,374 @@ $parameters=array(); $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; $sql.=$db->order($sortfield,$sortorder); -//$sql.= $db->plimit($conf->liste_limit+1, $offset); -/*$totalnboflines=0; +$nbtotalofrecords=0; $result=$db->query($sql); if ($result) { - $totalnboflines = $db->num_rows($result); + $nbtotalofrecords = $db->num_rows($result); } $sql.= $db->plimit($limit+1, $offset); -*/ + $result = $db->query($sql); -if ($result) +if (! $result) { - $num = $db->num_rows($result); - $i = 0; + dol_print_error($db); + exit; +} - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall != '') $param.='&sall='.urlencode($sall); - if ($search_user != '') $param.="&search_user=".$search_user; - if ($search_login != '') $param.="&search_login=".$search_login; - if ($search_lastname != '') $param.="&search_lastname=".$search_lastname; - if ($search_firstname != '') $param.="&search_firstname=".$search_firstname; - if ($search_gender != '') $param.="&search_gender=".$search_gender; - if ($search_employee != '') $param.="&search_employee=".$search_employee; - if ($search_accountancy_code != '') $param.="&search_accountancy_code=".$search_accountancy_code; - if ($search_email != '') $param.="&search_email=".$search_email; - if ($search_supervisor > 0) $param.="&search_supervisor=".$search_supervisor; - if ($search_statut != '') $param.="&search_statut=".$search_statut; - if ($optioncss != '') $param.='&optioncss='.$optioncss; - // Add $param from extra fields - foreach ($search_array_options as $key => $val) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); - } - - - print ''."\n"; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } - - $moreforfilter=''; - - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '
    '; - print $form->showphoto('userphoto',$object,100,0,$caneditfield,'photowithmargin','small'); - print '
    '.$langs->trans("Photo").''; + print $form->showphoto('userphoto',$object,100,0,$caneditfield,'photowithmargin','small'); + print '
    '.fieldLabel('Employee','employee',0).''; @@ -2189,6 +2201,13 @@ else print '
    '.$langs->trans("DateEmployment").''; + echo $form->select_date(GETPOST('dateemployment')?GETPOST('dateemployment'):$object->dateemployment,'dateemployment',0,0,1,'form'.'dateemployment',1,0,1); + print '
    '; - print ''; - if (! empty($arrayfields['u.login']['checked'])) print_liste_field_titre($langs->trans("Login"),$_SERVER['PHP_SELF'],"u.login",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.lastname']['checked'])) print_liste_field_titre($langs->trans("Lastname"),$_SERVER['PHP_SELF'],"u.lastname",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.firstname']['checked'])) print_liste_field_titre($langs->trans("FirstName"),$_SERVER['PHP_SELF'],"u.firstname",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.gender']['checked'])) print_liste_field_titre($langs->trans("Gender"),$_SERVER['PHP_SELF'],"u.gender",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.employee']['checked'])) print_liste_field_titre($langs->trans("Employee"),$_SERVER['PHP_SELF'],"u.employee",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.accountancy_code']['checked'])) print_liste_field_titre($langs->trans("AccountancyCode"),$_SERVER['PHP_SELF'],"u.accountancy_code",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.email']['checked'])) print_liste_field_titre($langs->trans("EMail"),$_SERVER['PHP_SELF'],"u.email",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.fk_soc']['checked'])) print_liste_field_titre($langs->trans("Company"),$_SERVER['PHP_SELF'],"u.fk_soc",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.entity']['checked'])) print_liste_field_titre($langs->trans("Entity"),$_SERVER['PHP_SELF'],"u.entity",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.fk_user']['checked'])) print_liste_field_titre($langs->trans("HierarchicalResponsible"),$_SERVER['PHP_SELF'],"u.fk_user",$param,"","",$sortfield,$sortorder); - if (! empty($arrayfields['u.datelastlogin']['checked'])) print_liste_field_titre($langs->trans("LastConnexion"),$_SERVER['PHP_SELF'],"u.datelastlogin",$param,"",'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['u.datepreviouslogin']['checked'])) print_liste_field_titre($langs->trans("PreviousConnexion"),$_SERVER['PHP_SELF'],"u.datepreviouslogin",$param,"",'align="center"',$sortfield,$sortorder); - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); - } - } - } - // Hook fields - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (! empty($arrayfields['u.datec']['checked'])) print_liste_field_titre($langs->trans("DateCreationShort"),$_SERVER["PHP_SELF"],"u.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['u.tms']['checked'])) print_liste_field_titre($langs->trans("DateModificationShort"),$_SERVER["PHP_SELF"],"u.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['u.statut']['checked'])) print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"u.statut","",$param,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; +$num = $db->num_rows($result); - // Search bar - print ''; +if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) +{ + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/user/card.php?id='.$id); + exit; +} + +llxHeader('',$langs->trans("ListOfUsers")); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($sall != '') $param.='&sall='.urlencode($sall); +if ($search_user != '') $param.="&search_user=".$search_user; +if ($search_login != '') $param.="&search_login=".$search_login; +if ($search_lastname != '') $param.="&search_lastname=".$search_lastname; +if ($search_firstname != '') $param.="&search_firstname=".$search_firstname; +if ($search_gender != '') $param.="&search_gender=".$search_gender; +if ($search_employee != '') $param.="&search_employee=".$search_employee; +if ($search_accountancy_code != '') $param.="&search_accountancy_code=".$search_accountancy_code; +if ($search_email != '') $param.="&search_email=".$search_email; +if ($search_supervisor > 0) $param.="&search_supervisor=".$search_supervisor; +if ($search_statut != '') $param.="&search_statut=".$search_statut; +if ($optioncss != '') $param.='&optioncss='.$optioncss; +if ($mode != '') $param.='&mode='.$mode; +// Add $param from extra fields +foreach ($search_array_options as $key => $val) +{ + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); +} + +$text = $langs->trans("ListOfUsers"); + +print ''."\n"; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($text, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $nbtotalofrecords, 'title_generic', 0, '', '', $limit); + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); +} + +$moreforfilter=''; + +$varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; +$selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + +print '
    '; +print ''; +if (! empty($arrayfields['u.login']['checked'])) print_liste_field_titre($langs->trans("Login"),$_SERVER['PHP_SELF'],"u.login",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.lastname']['checked'])) print_liste_field_titre($langs->trans("Lastname"),$_SERVER['PHP_SELF'],"u.lastname",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.firstname']['checked'])) print_liste_field_titre($langs->trans("FirstName"),$_SERVER['PHP_SELF'],"u.firstname",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.gender']['checked'])) print_liste_field_titre($langs->trans("Gender"),$_SERVER['PHP_SELF'],"u.gender",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.employee']['checked'])) print_liste_field_titre($langs->trans("Employee"),$_SERVER['PHP_SELF'],"u.employee",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.accountancy_code']['checked'])) print_liste_field_titre($langs->trans("AccountancyCode"),$_SERVER['PHP_SELF'],"u.accountancy_code",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.email']['checked'])) print_liste_field_titre($langs->trans("EMail"),$_SERVER['PHP_SELF'],"u.email",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.fk_soc']['checked'])) print_liste_field_titre($langs->trans("Company"),$_SERVER['PHP_SELF'],"u.fk_soc",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.entity']['checked'])) print_liste_field_titre($langs->trans("Entity"),$_SERVER['PHP_SELF'],"u.entity",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.fk_user']['checked'])) print_liste_field_titre($langs->trans("HierarchicalResponsible"),$_SERVER['PHP_SELF'],"u.fk_user",$param,"","",$sortfield,$sortorder); +if (! empty($arrayfields['u.datelastlogin']['checked'])) print_liste_field_titre($langs->trans("LastConnexion"),$_SERVER['PHP_SELF'],"u.datelastlogin",$param,"",'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['u.datepreviouslogin']['checked'])) print_liste_field_titre($langs->trans("PreviousConnexion"),$_SERVER['PHP_SELF'],"u.datepreviouslogin",$param,"",'align="center"',$sortfield,$sortorder); +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + } + } +} +// Hook fields +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['u.datec']['checked'])) print_liste_field_titre($langs->trans("DateCreationShort"),$_SERVER["PHP_SELF"],"u.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['u.tms']['checked'])) print_liste_field_titre($langs->trans("DateModificationShort"),$_SERVER["PHP_SELF"],"u.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['u.statut']['checked'])) print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"u.statut","",$param,'align="center"',$sortfield,$sortorder); +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); +print "\n"; + +// Search bar +print ''; +if (! empty($arrayfields['u.login']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.lastname']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.firstname']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.gender']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.employee']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.accountancy_code']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.email']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.fk_soc']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.entity']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.fk_user']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.datelastlogin']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['u.datepreviouslogin']['checked'])) +{ + print ''; +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($arrayfields["ef.".$key]['checked'])) + { + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + } + } +} +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['u.datec']['checked'])) +{ + // Date creation + print ''; +} +if (! empty($arrayfields['u.tms']['checked'])) +{ + // Date modification + print ''; +} +if (! empty($arrayfields['u.statut']['checked'])) +{ + // Status + print ''; +} +// Action column +print ''; + +print "\n"; + +$user2=new User($db); + +$var=True; +$i = 0; +while ($i < min($num,$limit)) +{ + $obj = $db->fetch_object($result); + $var=!$var; + + $userstatic->id=$obj->rowid; + $userstatic->ref=$obj->label; + $userstatic->login=$obj->login; + $userstatic->statut=$obj->statut; + $userstatic->email=$obj->email; + $userstatic->gender=$obj->gender; + $userstatic->societe_id=$obj->fk_soc; + $userstatic->firstname=$obj->firstname; + $userstatic->lastname=$obj->lastname; + $userstatic->employee=$obj->employee; + $userstatic->photo=$obj->photo; + + $li=$userstatic->getNomUrl(-1,'',0,0,24,1,'login'); + + print ""; if (! empty($arrayfields['u.login']['checked'])) - { - print ''; - } + { + print ''; + } if (! empty($arrayfields['u.lastname']['checked'])) - { - print ''; - } + { + print ''; + } if (! empty($arrayfields['u.firstname']['checked'])) - { - print ''; - } + { + print ''; + } if (! empty($arrayfields['u.gender']['checked'])) - { - print ''; - } + { + print ''; + } if (! empty($arrayfields['u.employee']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.accountancy_code']['checked'])) - { - print ''; - } + { + print ''; + } + if (! empty($arrayfields['u.accountancy_code']['checked'])) + { + print ''; + } if (! empty($arrayfields['u.email']['checked'])) + { + print ''; + } + if (! empty($arrayfields['u.fk_soc']['checked'])) + { + print "'; + } + // Multicompany enabled + if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode)) { - print ''; - } - if (! empty($arrayfields['u.fk_soc']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.entity']['checked'])) - { - print ''; + if (! empty($arrayfields['u.entity']['checked'])) + { + print ''; + } } + // Supervisor if (! empty($arrayfields['u.fk_user']['checked'])) - { - print ''; - } + { + // Resp + print ''; + } + + // Date last login if (! empty($arrayfields['u.datelastlogin']['checked'])) - { - print ''; - } + { + print ''; + } + // Date previous login if (! empty($arrayfields['u.datepreviouslogin']['checked'])) - { - print ''; - } + { + print ''; + } + // Extra fields if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) { @@ -384,260 +609,55 @@ if ($result) { if (! empty($arrayfields["ef.".$key]['checked'])) { - $align=$extrafields->getAlignFlag($key); - $typeofextrafield=$extrafields->attribute_type[$key]; - print ''; } } } // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; + // Date creation if (! empty($arrayfields['u.datec']['checked'])) { - // Date creation - print ''; } + // Date modification if (! empty($arrayfields['u.tms']['checked'])) { - // Date modification - print ''; } + // Status if (! empty($arrayfields['u.statut']['checked'])) { - // Status - print ''; + $userstatic->statut=$obj->statut; + print ''; } // Action column - print ''; - + print ''; + print "\n"; - - $user2=new User($db); - - $var=True; - //while ($i < min($num,$conf->liste_limit)) - while ($i < $num) - { - $obj = $db->fetch_object($result); - $var=!$var; - - $userstatic->id=$obj->rowid; - $userstatic->ref=$obj->label; - $userstatic->login=$obj->login; - $userstatic->statut=$obj->statut; - $userstatic->email=$obj->email; - $userstatic->gender=$obj->gender; - $userstatic->societe_id=$obj->fk_soc; - $userstatic->firstname=$obj->firstname; - $userstatic->lastname=$obj->lastname; - $userstatic->employee=$obj->employee; - $userstatic->photo=$obj->photo; - - $li=$userstatic->getNomUrl(-1,'',0,0,24,1,'login'); - - print ""; - if (! empty($arrayfields['u.login']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.lastname']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.firstname']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.gender']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.employee']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.accountancy_code']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.email']['checked'])) - { - print ''; - } - if (! empty($arrayfields['u.fk_soc']['checked'])) - { - print "'; - } - // Multicompany enabled - if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode)) - { - if (! empty($arrayfields['u.entity']['checked'])) - { - print ''; - } - } - // Supervisor - if (! empty($arrayfields['u.fk_user']['checked'])) - { - // Resp - print ''; - } - - // Date last login - if (! empty($arrayfields['u.datelastlogin']['checked'])) - { - print ''; - } - // Date previous login - if (! empty($arrayfields['u.datepreviouslogin']['checked'])) - { - print ''; - } - - // Extra fields - if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key => $val) - { - if (! empty($arrayfields["ef.".$key]['checked'])) - { - print 'getAlignFlag($key); - if ($align) print ' align="'.$align.'"'; - print '>'; - $tmpkey='options_'.$key; - print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); - print ''; - } - } - } - // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - // Date creation - if (! empty($arrayfields['u.datec']['checked'])) - { - print ''; - } - // Date modification - if (! empty($arrayfields['u.tms']['checked'])) - { - print ''; - } - // Status - if (! empty($arrayfields['u.statut']['checked'])) - { - $userstatic->statut=$obj->statut; - print ''; - } - // Action column - print ''; - - print "\n"; - $i++; - } - - $parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - - print "
    '; + $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); + print $form->selectarray('search_gender', $arraygender, $search_gender, 1); + print ''; + print $form->selectyesno('search_employee', $search_employee, 1, false, 1); + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } + print ''; + print ''; + print ''; + print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); + print ''; +$searchpitco=$form->showFilterAndCheckAddButtons(0); +print $searchpitco; +print '
    '; + print $li; + if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity) + { + print img_picto($langs->trans("SuperAdministrator"),'redstar'); + } + else if ($obj->admin) + { + print img_picto($langs->trans("Administrator"),'star'); + } + print ''.$obj->lastname.''.$obj->firstname.''; - $arraygender=array('man'=>$langs->trans("Genderman"),'woman'=>$langs->trans("Genderwoman")); - print $form->selectarray('search_gender', $arraygender, $search_gender, 1); - print ''; + if ($obj->gender) print $langs->trans("Gender".$obj->gender); + print ''; - print $form->selectyesno('search_employee', $search_employee, 1, false, 1); - print ''.yn($obj->employee).''.$obj->accountancy_code.''.$obj->email.'"; + if ($obj->fk_soc) + { + $companystatic->id=$obj->fk_soc; + $companystatic->name=$obj->name; + $companystatic->canvas=$obj->canvas; + print $companystatic->getNomUrl(1); + } + else if ($obj->ldap_sid) + { + print $langs->trans("DomainUser"); + } + else + { + print $langs->trans("InternalUser"); + } + print ''; + if (! $obj->entity) + { + print $langs->trans("AllEntities"); + } + else + { + // $mc is defined in conf.class.php if multicompany enabled. + if (is_object($mc)) + { + $mc->getInfo($obj->entity); + print $mc->label; + } + } + print ''; + if ($obj->login2) + { + $user2->id=$obj->id2; + $user2->login=$obj->login2; + $user2->lastname=$obj->lastname2; + $user2->firstname=$obj->firstname2; + $user2->gender=$obj->gender2; + $user2->photo=$obj->photo2; + $user2->admin=$obj->admin2; + $user2->email=$obj->email2; + $user2->societe_id=$obj->fk_soc2; + print $user2->getNomUrl(-1,'',0,0,24,0,''); + if (! empty($conf->multicompany->enabled) && $obj->admin2 && ! $obj->entity2) + { + print img_picto($langs->trans("SuperAdministrator"),'redstar'); + } + else if ($obj->admin2) + { + print img_picto($langs->trans("Administrator"),'star'); + } + } + print ''.dol_print_date($db->jdate($obj->datelastlogin),"dayhour").''.dol_print_date($db->jdate($obj->datepreviouslogin),"dayhour").''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) - { - $crit=$val; - $tmpkey=preg_replace('/search_options_/','',$key); - $searchclass=''; - if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; - print ''; - } + print 'getAlignFlag($key); + if ($align) print ' align="'.$align.'"'; + print '>'; + $tmpkey='options_'.$key; + print $extrafields->showOutputField($key, $obj->$tmpkey, '', 1); print ''; + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); print ''; + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour'); print ''; - print $form->selectarray('search_statut', array('-1'=>'','0'=>$langs->trans('Disabled'),'1'=>$langs->trans('Enabled')),$search_statut); - print ''.$userstatic->getLibStatut(3).''; - $searchpitco=$form->showFilterAndCheckAddButtons(0); - print $searchpitco; - print '
    '; - print $li; - if (! empty($conf->multicompany->enabled) && $obj->admin && ! $obj->entity) - { - print img_picto($langs->trans("SuperAdministrator"),'redstar'); - } - else if ($obj->admin) - { - print img_picto($langs->trans("Administrator"),'star'); - } - print ''.$obj->lastname.''.$obj->firstname.''; - if ($obj->gender) print $langs->trans("Gender".$obj->gender); - print ''.yn($obj->employee).''.$obj->accountancy_code.''.$obj->email.'"; - if ($obj->fk_soc) - { - $companystatic->id=$obj->fk_soc; - $companystatic->name=$obj->name; - $companystatic->canvas=$obj->canvas; - print $companystatic->getNomUrl(1); - } - else if ($obj->ldap_sid) - { - print $langs->trans("DomainUser"); - } - else - { - print $langs->trans("InternalUser"); - } - print ''; - if (! $obj->entity) - { - print $langs->trans("AllEntities"); - } - else - { - // $mc is defined in conf.class.php if multicompany enabled. - if (is_object($mc)) - { - $mc->getInfo($obj->entity); - print $mc->label; - } - } - print ''; - if ($obj->login2) - { - $user2->id=$obj->id2; - $user2->login=$obj->login2; - $user2->lastname=$obj->lastname2; - $user2->firstname=$obj->firstname2; - $user2->gender=$obj->gender2; - $user2->photo=$obj->photo2; - $user2->admin=$obj->admin2; - $user2->email=$obj->email2; - $user2->societe_id=$obj->fk_soc2; - print $user2->getNomUrl(-1,'',0,0,24,0,''); - if (! empty($conf->multicompany->enabled) && $obj->admin2 && ! $obj->entity2) - { - print img_picto($langs->trans("SuperAdministrator"),'redstar'); - } - else if ($obj->admin2) - { - print img_picto($langs->trans("Administrator"),'star'); - } - } - print ''.dol_print_date($db->jdate($obj->datelastlogin),"dayhour").''.dol_print_date($db->jdate($obj->datepreviouslogin),"dayhour").''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour'); - print ''.$userstatic->getLibStatut(3).'
    "; - print "\n"; - $db->free($result); -} -else -{ - dol_print_error($db); + $i++; } +$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print "
    "; +print "\n"; +$db->free($result); + + llxFooter(); - $db->close(); diff --git a/htdocs/user/info.php b/htdocs/user/info.php index 1d10875b3eb..e27fcf56266 100644 --- a/htdocs/user/info.php +++ b/htdocs/user/info.php @@ -76,7 +76,6 @@ $object->info($id); // This overwrite ->ref with login instead of id print '
    '; - print '
    '; print '
    '; diff --git a/htdocs/webservices/server_actioncomm.php b/htdocs/webservices/server_actioncomm.php index a5df31c2a7e..99e8ea59e6f 100644 --- a/htdocs/webservices/server_actioncomm.php +++ b/htdocs/webservices/server_actioncomm.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2012 Florian Henry * * This program is free software; you can redistribute it and/or modify @@ -14,16 +14,16 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . + * + * Path to WSDL is: http://localhost/dolibarr/webservices/server_actioncomm.php?wsdl */ /** * \file htdocs/webservices/server_actioncomm.php * \brief File that is entry point to call Dolibarr WebServices - * \version $Id: server_actioncomm.php,v 1.7 2010/12/19 11:49:37 eldy Exp $ */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once("../master.inc.php"); require_once(NUSOAP_PATH.'/nusoap.php'); // Include SOAP diff --git a/htdocs/webservices/server_category.php b/htdocs/webservices/server_category.php index 2bf914ebd38..9ef07dda952 100644 --- a/htdocs/webservices/server_category.php +++ b/htdocs/webservices/server_category.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2012 JF FERRY * * This program is free software; you can redistribute it and/or modify @@ -21,8 +21,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once("../master.inc.php"); require_once(NUSOAP_PATH.'/nusoap.php'); // Include SOAP diff --git a/htdocs/webservices/server_contact.php b/htdocs/webservices/server_contact.php index 8a12c288d55..cab58268f57 100644 --- a/htdocs/webservices/server_contact.php +++ b/htdocs/webservices/server_contact.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2012 JF FERRY * * This program is free software; you can redistribute it and/or modify @@ -21,8 +21,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once("../master.inc.php"); require_once(NUSOAP_PATH.'/nusoap.php'); // Include SOAP diff --git a/htdocs/webservices/server_invoice.php b/htdocs/webservices/server_invoice.php index 04ce0c3cf48..54f5e3c564c 100644 --- a/htdocs/webservices/server_invoice.php +++ b/htdocs/webservices/server_invoice.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2016 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -21,8 +21,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/webservices/server_order.php b/htdocs/webservices/server_order.php index de72af93b61..f477ccfed9c 100644 --- a/htdocs/webservices/server_order.php +++ b/htdocs/webservices/server_order.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2012 JF FERRY * Copyright (C) 2012 Regis Houssin * @@ -22,9 +22,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ - -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/webservices/server_other.php b/htdocs/webservices/server_other.php index ba948d463ea..8ac519ae87e 100644 --- a/htdocs/webservices/server_other.php +++ b/htdocs/webservices/server_other.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-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 @@ -20,8 +20,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/webservices/server_productorservice.php b/htdocs/webservices/server_productorservice.php index aa43dbb185c..385c7dc3b95 100644 --- a/htdocs/webservices/server_productorservice.php +++ b/htdocs/webservices/server_productorservice.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2012 JF FERRY * * This program is free software; you can redistribute it and/or modify @@ -23,8 +23,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/webservices/server_project.php b/htdocs/webservices/server_project.php index 8838f726d63..5400e069c3f 100644 --- a/htdocs/webservices/server_project.php +++ b/htdocs/webservices/server_project.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2016 Laurent Destailleur * Copyright (C) 2016 Ion Agorria * * This program is free software; you can redistribute it and/or modify @@ -21,8 +21,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/webservices/server_supplier_invoice.php b/htdocs/webservices/server_supplier_invoice.php index fea871ac077..ea162ef2a8b 100644 --- a/htdocs/webservices/server_supplier_invoice.php +++ b/htdocs/webservices/server_supplier_invoice.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-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 @@ -20,8 +20,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/webservices/server_thirdparty.php b/htdocs/webservices/server_thirdparty.php index 50b8e80e363..6b2c94a36fd 100644 --- a/htdocs/webservices/server_thirdparty.php +++ b/htdocs/webservices/server_thirdparty.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-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 @@ -20,8 +20,7 @@ * \brief File that is entry point to call Dolibarr WebServices */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/webservices/server_user.php b/htdocs/webservices/server_user.php index 6339486922f..c4d8ce08724 100644 --- a/htdocs/webservices/server_user.php +++ b/htdocs/webservices/server_user.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-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 @@ -18,11 +18,9 @@ /** * \file htdocs/webservices/server_user.php * \brief File that is entry point to call Dolibarr WebServices - * \version $Id: server_user.php,v 1.7 2010/12/19 11:49:37 eldy Exp $ */ -// This is to make Dolibarr working with Plesk -set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs'); +if (! defined("NOCSRFCHECK")) define("NOCSRFCHECK",'1'); require_once '../master.inc.php'; require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP diff --git a/htdocs/websites/class/website.class.php b/htdocs/websites/class/website.class.php index e75cacf9100..2d5f13570b8 100644 --- a/htdocs/websites/class/website.class.php +++ b/htdocs/websites/class/website.class.php @@ -562,7 +562,7 @@ class Website extends CommonObject if ($withpicto) { - $result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); + $result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto != 2) $result.=' '; } $result.= $link . $this->ref . $linkend; diff --git a/htdocs/websites/class/websitepage.class.php b/htdocs/websites/class/websitepage.class.php index 65e56e030a1..abd604bd3d9 100644 --- a/htdocs/websites/class/websitepage.class.php +++ b/htdocs/websites/class/websitepage.class.php @@ -183,7 +183,7 @@ class WebsitePage extends CommonObject * Load object in memory from the database * * @param int $id Id object - * @param string $website_id Web site page + * @param string $website_id Web site id * @param string $page Page name * * @return int <0 if KO, 0 if not found, >0 if OK @@ -376,14 +376,11 @@ class WebsitePage extends CommonObject $this->status = trim($this->status); } - - // Check parameters // Put here code to add a control on parameters values // Update request $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET'; - $sql .= ' fk_website = '.(isset($this->fk_website)?$this->fk_website:"null").','; $sql .= ' pageurl = '.(isset($this->pageurl)?"'".$this->db->escape($this->pageurl)."'":"null").','; $sql .= ' title = '.(isset($this->title)?"'".$this->db->escape($this->title)."'":"null").','; @@ -394,8 +391,6 @@ class WebsitePage extends CommonObject $sql .= ' date_creation = '.(! isset($this->date_creation) || dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').','; $sql .= ' date_modification = '.(! isset($this->date_modification) || dol_strlen($this->date_modification) != 0 ? "'".$this->db->idate($this->date_modification)."'" : 'null').','; $sql .= ' tms = '.(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : "'".$this->db->idate(dol_now())."'"); - - $sql .= ' WHERE rowid=' . $this->id; $this->db->begin(); @@ -407,6 +402,12 @@ class WebsitePage extends CommonObject dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); } + if ($this->old_object->pageurl != $this->pageurl) + { + dol_syslog("The alias was changed, we must rename/recreate the page file into document"); + + } + if (!$error && !$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -559,7 +560,7 @@ class WebsitePage extends CommonObject if ($withpicto) { - $result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend); + $result.=($link.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend); if ($withpicto != 2) $result.=' '; } $result.= $link . $this->ref . $linkend; diff --git a/htdocs/websites/index.php b/htdocs/websites/index.php index 655bdd18e9f..d0aa6424787 100644 --- a/htdocs/websites/index.php +++ b/htdocs/websites/index.php @@ -177,48 +177,9 @@ if ($action == 'add') { $db->rollback(); } -} - -// Update page -if ($action == 'update') -{ - $db->begin(); - - $res = $object->fetch(0, $website); - - $objectpage->fk_website = $object->id; - $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); - - $res = $objectpage->fetch(0, $object->fk_website, $objectpage->pageurl); - - if ($res > 0) - { - $objectpage->title = GETPOST('WEBSITE_TITLE'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); - $objectpage->keyword = GETPOST('WEBSITE_KEYWORD'); - - $res = $objectpage->update($user); - if (! $res > 0) - { - $error++; - setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - } - - if (! $error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - $action=''; - } - else - { - $db->rollback(); - } - } - else - { - dol_print_error($db); - } + + $action = 'preview'; + $id = $objectpage->id; } // Update page @@ -261,35 +222,48 @@ if ($action == 'delete') // Update css if ($action == 'updatecss') { - $db->begin(); + //$db->begin(); $res = $object->fetch(0, $website); + /* $res = $object->update($user); if ($res > 0) { $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); $action=''; } else { + $error++; $db->rollback(); }*/ - $csscontent =''."\n"; + $csscontent.= '"."\n"; + $csscontent.= ''."\n"; $csscontent.= GETPOST('WEBSITE_CSS_INLINE'); + dol_syslog("Save file css into ".$filecss); + dol_mkdir($pathofwebsite); $result = file_put_contents($filecss, $csscontent); if (! empty($conf->global->MAIN_UMASK)) @chmod($filecss, octdec($conf->global->MAIN_UMASK)); - - if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); - else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + if (! $result) + { + $error++; + setEventMessages('Failed to write file '.$filecss, null, 'errors'); + } + + if (! $error) + { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + } + $action='preview'; } @@ -335,7 +309,7 @@ if ($action == 'setashome') } } -// Update page +// Update page (meta) if ($action == 'updatemeta') { $db->begin(); @@ -346,7 +320,7 @@ if ($action == 'updatemeta') $res = $objectpage->fetch($pageid, $object->fk_website); if ($res > 0) { - $oldobjectpage = clone $objectpage; + $objectpage->old_object = clone $objectpage; $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME'); $objectpage->title = GETPOST('WEBSITE_TITLE'); @@ -364,32 +338,54 @@ if ($action == 'updatemeta') { $db->commit(); - $fileoldalias=$pathofwebsite.'/'.$oldobjectpage->pageurl.'.php'; + $filemaster=$pathofwebsite.'/master.inc.php'; + $fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; - - // Generate the alias.php page - //----------------------------- + dol_mkdir($pathofwebsite); - dol_delete_file($fileoldalias); + + + // Now generate the master.inc.php page + dol_syslog("We regenerate the master file"); + dol_delete_file($filemaster); + + $mastercontent = ''."\n"; + $result = file_put_contents($filemaster, $mastercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); + + if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + + + // Now generate the alias.php page + if (! empty($fileoldalias)) + { + dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); + dol_delete_file($fileoldalias); + } $aliascontent = 'id.".tpl.php'\n"; + $aliascontent.= "include_once './page".$objectpage->id.".tpl.php';\n"; $aliascontent.= '?>'."\n"; $result = file_put_contents($filealias, $aliascontent); if (! empty($conf->global->MAIN_UMASK)) @chmod($filealias, octdec($conf->global->MAIN_UMASK)); - if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); - else setEventMessages('Failed to write file '.$filealias, null, 'errors'); + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); - // Now create the .tpl file (duplicate code with actions updatecontent but we need this to save new header) - dol_mkdir($pathofwebsite); + dol_syslog("We regenerate the tpl page filetpl=".$filetpl); + dol_delete_file($filetpl); - $tplcontent = ''."\n"; + $tplcontent =''; + $tplcontent.= ''."\n"; + $tplcontent.= ''."\n"; $tplcontent.= '
    '."\n"; $tplcontent.= ''."\n"; $tplcontent.= ''."\n"; @@ -412,7 +408,7 @@ if ($action == 'updatemeta') if ($result) { - //setEventMessages($langs->trans("Saved"), null, 'mesgs'); + setEventMessages($langs->trans("Saved"), null, 'mesgs'); //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid); //exit; } @@ -449,7 +445,7 @@ if ($action == 'updatecontent') /* $objectpage->content = preg_replace('//s', '', $objectpage->content); */ $res = $objectpage->update($user); - if (! $res > 0) + if ($res < 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); @@ -459,12 +455,53 @@ if ($action == 'updatecontent') { $db->commit(); + $filemaster=$pathofwebsite.'/master.inc.php'; + //$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; + $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php'; + + dol_mkdir($pathofwebsite); + + + // Now generate the master.inc.php page + dol_syslog("We regenerate the master file"); + dol_delete_file($filemaster); + + $mastercontent = ''."\n"; + $result = file_put_contents($filemaster, $mastercontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filemaster, octdec($conf->global->MAIN_UMASK)); + + if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + + + // Now generate the alias.php page + if (! empty($fileoldalias)) + { + dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias); + dol_delete_file($fileoldalias); + } + + $aliascontent = 'id.".tpl.php';\n"; + $aliascontent.= '?>'."\n"; + $result = file_put_contents($filealias, $aliascontent); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filealias, octdec($conf->global->MAIN_UMASK)); + + if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + + // Now create the .tpl file // TODO Keep a one time generate file or include a dynamicaly generated content ? - dol_mkdir($pathofwebsite); dol_delete_file($filetpl); - $tplcontent = ''."\n"; + $tplcontent =''; + $tplcontent.= ""."\n"; + $tplcontent.= ''."\n"; $tplcontent.= '
    '."\n"; $tplcontent.= ''."\n"; $tplcontent.= ''."\n"; @@ -516,7 +553,7 @@ $help_url=''; llxHeader('', $langs->trans("WebsiteSetup"), $help_url); -print "\n".'
    '; +print "\n".'
    '; print ''; if ($action == 'create') { @@ -590,47 +627,19 @@ if (count($object->records) > 0) $realurl=$urlwithroot.'/public/websites/index.php?website='.$website; $dataroot=DOL_DATA_ROOT.'/websites/'.$website; if (! empty($object->virtualhost)) $realurl=$object->virtualhost; - // TODO If virtual url defined, we use it - - /*print ' - '.$langs->trans("RealURL").' '; - print ' '; - print ''.$langs->trans("ViewSiteInNewTab").'';*/ - + } + + if ($website && $action == 'preview') + { + $disabled=''; + if (empty($user->rights->websites->create)) $disabled=' disabled="disabled"'; + print '   '; - - print $langs->trans("ViewWebsiteInProduction").': '; - print ''; - //print ''; - $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); - print $form->textwithpicto('', $htmltext); - print ''.$langs->trans("ViewSiteInNewTab").''; - // Example : Adding jquery code - if (! empty($conf->use_javascript_ajax)) - { - print ''; - } + //print ''; + print ''; + print ''; + print ''; } print '
    '; @@ -640,13 +649,22 @@ if (count($object->records) > 0) if ($action == 'preview') { - $disabled=''; - if (empty($user->rights->websites->create)) $disabled=' disabled="disabled"'; - - //print ''; - print ''; - print ''; - print ''; + print '
    '; + print ''; + //print ''; + $htmltext=$langs->trans("SetHereVirtualHost", $dataroot); + print $form->textwithpicto('', $htmltext); + print '
    '; + + $urlext=$realurl; + $urlint=DOL_URL_ROOT.'/public/websites/index.php?website='.$website; + print ''; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $urlext), 1, 'preview_ext'); + print ''; + + print ''; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $urlint), 1, 'preview'); + print ''; } if (in_array($action, array('editcss','editmenu','create'))) @@ -674,60 +692,55 @@ if (count($object->records) > 0) print $langs->trans("Page").': '; print '
    '; print '
    '; - $out=''; - $out.=''; + if ($atleastonepage) { - $firstpageid=0;$homepageid=0; + 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) { - if (empty($firstpageid)) $firstpageid=$valpage->id; - if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid=$valpage->id; + $out.=''; } - $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.=''; + print $out; + } + else + { + print $langs->trans("New"); } - else $out.=''; - $out.=''; - print $out; print ''; //print $form->selectarray('page', $array); - if ($website && $pageid > 0) - { - print ' - '.$langs->trans("RealURL").' '; - $realurl=$urlwithroot.'/public/websites/index.php?website='.$website.'&page='.$pageid; - print ' '; - print ''.$langs->trans("ViewPageInNewTab").''; // View page in new Tab - //print ''; - } - - print '
    '; - print '
    '; - print '
    '; - - print '
    '; - if ($action == 'preview') { $disabled=''; if (empty($user->rights->websites->create)) $disabled=' disabled="disabled"'; - + if ($pageid > 0) { + print '   '; + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print ''; else print ''; print ''; @@ -738,15 +751,80 @@ if (count($object->records) > 0) } } + print '
    '; + print '
    '; + print '
    '; + + print '
    '; + + 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; + + print '
    '; + print ''; + //print ''; + $htmltext=$langs->trans("WEBSITE_PAGENAME", $pagealias); + print $form->textwithpicto('', $htmltext); + print '
    '; + + $urlext=$realurl.'/'.$pagealias.'.php'; + print ''; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $urlext), 1, 'preview_ext'); + print ''; + + print ''; + print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage), 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 ''; } - + print '
    '; + if ($action == 'preview') + { + // Adding jquery code to change on the fly url of preview ext + if (! empty($conf->use_javascript_ajax)) + { + print ''; + } + } } } else @@ -775,12 +853,15 @@ if ($action == 'editcss') print '
    '; $csscontent = @file_get_contents($filecss); - + // Clean php css file to get only css part + $csscontent = preg_replace('//s', '', $csscontent); + dol_fiche_head(); + print ''."\n"; print ''; - print '
    '; + print '
    '; print $langs->trans('WebSite'); print ''; print $website; @@ -817,6 +898,7 @@ if ($action == 'editmeta' || $action == 'create') dol_fiche_head(); + print ''."\n"; print ''; if ($action != 'create') @@ -836,7 +918,7 @@ if ($action == 'editmeta' || $action == 'create') if (GETPOST('WEBSITE_DESCRIPTION')) $pagedescription=GETPOST('WEBSITE_DESCRIPTION'); if (GETPOST('WEBSITE_KEYWORDS')) $pagekeywords=GETPOST('WEBSITE_KEYWORDS'); - print '
    '; + print '
    '; print $langs->trans('WEBSITE_PAGENAME'); print ''; print ''; @@ -871,11 +953,13 @@ if ($action == 'editmeta' || $action == 'create') if ($action == 'editmedia') { + print ''."\n"; print '
    '.$langs->trans("FeatureNotYetAvailable").''; } if ($action == 'editmenu') { + print ''."\n"; print '
    '.$langs->trans("FeatureNotYetAvailable").''; } @@ -895,10 +979,10 @@ if ($action == 'editcontent') require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,5,60); - $doleditor->Create(); + $doleditor->Create(0, '', false); } -print ''; +print "
    \n\n"; diff --git a/scripts/bank/export-bank-receipts.php b/scripts/bank/export-bank-receipts.php index 4ec31ea3789..2116d51e65b 100755 --- a/scripts/bank/export-bank-receipts.php +++ b/scripts/bank/export-bank-receipts.php @@ -143,7 +143,7 @@ $objmodel = new $classname($db); // Define target path -$dirname = $conf->banque->dir_temp; +$dirname = $conf->bank->dir_temp; $filename = 'export-bank-receipts-'.$bankref.'-'.$num.'.'.$objmodel->extension; diff --git a/scripts/cron/cron_run_jobs.php b/scripts/cron/cron_run_jobs.php index a0f067b5d0c..e10d089c2a8 100755 --- a/scripts/cron/cron_run_jobs.php +++ b/scripts/cron/cron_run_jobs.php @@ -109,8 +109,8 @@ else { if (empty($user->id)) { - echo "User user login: ".$userlogin." does not exists"; - dol_syslog("User user login:".$userlogin." does not exists", LOG_ERR); + echo "User login: ".$userlogin." does not exists"; + dol_syslog("User login:".$userlogin." does not exists", LOG_ERR); exit(-1); } } @@ -124,8 +124,7 @@ if (isset($argv[3]) || $argv[3]) $object = new Cronjob($db); $filter=array(); -if (empty($id)) { - $filter=array(); +if (! empty($id)) { $filter['t.rowid']=$id; } @@ -152,22 +151,25 @@ if(is_array($object->lines) && (count($object->lines)>0)) //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database if (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now)) { - dol_syslog("cron_run_jobs.php:: torun line->datenextrun:".dol_print_date($line->datenextrun,'dayhourtext')." line->dateend:".dol_print_date($line->dateend,'dayhourtext')." now:".dol_print_date($now,'dayhourtext')); + dol_syslog("cron_run_jobs.php:: to run line->datenextrun:".dol_print_date($line->datenextrun,'dayhourrfc')." line->datestart:".dol_print_date($line->datestart,'dayhourrfc')." line->dateend:".dol_print_date($line->dateend,'dayhourrfc')." now:".dol_print_date($now,'dayhourrfc')); $cronjob=new Cronjob($db); $result=$cronjob->fetch($line->id); if ($result<0) { - echo "Error:".$cronjob->error; - dol_syslog("cron_run_jobs.php:: fetch Error".$cronjob->error, LOG_ERR); + echo "Error cronjob->fetch: ".$cronjob->error."\n"; + echo "Failed to fetch job ".$line->id."\n"; + dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR); exit(-1); } // Execute job $result=$cronjob->run_jobs($userlogin); if ($result<0) { - echo "Error:".$cronjob->error; - dol_syslog("cron_run_jobs.php:: run_jobs Error".$cronjob->error, LOG_ERR); + echo "Error cronjob->run_job: ".$cronjob->error."\n"; + echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n"; + echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n"; + dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR); exit(-1); } @@ -175,12 +177,17 @@ if(is_array($object->lines) && (count($object->lines)>0)) $result=$cronjob->reprogram_jobs($userlogin, $now); if ($result<0) { - echo "Error:".$cronjob->error; - dol_syslog("cron_run_jobs.php:: reprogram_jobs Error".$cronjob->error, LOG_ERR); + echo "Error cronjob->reprogram_job: ".$cronjob->error."\n"; + echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n"; + dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR); exit(-1); } } + else + { + dol_syslog("cron_run_jobs.php:: job not qualified line->datenextrun:".dol_print_date($line->datenextrun,'dayhourrfc')." line->datestart:".dol_print_date($line->datestart,'dayhourrfc')." line->dateend:".dol_print_date($line->dateend,'dayhourrfc')." now:".dol_print_date($now,'dayhourrfc')); + } } } diff --git a/test/phpunit/CMailFileTest.php b/test/phpunit/CMailFileTest.php index 092d2e1f41c..06f24ba45e0 100755 --- a/test/phpunit/CMailFileTest.php +++ b/test/phpunit/CMailFileTest.php @@ -177,7 +177,22 @@ class CMailFileTest extends PHPUnit_Framework_TestCase $result=$localobject->getValidAddress($src,3,1); print __METHOD__." result=".$result."\n"; $this->assertEquals($result,'"=?UTF-8?B?Sm9obiBEb2U=?=" '); - + + $src='John Doe '; + $result=$localobject->getValidAddress($src,4); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($result,'John Doe'); + + $src='John Doe , John Doe2 , John Doe3 '; + $result=$localobject->getValidAddress($src,4); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($result,'John Doe,John Doe2,John Doe3'); + + $src='John Doe , John Doe2 , John Doe3 '; + $result=$localobject->getValidAddress($src,4,0,2); + print __METHOD__." result=".$result."\n"; + $this->assertEquals($result,'John Doe,John Doe2...'); + return $result; } diff --git a/test/phpunit/EntrepotTest.php b/test/phpunit/EntrepotTest.php index d3d7c300308..e695bff34a3 100644 --- a/test/phpunit/EntrepotTest.php +++ b/test/phpunit/EntrepotTest.php @@ -233,7 +233,7 @@ class EntrepotTest extends PHPUnit_Framework_TestCase $localobject=new Entrepot($this->savdb); $result=$localobject->fetch($id); - $result=$localobject->delete($id); + $result=$localobject->delete($user); print __METHOD__." id=".$id." result=".$result."\n"; $this->assertLessThan($result, 0); diff --git a/test/phpunit/FunctionsLibTest.php b/test/phpunit/FunctionsLibTest.php index ee7288e2928..f967b53d9db 100644 --- a/test/phpunit/FunctionsLibTest.php +++ b/test/phpunit/FunctionsLibTest.php @@ -119,6 +119,32 @@ class FunctionsLibTest extends PHPUnit_Framework_TestCase } + + /** + * testDolBuildPath + * + * @return boolean + */ + public function testDolBuildPath() + { + /*$tmp=dol_buildpath('/google/oauth2callback.php', 0); + var_dump($tmp); + */ + + /*$tmp=dol_buildpath('/google/oauth2callback.php', 1); + var_dump($tmp); + */ + + $result=dol_buildpath('/google/oauth2callback.php', 2); + print __METHOD__." result=".$result."\n"; + $this->assertStringStartsWith('http', $result); + + $result=dol_buildpath('/google/oauth2callback.php', 3); + print __METHOD__." result=".$result."\n"; + $this->assertStringStartsWith('http', $result); + } + + /** * testGetBrowserInfo * @@ -1009,5 +1035,5 @@ class FunctionsLibTest extends PHPUnit_Framework_TestCase return true; } - + } diff --git a/test/phpunit/RestAPIUserTest.php b/test/phpunit/RestAPIUserTest.php index af1ae6b3622..a92bc80ed63 100644 --- a/test/phpunit/RestAPIUserTest.php +++ b/test/phpunit/RestAPIUserTest.php @@ -150,7 +150,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase $url = $this->api_url.'/users/123456789?api_key='.$this->api_key; //$addheaders=array('Content-Type: application/json'); - print __METHOD__." Request url=".$url."\n"; + print __METHOD__." Request GET url=".$url."\n"; $result=getURLContent($url, 'GET', '', 1, array()); //print __METHOD__." Result for unexisting user: ".var_export($result, true)."\n"; print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n"; @@ -161,7 +161,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase $url = $this->api_url.'/users/1?api_key='.$this->api_key; - print __METHOD__." Request url=".$url."\n"; + print __METHOD__." Request GET url=".$url."\n"; $result=getURLContent($url, 'GET', '', 1, array()); //print __METHOD__." Result for existing user user: ".var_export($result, true)."\n"; print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n"; @@ -184,7 +184,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase ); $body = json_encode($bodyobj); - print __METHOD__." Request url=".$url."\n"; + print __METHOD__." Request POST url=".$url."\n"; $result=getURLContent($url, 'POST', $body, 1, $addheaders); //print __METHOD__." Result for creating incomplete user".var_export($result, true)."\n"; print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n"; @@ -202,7 +202,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase "email"=>"test@restuser.com" ); $body = json_encode($bodyobj); - print __METHOD__." Request url=".$url."\n"; + print __METHOD__." Request POST url=".$url."\n"; $result=getURLContent($url, 'POST', $body, 1, $addheaders); print __METHOD__." Result code for creating user ".var_export($result, true)."\n"; print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n"; @@ -212,7 +212,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase $this->assertGreaterThan(0, $object['id'], $object['error']['code'].' '.$object['error']['message']); // attempt to create duplicated user - print __METHOD__." Request url=".$url."\n"; + print __METHOD__." Request POST url=".$url."\n"; $result=getURLContent($url, 'POST', $body, 1, $addheaders); //print __METHOD__." Result for creating duplicate user".var_export($result, true)."\n"; print __METHOD__." curl_error_no: ".$result['curl_error_no']."\n";