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 a7a643e9d05..7f210c6fab1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -22,7 +22,7 @@ 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. @@ -32,33 +32,75 @@ check you make a fetch on object before calling the delete. - 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: #2853 +FIX: #2991 +FIX: #3128 FIX: #5699 -FIX #5734 -FIX : #5776 -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: #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: 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: 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/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/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 1883f1814da..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 @@ -368,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"; @@ -730,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`; @@ -1137,10 +1141,11 @@ if ($nboftargetok) { print "\nList of files to publish (BUILD=$BUILD)\n"; %filestoscansf=( - "$DESTI/signatures/filelist-$MAJOR.$MINOR.$BUILD.xml"=>'signatures', + "$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' @@ -1148,6 +1153,7 @@ if ($nboftargetok) { %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', @@ -1209,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/) { @@ -1228,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/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index 2a58094717f..32a938662e6 100644 --- a/dev/setup/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/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_class.class.php b/dev/skeletons/skeleton_class.class.php index 86603642362..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); @@ -236,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); @@ -443,36 +451,51 @@ class Skeleton_Class extends CommonObject * * @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; } @@ -491,7 +514,7 @@ class Skeleton_Class extends CommonObject * Return the status * * @param int $status Id status - * @param int $mode 0=long label, 1=short label, 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 */ static function LibStatut($status,$mode=0) @@ -529,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 0ca6962bbef..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(); - - $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) + 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"], $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) + 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/tools/fixduplicatelangkey.sh b/dev/tools/fixduplicatelangkey.sh index ae0be750646..2090f8a3504 100755 --- a/dev/tools/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/tools/fixduplicatelines.sh b/dev/tools/fixduplicatelanglines.sh similarity index 90% rename from dev/tools/fixduplicatelines.sh rename to dev/tools/fixduplicatelanglines.sh index 18f9707169e..0c0e2eecb4b 100755 --- a/dev/tools/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/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 63f99184884..cb3255f981d 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -22,19 +22,23 @@ * \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 934e5f1f081..822a4d19bcd 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -22,9 +22,8 @@ * \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,6 +37,7 @@ $langs->load("accountancy"); $mesg = ''; $action = GETPOST('action'); +$backtopage = GETPOST('backtopage'); $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); $cancel = GETPOST('cancel'); @@ -47,7 +47,18 @@ $cancel = GETPOST('cancel'); $object = new AccountingAccount($db); -// Action + +/* + * 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) { @@ -85,18 +96,30 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) $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' && $user->rights->accounting->chartofaccount) { if (! $cancel) { $result = $object->fetch($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 ''; 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 5b767208987..4127f5e4ee2 100644 --- a/htdocs/accountancy/admin/fiscalyear.php +++ b/htdocs/accountancy/admin/fiscalyear.php @@ -45,7 +45,7 @@ $langs->load("compta"); // Security check if ($user->societe_id > 0) accessforbidden(); -if (! $user->rights->mouvements->lire) // If we can read accounting records, we shoul be able to see fiscal year. +if (! $user->rights->accounting->fiscalyear) // If we can read accounting records, we shoul be able to see fiscal year. accessforbidden(); $error = 0; @@ -80,7 +80,7 @@ $max = 100; $form = new Form($db); -$title = $langs->trans('FiscalYears'); +$title = $langs->trans('AccountingPeriods'); $helpurl = ""; llxHeader('', $title, $helpurl); @@ -106,8 +106,8 @@ if ($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 '
'; 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 7fef6dfa8fb..79d642ffcef 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -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 17bbe55158c..f925bf4e4eb 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -2,6 +2,7 @@ /* 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 @@ -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,6 +301,7 @@ 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'); @@ -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/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 00a16a227e3..b63d7ce2fda 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -172,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(); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 7b8aa12dca2..a6f487c1211 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -105,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); } @@ -162,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(); @@ -173,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) { @@ -187,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); @@ -198,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) { @@ -235,7 +254,7 @@ class BookKeeping extends CommonObject $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; @@ -248,7 +267,7 @@ 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); @@ -274,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; @@ -315,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); @@ -372,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,'; @@ -403,16 +422,16 @@ class BookKeeping extends CommonObject $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 .= ')'; @@ -460,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,"; @@ -481,7 +501,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'; $sql .= ' WHERE 1 = 1'; if (! empty($conf->multicompany->enabled)) { @@ -546,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,"; @@ -567,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) { @@ -591,7 +608,6 @@ class BookKeeping extends CommonObject } } } - $sql.= ' WHERE 1 = 1'; if (! empty($conf->multicompany->enabled)) { $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; @@ -662,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,"; @@ -683,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) { @@ -705,7 +720,6 @@ class BookKeeping extends CommonObject } } } - $sql.= ' WHERE 1 = 1'; if (! empty($conf->multicompany->enabled)) { $sql .= " AND entity IN (" . getEntity("accountancy", 1) . ")"; @@ -774,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) { @@ -803,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)) { @@ -907,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") . ','; @@ -924,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(); @@ -1012,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) { @@ -1027,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; } @@ -1042,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) { @@ -1062,7 +1085,7 @@ class BookKeeping extends CommonObject $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); } $this->db->rollback(); - return - 1; + return -1; } $this->db->commit(); @@ -1076,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); @@ -1179,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); @@ -1205,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); @@ -1231,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); @@ -1281,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); @@ -1329,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; + } @@ -1405,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) { @@ -1447,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 "; @@ -1460,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) { @@ -1483,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 237c0def27f..fab9e81031d 100644 --- a/htdocs/accountancy/class/html.formventilation.class.php +++ b/htdocs/accountancy/class/html.formventilation.class.php @@ -65,7 +65,7 @@ class FormVentilation extends Form /** * Return list of accounts with label by chart of accounts * - * @param string $selectid Preselected chart of accounts + * @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 @@ -99,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, '', $morecss); + $out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, 1); $this->db->free($resql); + return $out; } 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 be23efb56ea..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"; @@ -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); @@ -143,16 +164,16 @@ 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("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToDispatch")) . '
'; +print $langs->trans("DescVentilMore", $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. -print '' . $langs->trans("CleanFixHistory", $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"; @@ -191,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"; @@ -238,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; @@ -282,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); diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index a579daf1a9d..d33fc82f3bc 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -52,37 +52,27 @@ $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); @@ -128,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 } /* @@ -168,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 . ")"; @@ -204,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,28 +233,38 @@ if ($result) { if ($search_tvaintra) $param .= "&search_tvaintra=" . $search_tvaintra; - - print_barre_liste($langs->trans("InvoiceLinesDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords); - print '' . $langs->trans("DescVentilDoneCustomer") . ''; - - print '
'; - print ''; + + 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("VATIntra"), $_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 ''; @@ -273,12 +273,14 @@ if ($result) { print ''; print ''; print ''; - print ''; + print ''; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print '\n"; $facture_static = new Facture($db); @@ -289,7 +291,7 @@ if ($result) { $var = ! $var; $codecompta = length_accountg($objp->account_number) . ' - ' . $objp->label_compte; - print ''; + print ''; // Ref Invoice $facture_static->ref = $objp->facnumber; @@ -300,6 +302,7 @@ if ($result) { $product_static->ref = $objp->product_ref; $product_static->id = $objp->product_id; $product_static->type = $objp->product_type; + $product_static->label = $objp->product_label; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ""; $i ++; @@ -325,11 +329,14 @@ if ($result) { print $db->error(); } -print "
%'; - print ''; + print ''; + $searchpitco=$form->showFilterAndCheckAddButtons(1); + print $searchpitco; print "
'; if ($product_static->id) print $product_static->getNomUrl(1); @@ -314,9 +317,10 @@ if ($result) { print '' . $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 7d2326b05e5..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,6 +101,54 @@ 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") . '
'; +} + /* @@ -111,74 +157,7 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) { 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"; @@ -187,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 . "%')"; @@ -214,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 ''; @@ -305,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; @@ -328,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 136fa27c314..bd18388aacb 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -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; @@ -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; @@ -585,14 +658,17 @@ else { 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 63b88c5fd39..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 { @@ -456,9 +491,10 @@ if ($action == 'export_csv') { print ""; print ""; // /print ""; + print ""; print ""; print ""; - print ""; + print ""; print ""; print "\n"; @@ -486,9 +522,17 @@ if ($action == 'export_csv') { if ($mt) { print ""; + print ""; print ""; print ""; - print ""; + print ""; $companystatic->id = $tabcompany[$key]['id']; $companystatic->name = $tabcompany[$key]['name']; print ""; @@ -502,9 +546,17 @@ if ($action == 'export_csv') { foreach ( $tabtva[$key] as $k => $mt ) { if ($mt) { print ""; + print ""; print ""; print ""; - print ""; + print ""; print ""; print '"; print '"; @@ -515,11 +567,19 @@ if ($action == 'export_csv') { // Third party foreach ( $tabttc[$key] as $k => $mt ) { - print ""; + print ""; + print ""; print ""; $companystatic->id = $tabcompany[$key]['id']; $companystatic->name = $tabcompany[$key]['name']; - print ""; + print ""; print ""; // print "
".$langs->trans("JournalNum")."" . $langs->trans("Date") . "" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("Account") . "" . $langs->trans("AccountAccounting") . "" . $langs->trans("Type") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . ""; + $accountoshow = length_accountg($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("ProductAccountNotDefined").''; + } + else print $accountoshow; + print "" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $accountingaccount->label . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . ""; + $accountoshow = length_accountg($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("VatAccountNotDefined").''; + } + else print $accountoshow; + print "" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("VAT"). ' '.$def_tva[$key]. "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "" . $date . "" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accounta($k) . ""; + $accountoshow = length_accounta($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("ThirdpartyAccountNotDefined").''; + } + else print $accountoshow; + print "" . $companystatic->getNomUrl(0, 'supplier', 16) . ' - ' . $invoicestatic->refsupplier . ' - ' . $langs->trans("Code_tiers") . "" . $langs->trans("ThirdParty"); // print ' (' . $companystatic->getNomUrl(0, 'supplier', 16) . ')'; diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php index 755cb6ce81b..f73af79ff89 100644 --- a/htdocs/accountancy/journal/sellsjournal.php +++ b/htdocs/accountancy/journal/sellsjournal.php @@ -62,16 +62,17 @@ if ($user->societe_id > 0) $action = GETPOST('action'); + /* - * View + * Actions */ $year_current = strftime("%Y", dol_now()); $pastmonth = strftime("%m", dol_now()) - 1; $pastmonthyear = $year_current; if ($pastmonth == 0) { - $pastmonth = 12; - $pastmonthyear --; + $pastmonth = 12; + $pastmonthyear --; } $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); @@ -79,8 +80,8 @@ $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); if (empty($date_start) || empty($date_end)) // We define date_start and date_end { - $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); - $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); + $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); + $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); } $p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); @@ -88,7 +89,7 @@ $idpays = $p[0]; $sql = "SELECT f.rowid, f.facnumber, f.type, f.datef as df, f.ref_client,"; $sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.total_ttc,"; -$sql .= " s.rowid as socid, s.nom as name, s.code_compta, s.code_client,"; +$sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,"; $sql .= " p.rowid as pid, p.ref as pref, p.accountancy_code_sell, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte,"; $sql .= " fd.situation_percent,ct.accountancy_code_sell as account_tva"; $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; @@ -97,334 +98,367 @@ $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = $sql .= " JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; $sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_tva as ct ON fd.tva_tx = ct.taux AND ct.fk_pays = '" . $idpays . "'"; -$sql .= " WHERE fd.fk_code_ventilation > 0 "; -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND f.entity IN (" . getEntity("facture", 1) . ")"; -} +$sql .= " WHERE fd.fk_code_ventilation > 0"; +$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 . ")"; + $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")"; } else { - $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_STANDARD . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")"; + $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_STANDARD . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")"; } $sql .= " AND fd.product_type IN (0,1)"; if ($date_start && $date_end) - $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'"; + $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'"; $sql .= " ORDER BY f.datef"; dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG); $result = $db->query($sql); if ($result) { - $tabfac = array (); - $tabht = array (); - $tabtva = array (); - $def_tva = array (); - $tabttc = array (); - $tabcompany = array (); + $tabfac = array (); + $tabht = array (); + $tabtva = array (); + $def_tva = array (); + $tabttc = array (); + $tabcompany = array (); - $num = $db->num_rows($result); - $i = 0; + $num = $db->num_rows($result); + $i = 0; - while ( $i < $num ) { - $obj = $db->fetch_object($result); - // les variables - $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef"); - $compta_soc = (! empty($obj->code_compta)) ? $obj->code_compta : $cptcli; + while ( $i < $num ) { + $obj = $db->fetch_object($result); + // les variables + $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef"); + $compta_soc = (! empty($obj->code_compta)) ? $obj->code_compta : $cptcli; - $compta_prod = $obj->compte; - if (empty($compta_prod)) { - if ($obj->product_type == 0) - $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); - else - $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); - } - $cpttva = (! empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); - $compta_tva = (! empty($obj->account_tva) ? $obj->account_tva : $cpttva); + $compta_prod = $obj->compte; + if (empty($compta_prod)) { + if ($obj->product_type == 0) + $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); + else + $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); + } + $cpttva = (! empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); + $compta_tva = (! empty($obj->account_tva) ? $obj->account_tva : $cpttva); - //Define array for display vat tx - $def_tva[$obj->rowid]=price($obj->tva_tx); + //Define array for display vat tx + $def_tva[$obj->rowid]=price($obj->tva_tx); - // Situation invoices handling - $line = new FactureLigne($db); - $line->fetch($obj->fdid); - $prev_progress = $line->get_prev_progress($obj->fdid); - if ($obj->type == Facture::TYPE_SITUATION) { - // Avoid divide by 0 - if ($obj->situation_percent == 0) { - $situation_ratio = 0; - } else { - $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent; - } - } else { - $situation_ratio = 1; - } + // Situation invoices handling + $line = new FactureLigne($db); + $line->fetch($obj->fdid); + $prev_progress = $line->get_prev_progress($obj->fdid); + if ($obj->type == Facture::TYPE_SITUATION) { + // Avoid divide by 0 + if ($obj->situation_percent == 0) { + $situation_ratio = 0; + } else { + $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent; + } + } else { + $situation_ratio = 1; + } - // Invoice lines - $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df); - $tabfac[$obj->rowid]["ref"] = $obj->facnumber; - $tabfac[$obj->rowid]["type"] = $obj->type; - $tabfac[$obj->rowid]["description"] = $obj->label_compte; - $tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid; - if (! isset($tabttc[$obj->rowid][$compta_soc])) - $tabttc[$obj->rowid][$compta_soc] = 0; - if (! isset($tabht[$obj->rowid][$compta_prod])) - $tabht[$obj->rowid][$compta_prod] = 0; - if (! isset($tabtva[$obj->rowid][$compta_tva])) - $tabtva[$obj->rowid][$compta_tva] = 0; - $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio; - $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio; - $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; - $tabcompany[$obj->rowid] = array ( - 'id' => $obj->socid, - 'name' => $obj->name, - 'code_client' => $obj->code_compta - ); + // Invoice lines + $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df); + $tabfac[$obj->rowid]["ref"] = $obj->facnumber; + $tabfac[$obj->rowid]["type"] = $obj->type; + $tabfac[$obj->rowid]["description"] = $obj->label_compte; + $tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid; + if (! isset($tabttc[$obj->rowid][$compta_soc])) + $tabttc[$obj->rowid][$compta_soc] = 0; + if (! isset($tabht[$obj->rowid][$compta_prod])) + $tabht[$obj->rowid][$compta_prod] = 0; + if (! isset($tabtva[$obj->rowid][$compta_tva])) + $tabtva[$obj->rowid][$compta_tva] = 0; + $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio; + $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio; + $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; + $tabcompany[$obj->rowid] = array ( + 'id' => $obj->socid, + 'name' => $obj->name, + 'code_client' => $obj->code_compta + ); - $i ++; - } + $i ++; + } } else { - dol_print_error($db); + dol_print_error($db); } -/* - * Action - * FIXME Action must be set before any view part to respect MVC - */ - // Bookkeeping Write if ($action == 'writebookkeeping') { - $now = dol_now(); - $error = 0; + $now = dol_now(); + $error = 0; - foreach ( $tabfac as $key => $val ) { + foreach ( $tabfac as $key => $val ) { + + $errorforline = 0; - $companystatic = new Societe($db); - $invoicestatic = new Facture($db); + $db->begin(); - $companystatic->id = $tabcompany[$key]['id']; - $companystatic->name = $tabcompany[$key]['name']; - $companystatic->client = $tabcompany[$key]['code_client']; + $companystatic = new Societe($db); + $invoicestatic = new Facture($db); - $invoicestatic->id = $key; - $invoicestatic->ref = (string) $val["ref"]; + $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 ) { - $bookkeeping = new BookKeeping($db); - $bookkeeping->doc_date = $val["date"]; - $bookkeeping->doc_ref = $val["ref"]; - $bookkeeping->date_create = $now; - $bookkeeping->doc_type = 'customer_invoice'; - $bookkeeping->fk_doc = $key; - $bookkeeping->fk_docdet = $val["fk_facturedet"]; - $bookkeeping->code_tiers = $tabcompany[$key]['code_client']; - $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; - // $bookkeeping->label_compte = $tabcompany[$key]['name']; - $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers"); - $bookkeeping->montant = $mt; - $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; - $bookkeeping->debit = ($mt >= 0) ? $mt : 0; - $bookkeeping->credit = ($mt < 0) ? $mt : 0; - $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; - $bookkeeping->fk_user_author = $user->id; + $invoicestatic->id = $key; + $invoicestatic->ref = (string) $val["ref"]; - $result = $bookkeeping->create($user); - if ($result < 0) { - $error ++; - setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); - } - } + foreach ( $tabttc[$key] as $k => $mt ) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'customer_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturedet"]; + $bookkeeping->code_tiers = $tabcompany[$key]['code_client']; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + // $bookkeeping->label_compte = $tabcompany[$key]['name']; + $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers"); + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt >= 0) ? $mt : 0; + $bookkeeping->credit = ($mt < 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; + $bookkeeping->fk_user_author = $user->id; - // Product / Service - foreach ( $tabht[$key] as $k => $mt ) { - if ($mt) { - // get compte id and label - $accountingaccount = new AccountingAccount($db); - if ($accountingaccount->fetch(null, $k)) { - $bookkeeping = new BookKeeping($db); - $bookkeeping->doc_date = $val["date"]; - $bookkeeping->doc_ref = $val["ref"]; - $bookkeeping->date_create = $now; - $bookkeeping->doc_type = 'customer_invoice'; - $bookkeeping->fk_doc = $key; - $bookkeeping->fk_docdet = $val["fk_facturedet"]; - $bookkeeping->code_tiers = ''; - $bookkeeping->numero_compte = $k; - $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label; - $bookkeeping->montant = $mt; - $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; - $bookkeeping->debit = ($mt < 0) ? $mt : 0; - $bookkeeping->credit = ($mt >= 0) ? $mt : 0; - $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; - $bookkeeping->fk_user_author = $user->id; + $result = $bookkeeping->create($user); + if ($result < 0) { + $error++; + $errorforline++; + setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); + } + } - $result = $bookkeeping->create($user); - if ($result < 0) { - $error ++; - setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); - } - } - } - } + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + // get compte id and label + $accountingaccount = new AccountingAccount($db); + if ($accountingaccount->fetch(null, $k)) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'customer_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturedet"]; + $bookkeeping->code_tiers = ''; + $bookkeeping->numero_compte = $k; + $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt < 0) ? $mt : 0; + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; + $bookkeeping->fk_user_author = $user->id; - // VAT - // var_dump($tabtva); - foreach ( $tabtva[$key] as $k => $mt ) { - if ($mt) { - $bookkeeping = new BookKeeping($db); - $bookkeeping->doc_date = $val["date"]; - $bookkeeping->doc_ref = $val["ref"]; - $bookkeeping->date_create = $now; - $bookkeeping->doc_type = 'customer_invoice'; - $bookkeeping->fk_doc = $key; - $bookkeeping->fk_docdet = $val["fk_facturedet"]; - $bookkeeping->code_tiers = ''; - $bookkeeping->numero_compte = $k; - $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.$def_tva[$key]; - $bookkeeping->montant = $mt; - $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; - $bookkeeping->debit = ($mt < 0) ? $mt : 0; - $bookkeeping->credit = ($mt >= 0) ? $mt : 0; - $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; - $bookkeeping->fk_user_author = $user->id; + $result = $bookkeeping->create($user); + if ($result < 0) { + $error++; + $errorforline++; + setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); + } + } + } + } - $result = $bookkeeping->create($user); - if ($result < 0) { - $error ++; - setEventMessages($object->error, $object->errors, 'errors'); - } - } - } - } + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'customer_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturedet"]; + $bookkeeping->code_tiers = ''; + $bookkeeping->numero_compte = $k; + $bookkeeping->label_compte = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.$def_tva[$key]; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt < 0) ? $mt : 0; + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; + $bookkeeping->fk_user_author = $user->id; - if (empty($error)) { - setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs'); - } + $result = $bookkeeping->create($user); + if ($result < 0) { + $error++; + $errorforline++; + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } + + + if (! $errorforline) + { + $db->commit(); + } + else + { + $db->rollback(); + } + + } + + if (empty($error) && count($tabpay) > 0) { + 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; - $sell_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; + $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; + $sell_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; - include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; + include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; - $companystatic = new Client($db); + $companystatic = new Client($db); - // 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 ) { - $companystatic->id = $tabcompany[$key]['id']; - $companystatic->name = $tabcompany[$key]['name']; - $companystatic->client = $tabcompany[$key]['code_client']; + foreach ( $tabfac as $key => $val ) { + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; - $invoicestatic->id = $key; - $invoicestatic->ref = $val["ref"]; + $invoicestatic->id = $key; + $invoicestatic->ref = $val["ref"]; - $date = dol_print_date($val["date"], '%d%m%Y'); + $date = dol_print_date($val["date"], '%d%m%Y'); - foreach ( $tabttc[$key] as $k => $mt ) { - print $date . $sep; - print $sell_journal . $sep; - print length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) . $sep; - print length_accounta(html_entity_decode($k)) . $sep; - print ($mt < 0 ? 'C' : 'D') . $sep; - print ($mt <= 0 ? price(- $mt) : $mt) . $sep; - print dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . $sep; - print $val["ref"]; - print "\n"; - } + foreach ( $tabttc[$key] as $k => $mt ) { + print $date . $sep; + print $sell_journal . $sep; + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) . $sep; + print length_accounta(html_entity_decode($k)) . $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . $sep; + print $val["ref"]; + print "\n"; + } - // Product / Service - foreach ( $tabht[$key] as $k => $mt ) { - $accountingaccount_static = new AccountingAccount($db); - if ($accountingaccount_static->fetch(null, $k)) { - print $date . $sep; - print $sell_journal . $sep; - print length_accountg(html_entity_decode($k)) . $sep; - print $sep; - print ($mt < 0 ? 'D' : 'C') . $sep; - print ($mt <= 0 ? price(- $mt) : $mt) . $sep; - print dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount_static->label . $sep; - print $val["ref"]; - print "\n"; - } - } + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + $accountingaccount_static = new AccountingAccount($db); + if ($accountingaccount_static->fetch(null, $k)) { + print $date . $sep; + print $sell_journal . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount_static->label . $sep; + print $val["ref"]; + print "\n"; + } + } - // TVA - foreach ( $tabtva[$key] as $k => $mt ) { - if ($mt) { - print $date . $sep; - print $sell_journal . $sep; - print length_accountg(html_entity_decode($k)) . $sep; - print $sep; - print ($mt < 0 ? 'D' : 'C') . $sep; - print ($mt <= 0 ? price(- $mt) : $mt) . $sep; - print dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . $sep; - // print $langs->trans("VAT") . $sep; - print $val["ref"]; - print "\n"; - } - } - } - } elseif ($conf->global->ACCOUNTING_EXPORT_MODELCSV == 1) { - // Model Classic Export - foreach ( $tabfac as $key => $val ) { - $companystatic->id = $tabcompany[$key]['id']; - $companystatic->name = $tabcompany[$key]['name']; - $companystatic->client = $tabcompany[$key]['code_client']; + // TVA + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print $date . $sep; + print $sell_journal . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . $sep; + // print $langs->trans("VAT") . $sep; + print $val["ref"]; + print "\n"; + } + } + } + } elseif ($conf->global->ACCOUNTING_EXPORT_MODELCSV == 1) { + // Model Classic Export + foreach ( $tabfac as $key => $val ) { + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; - $invoicestatic->id = $key; - $invoicestatic->ref = $val["ref"]; + $invoicestatic->id = $key; + $invoicestatic->ref = $val["ref"]; - $date = dol_print_date($val["date"], 'day'); + $date = dol_print_date($val["date"], 'day'); - 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) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . '"' . $sep; - print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; - print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; - print "\n"; - } + 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) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + print "\n"; + } - // Product / Service - foreach ( $tabht[$key] as $k => $mt ) { - $accountingaccount = new AccountingAccount($db); - $accountingaccount->fetch(null, $k); + // 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) . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep; - print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; - print '"' . ($mt >= 0 ? price($mt) : '') . '"'; - print "\n"; - } - } + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . dol_trunc($companystatic->name, 16) . ' - ' . 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 '"' . dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . '"' . $sep; - print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; - print '"' . ($mt >= 0 ? price($mt) : '') . '"'; - print "\n"; - } - } - } - } -} else { + // 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 '"' . dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + print "\n"; + } + } + } + } +} - $form = new Form($db); +if (empty($action) || $action == 'view') { llxHeader('', $langs->trans("SellsJournal")); @@ -433,7 +467,8 @@ if ($action == 'export_csv') { $periodlink = ''; $exportlink = ''; $builddate = time(); - $description = $langs->trans("DescSellsJournal") . '
'; + //$description = $langs->trans("DescSellsJournal") . '
'; + $description.= $langs->trans("DescJournalOnlyBindedVisible").'
'; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description .= $langs->trans("DepositsAreNotIncluded"); else @@ -473,9 +508,10 @@ if ($action == 'export_csv') { $i = 0; print ""; print ""; + print ""; print ""; print ""; - print ""; + print ""; print ""; print ""; print ""; @@ -497,14 +533,23 @@ if ($action == 'export_csv') { // Third party foreach ( $tabttc[$key] as $k => $mt ) { print ""; + print ""; print ""; print ""; $companystatic->id = $tabcompany[$key]['id']; $companystatic->name = $tabcompany[$key]['name']; $companystatic->client = $tabcompany[$key]['code_client']; - print "'; print ""; print ""; print ""; @@ -518,9 +563,17 @@ if ($action == 'export_csv') { if ($mt) { print ""; + print ""; print ""; print ""; - print ""; + print ""; // print ""; print ""; print ""; @@ -533,9 +586,17 @@ if ($action == 'export_csv') { foreach ( $tabtva[$key] as $k => $mt ) { if ($mt) { print ""; + print ""; print ""; print ""; - print ""; + print ""; print ""; // print ""; print ""; diff --git a/htdocs/accountancy/report/result.php b/htdocs/accountancy/report/result.php index c9c1a13fd14..0031fa3c3b4 100644 --- a/htdocs/accountancy/report/result.php +++ b/htdocs/accountancy/report/result.php @@ -75,7 +75,7 @@ $form = new Form($db); $textprevyear = '' . img_previous() . ''; $textnextyear = ' ' . img_next() . ''; -print load_fiche_titre($langs->trans('ReportInOut') . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear); +print load_fiche_titre($langs->trans('ReportInOut') . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); print '
" . $langs->trans("Date") . "" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("Account") . "" . $langs->trans("AccountAccounting") . "" . $langs->trans("Type") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accounta($k); + $companystatic->client = $tabcompany[$key]['code_client']; + print ""; + $accountoshow = length_accounta($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("ThirdpartyAccountNotDefined").''; + } + else print $accountoshow; // print "" . $langs->trans("ThirdParty"); // print ' (' . $companystatic->getNomUrl(0, 'customer', 16) . ')'; + print '" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . "" . ($mt >= 0 ? price($mt) : '') . "" . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . ""; + $accountoshow = length_accountg($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("ProductNotDefined").''; + } + else print $accountoshow; + print "" . $accountingaccount->label . "" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label . "" . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . ""; + $accountoshow = length_accountg($k); + if (empty($accountoshow) || $accountoshow == 'NotDefined') + { + print ''.$langs->trans("VATAccountNotDefined").''; + } + else print $accountoshow; + print "" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . ' '.$def_tva[$key]. "" . $langs->trans("VAT") . "" . ($mt < 0 ? price(- $mt) : '') . "
'; @@ -103,14 +103,17 @@ foreach($months as $k => $v){ print ''; $cats = $AccCat->getCatsCpts(); +if ($cats < 0) dol_print_error($db, $AccCat->error, $AccCat->errors); + $catsCalcule = $AccCat->getCatsCal(); +if ($catsCalcule < 0) dol_print_error($db, $AccCat->error, $AccCat->errors); $j=1; $sommes = array(); -if(!empty($cats)) +if (!empty($cats)) { - foreach ( $cats as $name_cat => $cpts ) + foreach ($cats as $name_cat => $cpts) { print ""; print ''; diff --git a/htdocs/accountancy/supplier/card.php b/htdocs/accountancy/supplier/card.php index e0eb900b1c1..b8e709e152d 100644 --- a/htdocs/accountancy/supplier/card.php +++ b/htdocs/accountancy/supplier/card.php @@ -44,23 +44,35 @@ $id = GETPOST('id'); if ($user->societe_id > 0) accessforbidden(); -if ($action == 'ventil' && $user->rights->accounting->ventilation->dispatch) { + +/* + * Actions + */ + +if ($action == 'ventil' && $user->rights->accounting->bind->write) { if (! GETPOST('cancel', 'alpha')) { + if ($codeventil < 0) $codeventil = 0; + $sql = " UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det"; $sql .= " SET fk_code_ventilation = " . $codeventil; $sql .= " WHERE rowid = " . $id; - dol_syslog('accountancy/supplier/card.php:: $sql=' . $sql); $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 */ @@ -70,9 +82,7 @@ if ($cancel == $langs->trans("Cancel")) { $action = ''; } -/* - * Create - */ +// Create $form = new Form($db); $facturefournisseur_static = new FactureFournisseur($db); $formventilation = new FormVentilation($db); @@ -86,9 +96,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_fourn as f ON f.rowid = l.fk_facture_fourn "; $sql .= " WHERE f.fk_statut > 0 AND l.rowid = " . $id; - 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 dol_syslog("/accounting/supplier/card.php sql=" . $sql, LOG_DEBUG); $result = $db->query($sql); diff --git a/htdocs/accountancy/supplier/index.php b/htdocs/accountancy/supplier/index.php index 2506267ac15..f9a5100adbc 100644 --- a/htdocs/accountancy/supplier/index.php +++ b/htdocs/accountancy/supplier/index.php @@ -23,9 +23,8 @@ * \ingroup Advanced accountancy * \brief Home supplier 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'; @@ -37,9 +36,12 @@ $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 @@ -54,11 +56,28 @@ 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 . "facture_fourn_det"; $sql1 .= " SET fk_code_ventilation = accnt.rowid"; @@ -138,17 +157,17 @@ llxHeader('', $langs->trans("SuppliersVentilation")); $textprevyear = '' . img_previous() . ''; $textnextyear = ' ' . img_next() . ''; -print load_fiche_titre($langs->trans("SuppliersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear); +print load_fiche_titre($langs->trans("SuppliersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); print $langs->trans("DescVentilSupplier") . '
'; -print $langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToDispatch")) . '
'; +print $langs->trans("DescVentilMore", $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. -print '' . $langs->trans("CleanFixHistory", $year_current) . ''; +if ($conf->global->MAIN_FEATURES_LEVEL > 0) print '' . $langs->trans("CleanFixHistory", $year_current) . ''; print '
'; $y = $year_current; @@ -175,10 +194,7 @@ $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid $sql .= " WHERE ff.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; $sql .= " AND ff.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; $sql .= " AND ff.fk_statut > 0 "; - -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND ff.entity IN (" . getEntity("facture_fourn", 1) . ")"; -} +$sql .= " AND ff.entity IN (" . getEntity("facture_fourn", 0) . ")"; // We don't share object for accountancy $sql .= " GROUP BY ffd.fk_code_ventilation,aa.account_number,aa.label"; @@ -223,10 +239,7 @@ $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture_fourn as ff ON ff.rowid = ffd $sql .= " WHERE ff.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; $sql .= " AND ff.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; $sql .= " AND ff.fk_statut > 0 "; - -if (! empty($conf->multicompany->enabled)) { - $sql .= " AND ff.entity IN (" . getEntity("facture_fourn", 1) . ")"; -} +$sql .= " AND ff.entity IN (" . getEntity("facture_fourn", 0) . ")"; // We don't share object for accountancy dol_syslog('/accountancy/supplier/index.php:: sql=' . $sql); $resql = $db->query($sql); diff --git a/htdocs/accountancy/supplier/lines.php b/htdocs/accountancy/supplier/lines.php index bbb76f7c15c..94af5c82dba 100644 --- a/htdocs/accountancy/supplier/lines.php +++ b/htdocs/accountancy/supplier/lines.php @@ -51,36 +51,27 @@ $search_amount = GETPOST('search_amount', 'alpha'); $search_account = GETPOST('search_account', 'alpha'); $search_vat = GETPOST('search_vat', '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; $offset = $conf->liste_limit * $page; $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; -} if (! $sortfield) $sortfield = "f.datef, f.ref, l.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); @@ -124,6 +115,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 } @@ -182,41 +175,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_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/lines.php::list sql= ' . $sql1); +dol_syslog('accountancy/supplier/lines.php::list'); $result = $db->query($sql); if ($result) { $num_lines = $db->num_rows($result); $i = 0; - print_barre_liste($langs->trans("InvoiceLinesDone"), $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_invoice) + $param .= "&search_invoice=" . $search_invoice; + if ($search_ref) + $param .= "&search_ref=" . $search_ref; + 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 ''; + 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 ''; - print '
' . $name_cat . '' . $langs->trans("DescVentilDoneSupplier") . '
'; + print $langs->trans("DescVentilDoneSupplier") . '
'; print '
' . $langs->trans("ChangeAccount") . '
'; print $formventilation->select_account(GETPOST('account_parent'), 'account_parent', 1); - print '
'; + print ''; + + $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("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="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"], "l.rowid", "", $param, 'align="right"', $sortfield, $sortorder); print_liste_field_titre(''); - print_liste_field_titre(''); - print_liste_field_titre($langs->trans("Ventilate") . '
/', '', '', '', '', 'align="center"'); + print_liste_field_titre('', '', '', '', '', 'align="center"'); print "\n"; print ''; @@ -224,11 +254,12 @@ if ($result) { print ''; print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; + print ''; print ''; print "\n"; @@ -242,7 +273,7 @@ if ($result) { $var = ! $var; $codeCompta = length_accountg($objp->account_number) . ' - ' . $objp->label; - print ''; + print ''; // Ref Invoice $facturefournisseur_static->ref = $objp->facnumber; @@ -253,6 +284,7 @@ if ($result) { $product_static->ref = $objp->product_ref; $product_static->id = $objp->product_id; $product_static->type = $objp->type; + $product_static->label = $objp->product_label; print ''; - print ''; + print ''; print ""; $i ++; @@ -279,7 +311,14 @@ if ($result) { print $db->error(); } -print "
% '; - $searchpitco=$form->showFilterAndCheckAddButtons(0); + $searchpitco=$form->showFilterAndCheckAddButtons(1); print $searchpitco; print '
'; if ($product_static->id) print $product_static->getNomUrl(1); @@ -270,7 +302,7 @@ if ($result) { print img_edit(); print '
"; +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/supplier/list.php b/htdocs/accountancy/supplier/list.php index c98ba050222..bd0dac49096 100644 --- a/htdocs/accountancy/supplier/list.php +++ b/htdocs/accountancy/supplier/list.php @@ -4,6 +4,7 @@ * 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 @@ -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'); -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.ref, 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); @@ -98,91 +90,80 @@ $accounting = new AccountingAccount($db); $aarowid_s = $accounting->fetch('', $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT, 1); $aarowid_p = $accounting->fetch('', $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT, 1); + +/* + * Action + */ + // 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")) // All test are required to be compatible with all browsers { - $search_ref = ''; - $search_label = ''; - $search_desc = ''; - $search_amount = ''; - $search_account = ''; - $search_vat = ''; + $search_ref = ''; + $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 . "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)) { + $ok++; + $msg.= '
' . $langs->trans("Lineofinvoice") . ' ' . $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("SuppliersVentilation")); -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/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/card.php b/htdocs/adherents/card.php index 05a6772163e..ddbc7123d70 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -39,6 +39,7 @@ 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"); @@ -51,6 +52,7 @@ $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)) @@ -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; @@ -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 99de04bf000..db4c631c0c9 100644 --- a/htdocs/adherents/cartes/carte.php +++ b/htdocs/adherents/cartes/carte.php @@ -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 41fd2753109..79c12e68561 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -1070,6 +1070,7 @@ 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.subscription as subscription,"; @@ -1154,6 +1155,8 @@ class Adherent extends CommonObject $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 @@ -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) @@ -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. diff --git a/htdocs/adherents/class/adherent_type.class.php b/htdocs/adherents/class/adherent_type.class.php index 5fb3d8140bd..7520bdbf6a5 100644 --- a/htdocs/adherents/class/adherent_type.class.php +++ b/htdocs/adherents/class/adherent_type.class.php @@ -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 $subscription; // Subscription required - var $note; - var $vote; // Can vote - var $mail_valid; // mail sent during 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; /** diff --git a/htdocs/adherents/class/api_members.class.php b/htdocs/adherents/class/api_members.class.php index d18bbdbc106..548b5728b1a 100644 --- a/htdocs/adherents/class/api_members.class.php +++ b/htdocs/adherents/class/api_members.class.php @@ -84,13 +84,12 @@ class Members extends DolibarrApi * @param int $limit Limit for list * @param int $page Page number * @param string $typeid ID of the type of member - * @param string $login To filter the members by login - * @param string $name To filter the members by name (firstname, lastname or company name matching the filter) - * @return array Array of member objects + * @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 = "a.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $typeid = '', $login = '', $name = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $typeid = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -99,27 +98,24 @@ class Members extends DolibarrApi throw new RestException(401); } - $sql = "SELECT a.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."adherent as a"; - $sql.= ' WHERE a.entity IN ('.getEntity('adherent', 1).')'; + $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 a.fk_adherent_type='.$typeid; + $sql.= ' AND t.fk_adherent_type='.$typeid; } - if (!empty($login)) { - $sql .= " AND a.login LIKE '%".$login."%'"; - } - if (!empty($name)) { - $sql .= " AND (a.firstname LIKE '%".$name."%' OR a.lastname LIKE '%".$name."%' OR a.societe LIKE '%".$name."%')"; - } - - $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) @@ -271,7 +267,7 @@ class Members extends DolibarrApi /** * Validate fields before creating an object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * * @throws RestException diff --git a/htdocs/adherents/class/api_subscriptions.class.php b/htdocs/adherents/class/api_subscriptions.class.php index 4f8435c3a1d..2dd2a609e63 100644 --- a/htdocs/adherents/class/api_subscriptions.class.php +++ b/htdocs/adherents/class/api_subscriptions.class.php @@ -80,11 +80,12 @@ class Subscriptions 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.import_key:<:'20160101')" * @return array Array of subscription objects * * @throws RestException */ - function index($sortfield = "dateadh", $sortorder = 'ASC', $limit = 0, $page = 0) { + function index($sortfield = "dateadh", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -94,15 +95,19 @@ class Subscriptions extends DolibarrApi } $sql = "SELECT rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."subscription"; - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + $sql.= " FROM ".MAIN_DB_PREFIX."subscription as t"; + $sql.= ' WHERE 1 = 1'; + // 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) @@ -225,7 +230,7 @@ class Subscriptions extends DolibarrApi /** * Validate fields before creating an object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * * @throws RestException 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/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 d3e7e96a793..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,8 +184,6 @@ $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,"; @@ -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 '
'.$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).'">
'."\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->subscription == '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->subscription,$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/subscription/card.php b/htdocs/adherents/subscription/card.php index fb762a24345..ce3baee712b 100644 --- a/htdocs/adherents/subscription/card.php +++ b/htdocs/adherents/subscription/card.php @@ -21,7 +21,7 @@ * \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/subscription.class.php'; diff --git a/htdocs/adherents/subscription/info.php b/htdocs/adherents/subscription/info.php index 4e82d959a28..5c5799ec2a5 100644 --- a/htdocs/adherents/subscription/info.php +++ b/htdocs/adherents/subscription/info.php @@ -22,7 +22,7 @@ * \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'; diff --git a/htdocs/adherents/subscription/list.php b/htdocs/adherents/subscription/list.php index c46c1ee0904..6062bb12567 100644 --- a/htdocs/adherents/subscription/list.php +++ b/htdocs/adherents/subscription/list.php @@ -23,7 +23,7 @@ * \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/subscription.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php index 2fe4f0a6037..9ea048c27fd 100644 --- a/htdocs/admin/agenda_other.php +++ b/htdocs/admin/agenda_other.php @@ -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/dict.php b/htdocs/admin/dict.php index fbe0a471e3d..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')); @@ -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,6 +583,16 @@ 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')) { @@ -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 @@ -706,7 +722,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) $_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++; } @@ -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 ''; // 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 { @@ -1268,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); } @@ -1369,24 +1453,26 @@ 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 = ''; - $align="right"; + $align="center"; } else if ($fieldlist[$field]=='localtax2_type') { if ($obj->localtax2 != 0) $valuetoshow=$localtax_typeList[$valuetoshow]; else $valuetoshow = ''; - $align="right"; + $align="center"; } else if ($fieldlist[$field]=='taux') { $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - $align="right"; + $align="center"; } else if (in_array($fieldlist[$field],array('recuperableonly'))) { @@ -1417,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 @@ -1446,7 +1534,13 @@ if ($id) else print ''; // Delete link - if ($iserasable) print ''; + if ($iserasable) + { + print ''; + } else print ''; print "\n"; @@ -1625,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'))) { @@ -1687,12 +1786,14 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') print ''; } @@ -1702,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 a9a588ae4d7..01f2736d718 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -77,6 +77,7 @@ 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; @@ -89,6 +90,7 @@ $actiontypecode=''; $trigger_name=''; $paramname='id'; $mode='emailfortest'; +$trackid=(($action == 'testhtml')?"testhtml":"test"); include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; if ($action == 'presend' && GETPOST('trackid') == 'test') $action='test'; @@ -391,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 ''; @@ -409,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 ' 
'; - 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); + $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 ''; } @@ -517,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; @@ -539,6 +571,7 @@ else } print ''; + print ''; if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) @@ -558,6 +591,7 @@ else print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); } + // Boutons actions 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/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/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 ''; +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/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/filecheck.php b/htdocs/admin/system/filecheck.php index 428c3fde2d8..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"); @@ -77,32 +78,37 @@ $file_list = array('missing' => array(), 'updated' => array()); $xmlshortfile = '/install/filelist-'.DOL_VERSION.'.xml'; $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; - -$enableremotecheck = False; + + +// 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)) { - print ' '.$langs->trans("LocalSignature").' = '.$xmlshortfile.'
'; + print ' '.$langs->trans("LocalSignature").' = '.$xmlshortfile.'
'; } else { - print ' '.$langs->trans("LocalSignature").' = '.$xmlshortfile.' ('.$langs->trans("AvailableOnlyOnPackagedVersions").')
'; + print ' '.$langs->trans("LocalSignature").' = '.$xmlshortfile.' ('.$langs->trans("AvailableOnlyOnPackagedVersions").')
'; } if ($enableremotecheck) { - print ' '.$langs->trans("RemoteSignature").' = '.$xmlremote.'
'; + print ' '.$langs->trans("RemoteSignature").' = '.$xmlremote.'
'; } else { - print ' '.$langs->trans("RemoteSignature").' = '.$xmlremote.' ('.$langs->trans("FeatureNotYetAvailable").')
'; + print ' '.$langs->trans("RemoteSignature").' = '.$xmlremote.' ('.$langs->trans("FeatureAvailableOnlyOnStable").')
'; } print '
'; print '
'; print '
'; +print '
'; -if (GETPOST('local')) +if (GETPOST('target') == 'local') { if (dol_is_file($xmlfile)) { @@ -114,17 +120,20 @@ if (GETPOST('local')) $error++; } } -if (GETPOST('remote')) +if (GETPOST('target') == 'remote') { - // TODO - //$xmlfile = ; - if (1 == 1) + $xmlarray = getURLContent($xmlremote); + + // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) + if (! $xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') { - //$xml = simplexml_load_file($xmlfile); + $xmlfile = $xmlarray['content']; + $xml = simplexml_load_file($xmlfile); } else { - print $langs->trans('XmlNotFound') . ': ' . $xmlfile; + $errormsg=$langs->trans('XmlNotFound') . ': ' . $xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; + setEventMessages($errormsg, null, 'errors'); $error++; } } 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 "\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 ''; print ''; @@ -230,10 +230,10 @@ if ($mode == 'overwrite') print ''; } else - { + {*/ print ''; print ''; - } + //} print ''; 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 ''; print ''; // Limit to superadmin - if (! empty($conf->multicompany->enabled) && !$user->entity) + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''; print ''; } else - { + {*/ print ''; - } + //} print ''; // Action column - print ''; + print ''; $searchpitco=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); print $searchpitco; 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 ''.$valuetoshow.''; @@ -613,14 +614,15 @@ function fieldListWebsites($fieldlist, $obj='', $tabname='', $context='') foreach ($fieldlist as $field => $value) { + $fieldname = $fieldlist[$field]; if ($fieldlist[$field] == 'lang') { print ''; print $formadmin->select_language($conf->global->MAIN_LANG_DEFAULT,'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 75b0ce6d808..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,8 +73,10 @@ 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. @@ -108,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 a1660be133d..45f2be3e4da 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -162,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_dictionnarycountries.class.php b/htdocs/api/class/api_dictionnarycountries.class.php index 0243d27c81b..9b7b409ef19 100644 --- a/htdocs/api/class/api_dictionnarycountries.class.php +++ b/htdocs/api/class/api_dictionnarycountries.class.php @@ -54,27 +54,31 @@ class DictionnaryCountries extends DolibarrApi * @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 = '') + 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"; - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; + $sql.=" WHERE 1 = 1"; + // Add sql filters + if ($sqlfilters) { - $result = $this->db->query($sql); - $nbtotalofrecords = $this->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.= $this->db->order($sortfield, $sortorder); - if ($limit) { if ($page < 0) { diff --git a/htdocs/api/class/api_dictionnarytowns.class.php b/htdocs/api/class/api_dictionnarytowns.class.php index b028ff4af03..b5813d07792 100644 --- a/htdocs/api/class/api_dictionnarytowns.class.php +++ b/htdocs/api/class/api_dictionnarytowns.class.php @@ -47,27 +47,32 @@ class DictionnaryTowns extends DolibarrApi * @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 = '') + 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"; - $sql.= " WHERE active = 1"; - if ($zipcode) $sql.=" AND zip LIKE '%" . $this->db->escape($zipcode) . "%'"; - if ($town) $sql.=" AND town LIKE '%" . $this->db->escape($town) . "%'"; - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + $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) { - $result = $this->db->query($sql); - $nbtotalofrecords = $this->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.= $this->db->order($sortfield, $sortorder); if ($limit) { diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index bea6061e0fe..616ffcc31cd 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -98,11 +98,12 @@ class Categories extends DolibarrApi * @param int $limit Limit for list * @param int $page Page number * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact') - * @return array Array of category objects + * @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($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $type = '') { + 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) @@ -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 e18ada34e0a..106927a1a33 100644 --- a/htdocs/categories/class/api_deprecated_category.class.php +++ b/htdocs/categories/class/api_deprecated_category.class.php @@ -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/comm/action/card.php b/htdocs/comm/action/card.php index 60b3083d0f7..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 @@ -852,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"]); @@ -1100,8 +1101,10 @@ if ($id > 0) print ''; print ''; @@ -1122,8 +1125,8 @@ if ($id > 0) $langs->load("projects"); - print ''; @@ -1141,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)) { @@ -1469,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 b190047bac7..419b32cdea4 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -514,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 "; @@ -535,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; @@ -1018,7 +1019,7 @@ 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); } /** @@ -1027,9 +1028,10 @@ class ActionComm extends CommonObject * @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=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; @@ -1078,7 +1080,7 @@ class ActionComm extends CommonObject else if ($mode == 6) { 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) 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'); } @@ -1102,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; @@ -1118,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) @@ -1161,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 index c245476bdcc..db828656966 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -94,10 +94,10 @@ class AgendaEvents extends DolibarrApi * @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} - * - * @return array Array of Agenda Events objects + * @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) { + function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 0, $page = 0, $user_ids = 0, $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -108,21 +108,23 @@ class AgendaEvents extends DolibarrApi $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 ar.fk_user_action IN (".$user_ids.")"; - + 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; } - - $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) 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/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 '
".$langs->trans("Parameter")."".$langs->trans("Value")."'.$langs->trans("Value")." 
'.$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").''; @@ -1132,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); @@ -1153,7 +1156,7 @@ if ($id > 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 1bdf4e75e5d..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 @@ -89,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'); @@ -217,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 ''; } @@ -234,7 +233,7 @@ if ($id > 0) $langs->load("compta"); print ''; @@ -242,7 +241,7 @@ if ($id > 0) print ''; print ''; print ''; @@ -251,12 +250,12 @@ if ($id > 0) // Skype if (! empty($conf->skype->enabled)) { - print ''; + print ''; } // Assujeti a TVA ou pas print ''; - print ''; print ''; @@ -264,20 +263,20 @@ if ($id > 0) // Local Taxes if ($mysoc->useLocalTax(1)) { - print ''; } if ($mysoc->useLocalTax(2)) { - print ''; } // TVA Intra - print ''; @@ -289,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); @@ -308,7 +307,7 @@ if ($id > 0) print ''; if (($action != 'editmode') && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('SetMode'),1).''; print ''; - print ''; + print ''; if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->mode_reglement_id,'mode_reglement_id'); @@ -323,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); @@ -350,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) @@ -365,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).''; @@ -373,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)) { @@ -399,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); @@ -407,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 ''; @@ -445,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'); @@ -462,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 ""; } @@ -484,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) @@ -503,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(); @@ -519,14 +511,33 @@ if ($id > 0) } 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").'
'; + 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 '
'; 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 ''; - print ''; + print ''; print ''; // Title print ''; - print ''; + print ''; 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 2d21c0049a1..6b47d5205b6 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -26,11 +26,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'; @@ -136,6 +138,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); @@ -609,6 +640,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'; @@ -1607,6 +1639,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); } @@ -1675,7 +1710,7 @@ if ($action == 'create') $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') . ' : ' . $soc->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); // Project if (! empty($conf->projet->enabled)) { @@ -2080,8 +2115,26 @@ if ($action == 'create') 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 ''; print ''; print ''; @@ -2109,24 +2162,6 @@ if ($action == 'create') 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 ''; @@ -2337,8 +2372,6 @@ if ($action == 'create') if ($action != 'presend') { 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, '', $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 ''; // ancre /* * Documents generes @@ -2351,7 +2384,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')); @@ -2359,14 +2392,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 '
'; } @@ -2418,10 +2449,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 index 95698154870..84a7a1a1a1c 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -90,10 +90,10 @@ class Proposals extends DolibarrApi * @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} - * - * @return array Array of order objects + * @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, $thirdparty_ids = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -103,30 +103,32 @@ class Proposals extends DolibarrApi // 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 s.rowid"; + $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 s"; + $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 s.entity IN ('.getEntity('propal', 1).')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc"; - if ($socids) $sql.= " AND s.fk_soc IN (".$socids.")"; - 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('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; } - - $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) diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 9c5ac5e40cb..dc297e9df12 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -389,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 @@ -454,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); @@ -496,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; @@ -629,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]; @@ -681,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; @@ -3214,44 +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=''; if ($withpicto) - $result.=($link.img_object($label, $this->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; } @@ -3265,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; @@ -3307,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; @@ -3662,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,'; @@ -3677,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).","; @@ -3747,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; @@ -3773,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(); @@ -3846,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 7441fb751b9..7e759917604 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -79,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'); @@ -160,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 @@ -440,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; @@ -1013,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 89f31256717..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,10 +69,9 @@ 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); dol_fiche_head($head, 'note', $langs->trans('Proposal'), 0, 'propal'); @@ -81,71 +79,64 @@ if ($id > 0 || ! empty($ref)) $cssclass='titlefield'; //if ($action == 'editnote_public') $cssclass='titlefieldcreate'; //if ($action == 'editnote_private') $cssclass='titlefieldcreate'; - - 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) + + + // 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 3f1f440ce31..313fef16e2c 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -60,13 +60,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'); @@ -1256,6 +1256,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'; @@ -1764,16 +1765,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 @@ -1980,52 +1977,6 @@ if ($action == 'create' && $user->rights->commande->creer) 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 '
'; - // Ref - /* - print ''; - print ''; - print ''; - - // Ref commande client - print ''; - print ''; - - // Third party - print '';*/ - if ($soc->outstanding_limit) { // Outstanding Bill @@ -2294,29 +2245,6 @@ if ($action == 'create' && $user->rights->commande->creer) // TODO How record was recorded OrderMode (llx_c_input_method) - // Project - /* - if (! empty($conf->projet->enabled)) - { - $langs->load('projects'); - print ''; - } - */ - // Incoterms if (!empty($conf->incoterm->enabled)) { @@ -2373,8 +2301,26 @@ if ($action == 'create' && $user->rights->commande->creer) 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 '
'; - 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 '
'; + 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 ''; // Total VAT @@ -2395,24 +2341,6 @@ if ($action == 'create' && $user->rights->commande->creer) // Total TTC 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 ''; @@ -2635,7 +2563,7 @@ 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 @@ -2701,10 +2629,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_orders.class.php b/htdocs/commande/class/api_orders.class.php index 6ba66a78013..f000e4ce201 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -80,20 +80,22 @@ class Orders extends DolibarrApi 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 $thirdparty_ids Thirdparty ids to filter orders of. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} - * - * @return array Array of order objects + * @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 = 100, $page = 0, $thirdparty_ids = '') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -103,30 +105,32 @@ class Orders extends DolibarrApi // 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 s.rowid"; + $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 s"; + $sql.= " FROM ".MAIN_DB_PREFIX."commande 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 s.entity IN ('.getEntity('commande', 1).')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc"; - if ($socids) $sql.= " AND s.fk_soc IN (".$socids.")"; - 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('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) @@ -138,6 +142,7 @@ class Orders extends DolibarrApi $sql.= $db->plimit($limit + 1, $offset); } + dol_syslog("API Rest request"); $result = $db->query($sql); if ($result) diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 25a19868a45..0ae5ab4b217 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -1285,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); @@ -1327,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; @@ -1727,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,'; @@ -1762,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; @@ -2774,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); @@ -2848,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; @@ -3325,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; @@ -3344,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; @@ -3572,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 @@ -3918,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,'; @@ -3930,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)."',"; 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 b1abbcfb6b5..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'); @@ -153,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; @@ -203,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++; + } + +} /* @@ -403,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) { @@ -416,8 +640,9 @@ 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); // Lines of title fields @@ -469,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; @@ -527,6 +754,46 @@ if ($resql) dol_fiche_end(); } + elseif ($massaction == 'createbills') + { + //var_dump($_REQUEST); + 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) . '
' . $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)) . '
' . 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 ''; + 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) { @@ -641,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'])) { @@ -686,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'])) @@ -747,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 ''; @@ -1155,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) { @@ -1171,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 8cbf532c89a..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 ''; // 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($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 a26062e2bac..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; } @@ -1364,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(); @@ -1387,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 @@ -1497,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 @@ -1617,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)."'"; @@ -1767,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 index 250faea5a5d..7de67119d2b 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -56,11 +56,12 @@ class BankAccounts extends DolibarrApi * @param string $sortorder Sort order * @param int $limit Limit for list * @param int $page Page number - * @return array List of account objects + * @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 = "rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $sqlfilters = '') { $list = array(); @@ -68,13 +69,17 @@ class BankAccounts extends DolibarrApi throw new RestException(401); } - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank_account"; - - $nbtotalofrecords = 0; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."bank_account as t"; + $sql.= ' WHERE t.entity IN ('.getEntity('banque', 1).')'; + // Add sql filters + if ($sqlfilters) { - $result = $this->db->query($sql); - $nbtotalofrecords = $this->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.= $this->db->order($sortfield, $sortorder); @@ -88,6 +93,7 @@ class BankAccounts extends DolibarrApi $sql.= $this->db->plimit($limit + 1, $offset); } + dol_syslog("API Rest request"); $result = $this->db->query($sql); if ($result) { @@ -100,7 +106,7 @@ class BankAccounts extends DolibarrApi } } } else { - throw new RestException(503, 'Error when retrieving list of accounts: ' . $account->error); + throw new RestException(503, 'Error when retrieving list of accounts: ' . $this->db->lasterror()); } return $list; @@ -220,7 +226,7 @@ class BankAccounts extends DolibarrApi /** * Validate fields before creating an object * - * @param array $data Data to validate + * @param array|null $data Data to validate * @return array * * @throws RestException 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 0bd855b928a..56735d15fce 100644 --- a/htdocs/compta/bank/index.php +++ b/htdocs/compta/bank/index.php @@ -39,6 +39,9 @@ $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'); @@ -46,7 +49,7 @@ $optioncss = GETPOST('optioncss','alpha'); if ($user->societe_id) $socid=$user->societe_id; $result=restrictedArea($user,'banque'); -$diroutputmassaction=$conf->banque->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction=$conf->bank->dir_output . '/temp/massgeneration/'.$user->id; $limit = GETPOST("limit")?GETPOST("limit","int"):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -115,7 +118,10 @@ 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 { $statut = 'all'; - + $search_ref=''; + $search_label=''; + $search_number=''; + $search_statut=''; } @@ -124,6 +130,8 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETP * View */ +$form=new Form($db); + $title=$langs->trans('BankAccounts'); // Load array of financial accounts (opened by default) @@ -139,9 +147,11 @@ $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 == 'opened') $sql.= " AND clos = 0"; -if ($statut == 'closed') $sql.= " AND clos = 1"; - +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) { @@ -202,6 +212,9 @@ $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; @@ -266,8 +279,8 @@ 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['accountype']['checked'])) print_liste_field_titre($arrayfields['accountype']['label'],$_SERVER["PHP_SELF"],'','',$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); @@ -300,19 +313,19 @@ if (! empty($arrayfields['b.ref']['checked'])) print ''; print ''; } -// Account type -if (! empty($arrayfields['accountype']['checked'])) -{ - print ''; -} -// Ref +// Label if (! empty($arrayfields['b.label']['checked'])) { print ''; } +// Account type +if (! empty($arrayfields['accountype']['checked'])) +{ + print ''; +} // Number if (! empty($arrayfields['b.number']['checked'])) { @@ -401,17 +414,12 @@ foreach ($accounts as $key=>$type) $var = !$var; $solde = $acc->solde(1); - - - - print ''; print ''; + print ''; print ''; - print ''; print ''; print ''; - print ''; + // Status + print ''; + // print ''; // Action column @@ -447,11 +457,11 @@ foreach ($accounts as $key=>$type) $total[$acc->currency_code] += $solde; //} } -if (! $found) print ''; +if (! $found) print ''; // Total foreach ($total as $key=>$solde) { - print ''; + print ''; } print '
'; - print ''; print ''; print ''; + print '
'.$acc->getNomUrl(1).''.$acc->label.''; - print $langs->trans("CashAccounts"); print $acc->type_lib[$acc->type]; print ''.$acc->bank.''.$acc->number.''; if ($acc->rappro) @@ -426,9 +434,11 @@ 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("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).'
'; 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 5c1e3446e8d..00000000000 --- a/htdocs/compta/bank/search.php +++ /dev/null @@ -1,620 +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("bills"); -$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','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_thirdparty=GETPOST("thirdparty",'alpha'); -$search_req_nb=GETPOST("req_nb",'alpha'); -$search_num_releve=GETPOST("search_num_releve",'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'; - -// Initialize technical object to manage context to save list fields -$contextpage='banktransactionlist'; - -// 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('banktransaction'); -$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); - -$arrayfields=array( - 'b.rowid'=>array('label'=>$langs->trans("Ref"), '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), - 'description'=>array('label'=>$langs->trans("Description"), 'checked'=>1), - 'bu.label'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>500), - 'b.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1, 'position'=>600), - 'b.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1, 'position'=>605), - 'ba.ref'=>array('label'=>$langs->trans("Account"), '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=''; - $description=""; - $type=""; - $debit=""; - $credit=""; - $account=""; - $bid=""; - $search_ref=""; - $search_req_nb=''; - $search_thirdparty=''; - $search_num_releve=''; - $thirdparty=''; -} - -if (empty($reshook)) -{ - $objectclass='Account'; - $objectlabel='BankTransaction'; - $permtoread = $user->rights->banque->lire; - $permtodelete = $user->rights->banque->supprimer; - $uploaddir = $conf->banque->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; -} - - -/* - * 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"; -// 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 ($search_ref) $sql.=natural_search("b.rowid", $search_ref); -if ($account > 0) $sql.=" AND b.fk_account = ".$account; -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.=" 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); -// 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; -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); - - $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 (!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 ($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); - } - - // 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); - - // Lines of title fields - print '
'."\n"; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (! empty($_REQUEST['bid'])) print ''; - - $i = 0; - - // 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, $massactionbutton, $num, $nbtotalofrecords, 'title_bank.png', 0, '', '', $limit); - } - else - { - print_barre_liste($langs->trans("BankTransactions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $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 .= '
'; - - $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 '
'.$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"; - - // 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['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','',$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['description']['checked'])) print_liste_field_titre($arrayfields['description']['label'],$_SERVER['PHP_SELF'],'','',$param,'',$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['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['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.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($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="right"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; - - print ''; - if (! empty($arrayfields['b.rowid']['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['description']['checked'])) - { - print ''; - } - if (! empty($arrayfields['bu.label']['checked'])) - { - print ''; - } - if (! empty($arrayfields['b.debit']['checked'])) - { - print ''; - } - if (! empty($arrayfields['b.credit']['checked'])) - { - print ''; - } - if (! empty($arrayfields['ba.ref']['checked'])) - { - print ''; - } - if (! empty($arrayfields['b.num_releve']['checked'])) - { - // Numero - print ''; - } - print ''; - print "\n"; - - // Loop on each record - $totalarray=array(); - while ($i < min($num,$limit)) - { - $objp = $db->fetch_object($resql); - - // Why this ? - $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 - if (! empty($arrayfields['b.rowid']['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_releve']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } - - // Description - if (! empty($arrayfields['description']['checked'])) - { - print "'; - if (! $i) $totalarray['nbfield']++; - } - - // Third party - if (! empty($arrayfields['bu.label']['checked'])) - { - print "'; - 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']; - } - - // Bank account - if (! empty($arrayfields['ba.ref']['checked'])) - { - print '\n"; - if (! $i) $totalarray['nbfield']++; - } - - if (! empty($arrayfields['b.num_releve']['checked'])) - { - print '\n"; - 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 '  '; - $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($massactionbutton?1:0, 'checkforselect', 1); - 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 ''; - 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 "'; - $bankaccountstatic->id=$objp->bankid; - $bankaccountstatic->label=$objp->bankref; - print $bankaccountstatic->getNomUrl(1); - print "'.($objp->num_releve?$objp->num_releve:"")."'; - 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/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/facture.php b/htdocs/compta/facture.php index b2f1edc15c3..3ee875b5d93 100644 --- a/htdocs/compta/facture.php +++ b/htdocs/compta/facture.php @@ -894,7 +894,7 @@ if (empty($reshook)) // Source facture $object->fac_rec = GETPOST('fac_rec'); - $id = $object->create($user); + $id = $object->create($user); // This include recopy of links from recurring invoice } } @@ -1054,9 +1054,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 @@ -1781,6 +1782,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'; @@ -2318,7 +2320,7 @@ if ($action == 'create') '; $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' '; // $text.=''; - $text .= ' '; @@ -2897,7 +2899,7 @@ else if ($id > 0 || ! empty($ref)) $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') . ' : ' . $soc->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); // Project if (! empty($conf->projet->enabled)) { @@ -2931,83 +2933,16 @@ else if ($id > 0 || ! empty($ref)) } } $morehtmlref.='
'; - + $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 ''; - - // Ref - /* - print ''; - print ''; - - // Ref customer - print ''; - print ''; - - // Third party - print '';*/ // Type print ''; } - // Conditions de reglement + // Payment term 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; - } - 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 '
' . $langs->trans('Type') . ''; @@ -3075,7 +3010,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 . ')'); } @@ -3165,7 +3100,7 @@ else if ($id > 0 || ! empty($ref)) print '
'; print ''; // Multicurrency rate - print ''; - print ''; + //if ($object->multicurrency_code != $conf->currency) + //{ + print ''; + print ''; + //} } // Bank Account @@ -3288,7 +3226,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)) { @@ -3337,37 +3275,6 @@ else if ($id > 0 || ! empty($ref)) } } - // Statut - /* - print ''; - print ''; - - // Project - if (! empty($conf->projet->enabled)) { - $langs->load('projects'); - print ''; - print ''; - print ''; - }*/ - // Incoterms if (!empty($conf->incoterm->enabled)) { @@ -3396,7 +3303,7 @@ else if ($id > 0 || ! empty($ref)) include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; print '
'; print $langs->trans('PaymentConditionsShort'); @@ -3250,21 +3185,24 @@ else if ($id > 0 || ! empty($ref)) 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 '
'; + 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 '
' . $langs->trans('Status') . '' . ($object->getLibStatut(4, $totalpaye)) . '
'; - - 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 ''; print '
'; print '
'; @@ -3404,12 +3311,32 @@ else if ($id > 0 || ! empty($ref)) 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 { @@ -3421,7 +3348,7 @@ else if ($id > 0 || ! empty($ref)) print ''; print ''; } - + // Revenue stamp if ($selleruserevenustamp) // Test company use revenue stamp { @@ -3448,32 +3375,14 @@ else if ($id > 0 || ! empty($ref)) } print ''; } - + // Total with tax 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 '
' . 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("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, 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)) . '
' . 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)) . '
'; - + // List of payments - + $sign = 1; if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1; $nbrows = 8; @@ -3582,9 +3491,9 @@ else if ($id > 0 || ! empty($ref)) if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) print '
'; } - + print ''; - + // List of payments already done print ''; print ''; @@ -3596,9 +3505,9 @@ else if ($id > 0 || ! empty($ref)) 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,'; @@ -3609,12 +3518,12 @@ else if ($id > 0 || ! empty($ref)) $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) { @@ -3654,7 +3563,7 @@ else if ($id > 0 || ! empty($ref)) } 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; @@ -3701,30 +3611,33 @@ else if ($id > 0 || ! empty($ref)) } else { dol_print_error($db); } - + // Paye partiellement 'escompte' - if (($object->statut == 2 || $object->statut == 3) && $object->close_code == 'discount_vat') { + 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 == 2 || $object->statut == 3) && $object->close_code == '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 == 2 || $object->statut == 3) && $object->close_code == '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 == 2 || $object->statut == 3) && $object->close_code == 'abandon') { + if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { print ''; $resteapayeraffiche = 0; + $cssforamountpaymentcomplete = ''; } - + // Billed print ''; @@ -3744,7 +3658,7 @@ else if ($id > 0 || ! empty($ref)) else print $langs->trans('ExcessReceived'); print ' :'; - print ''; + print ''; print ''; } else // Credit note @@ -3753,10 +3667,10 @@ else if ($id > 0 || ! empty($ref)) 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('Amount') . ' 
'; @@ -3663,9 +3572,10 @@ else if ($id > 0 || ! empty($ref)) else print $langs->trans('AlreadyPaid'); print ' : 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . ' 
'; print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
'; $text = $langs->trans("HelpAbandonOther"); if ($object->close_note) @@ -3732,8 +3645,9 @@ else if ($id > 0 || ! empty($ref)) print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); print '' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . ' 
' . $langs->trans("Billed") . ' :' . price($object->total_ttc) . ' 
' . price($resteapayeraffiche) . '' . price($resteapayeraffiche) . ' 
'; print $langs->trans('AlreadyPaidBack'); print ' :' . price($sign * $totalpaye) . ' 
' . $langs->trans("Billed") . ' :' . price($sign * $object->total_ttc) . ' 
'; if ($resteapayeraffiche <= 0) @@ -3766,27 +3680,26 @@ else if ($id > 0 || ! empty($ref)) 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'; $title = $langs->trans('ContactsAddresses'); @@ -3816,7 +3729,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 ''; @@ -3897,8 +3810,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) @@ -3930,7 +3842,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 { @@ -4205,10 +4117,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_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index e3951b4dca7..0b2b7f58781 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -89,11 +89,12 @@ class Invoices extends DolibarrApi * @param int $page Page number * @param int $socid Filter list with thirdparty ID * @param string $status Filter by invoice status : draft | unpaid | paid | cancelled - * @return array Array of invoice objects + * @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($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid=0, $status='') { + function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $socid=0, $status='', $sqlfilters = '') { global $db, $conf; $obj_ret = array(); @@ -103,38 +104,38 @@ class Invoices 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."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) diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 007c8040d0d..41c1171ccef 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -42,7 +42,8 @@ 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; @@ -1040,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; @@ -1203,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 4f358074e59..2e76d9ce4db 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -219,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 @@ -282,6 +282,7 @@ 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; // Invoice created on same thirdparty than template $this->entity = $_facrec->entity; // Invoice created in same entity than template @@ -312,6 +313,8 @@ 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 recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice @@ -404,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; @@ -979,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=''; @@ -996,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; @@ -1039,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'; @@ -1185,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,'; @@ -1224,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; @@ -2127,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++; } @@ -2291,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 @@ -2343,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); @@ -2388,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]; @@ -2425,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; @@ -2576,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); @@ -2639,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; @@ -4295,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,'; @@ -4309,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).","; @@ -4489,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 fd9f9e0fc13..33da64e3221 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -31,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'); @@ -87,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 @@ -124,728 +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 == '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) -{ - $result=$object->setValueFrom('titre', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'BILLREC_MODIFY'); - if ($result > 0) - { - $object->titre = GETPOST('ref', 'alpha'); - $object->ref = $object->titre; - } -} -// 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) - { - $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 ++; - } + if (GETPOST('cancel')) $action=''; - if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) + // 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 { - $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'); - } - - // 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 = ''; - } + $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(); } -} - -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]); - } + + // Create predefined invoice + if ($action == 'add') + { + if (! GETPOST('titre')) + { + setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->trans("Title")), null, 'errors'); + $action = "create"; + $error++; + } + + $frequency=GETPOST('frequency', 'int'); + $reyear=GETPOST('reyear'); + $remonth=GETPOST('remonth'); + $reday=GETPOST('reday'); + $rehour=GETPOST('rehour'); + $remin=GETPOST('remin'); + $nb_gen_max=GETPOST('nb_gen_max', 'int'); + //if (empty($nb_gen_max)) $nb_gen_max =0; + + 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) + { + $object->titre = GETPOST('ref', 'alpha'); + $object->ref = $object->titre; } - - // 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) + else dol_print_error($db, $object->error, $object->errors); + } + // Set bank account + elseif ($action == 'setbankaccount' && $user->rights->facture->creer) + { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); + } + // Set frequency and unit frequency + elseif ($action == 'setfrequency' && $user->rights->facture->creer) + { + $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); + } + // Set next date of execution + elseif ($action == 'setdate_when' && $user->rights->facture->creer) + { + $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); + if (!empty($date)) $object->setNextDate($date); + } + // Set max period + elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) + { + $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); + } + // Set auto validate + elseif ($action == 'setauto_validate' && $user->rights->facture->creer) + { + $object->setAutoValidate(GETPOST('auto_validate', 'int')); + } + + // Delete line + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id); + $object->fetch_thirdparty(); + + $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 ++; + } + + if (! $error && ($qty >= 0) && (! empty($product_desc) || ! empty($idprod))) { - $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'); + $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'); + } + + // 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]); + } + } + + // 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 @@ -855,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(); @@ -1061,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 ''; @@ -1150,6 +1216,7 @@ else print ''; // Project + /* if (! empty($conf->projet->enabled)) { $langs->load('projects'); @@ -1174,7 +1241,7 @@ else } 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); @@ -1075,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).'
'; @@ -1196,10 +1263,15 @@ else print "
"; - - print '
'; - + print ''; + + print '
'; + print '
'; + print '
'; + print '
'; + + print ''; + /* * Recurrence */ @@ -1209,14 +1281,14 @@ else print '
'; // if "frequency" is empty or = 0, the reccurence is disabled - 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 '
'; @@ -1252,7 +1324,7 @@ else { print $langs->trans("NextDateToExecution"); } - 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'); @@ -1270,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); @@ -1288,7 +1360,7 @@ else print $form->editfieldkey($langs->trans("StatusOfGeneratedInvoices"), 'auto_validate', $object->auto_validate, $object, $user->rights->facture->creer); else print $langs->trans("StatusOfGeneratedInvoices"); - print ''; + print ''; $select = 'select;0:'.$langs->trans('BillStatusDraft').',1:'.$langs->trans('BillStatusValidated'); if ($action == 'auto_validate' || $object->frequency > 0) { @@ -1299,20 +1371,21 @@ else print '
'; - print '
'; - // Frequencry/Recurring section - if ($object->frequency > 0) - { - if (empty($conf->cron->enabled)) - { - print info_admin($langs->trans("EnableAndSetupModuleCron", $langs->transnoentitiesnoconv("Module2300Name"))); - } + 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 ''; @@ -1321,7 +1394,7 @@ else // Date last print ''; print ''; @@ -1331,6 +1404,13 @@ else print '
'; } + print ''; + print ''; + print ''; + + print '

'; + + // Lines print ' @@ -1420,11 +1500,12 @@ 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 ''; + print ''; } else diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 70e4cc03974..48ed568e3f9 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -278,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; @@ -379,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 { @@ -520,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; @@ -1148,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 8d43e573696..94686162687 100644 --- a/htdocs/compta/paiement/cheque/card.php +++ b/htdocs/compta/paiement/cheque/card.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'); @@ -801,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 ''; 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("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 '
'.$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/paiement.php b/htdocs/compta/paiement.php index 4b0039c0a21..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(); @@ -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')).' '; - 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 ''; @@ -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 '\n"; + $i++; } -print '
'; +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 d00525796c0..e2e092b032f 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -188,6 +188,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); +} + // Show Array $catotal=0; 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/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 b8c96884e96..7b2e5528eb6 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -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,219 +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 ($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 ''; +$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 ''; - - // 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)) { @@ -587,203 +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) - { - $objsoc = new Societe($db); - $objsoc->fetch($obj->socid); - print $objsoc->getNomUrl(1); - } - 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/contrat/card.php b/htdocs/contrat/card.php index 347d77e84dd..86e45ade086 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -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; @@ -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").''; @@ -1964,6 +1992,11 @@ else if ($user->rights->facture->creer) print ''; else print ''; } + + // Clone + if ($user->rights->contrat->creer) { + print ''; + } if ($object->nbofservicesclosed < $nbofservices) { @@ -2005,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 d12fa566284..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 @@ -536,7 +536,7 @@ class Contrat extends CommonObject return -1; } } - + /** * Load a contract from database * @@ -904,7 +904,7 @@ class Contrat extends CommonObject } if (! $paramsok) return -1; - + $this->db->begin(); $now=dol_now(); @@ -969,7 +969,7 @@ class Contrat extends CommonObject } } } - + // Insert contacts commerciaux ('SALESREPSIGN','contrat') if (! $error) { @@ -996,8 +996,8 @@ class Contrat extends CommonObject { dol_print_error($this->db); $error++; - } - + } + if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) { $originforcontact = $origin; @@ -1018,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) { @@ -1034,11 +1034,11 @@ class Contrat extends CommonObject } } else dol_print_error($resqlcontact); - } + } } } } - + if (! $error) { // Call trigger @@ -1359,6 +1359,8 @@ class Contrat extends CommonObject 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') { @@ -1379,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]; @@ -1402,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) { @@ -1563,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]; @@ -1587,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) { @@ -2261,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; + } + } } @@ -2271,7 +2387,7 @@ class ContratLigne extends CommonObjectLine { public $element='contratdet'; public $table_element='contratdet'; - + var $id; var $ref; var $tms; @@ -2289,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 @@ -2433,7 +2549,7 @@ class ContratLigne extends CommonObjectLine $result=''; $label=$langs->trans("ShowContractOfService").': '.$this->label; if (empty($label)) $label=$this->description; - + $link = ''; $linkend=''; @@ -2629,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/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 6f2d4a2128f..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; } 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 dfc73105255..9ec3bfcb3b7 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -103,12 +103,11 @@ 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=''; - if (is_object($object)) { $result=$object->fetch($id); @@ -172,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 @@ -190,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 { @@ -200,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)); @@ -218,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); @@ -283,7 +303,6 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO } // 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) { @@ -323,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; 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/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_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 03f7e39bde8..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).'?='; @@ -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/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index df65e73f679..3ed34cfd801 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -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 ); diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index c08d645cf53..b3b0cc4042b 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -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 1457d10726c..cdd8b89a1ad 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -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'; @@ -2799,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 @@ -3753,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; + } } @@ -3807,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; @@ -3837,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); @@ -3854,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); @@ -3911,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; diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index b388298cf08..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 * @@ -491,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,societe,propal,commande,facture,categorie,supplier_proposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,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'; diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index 5ad8b3aa646..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') diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index f50803fa451..b3e1c162102 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -80,7 +80,7 @@ class Form * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...) * @param string $moreparam More param to add on a href URL* * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS. - * @param int $notabletag Do no output table tags + * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':' * @return string HTML edit field */ function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0) @@ -118,7 +118,7 @@ class Form if (empty($notabletag) && GETPOST('action') != 'edit'.$htmlname && $perm) $ret.=''; if (empty($notabletag) && GETPOST('action') != 'edit'.$htmlname && $perm) $ret.=''; if (empty($notabletag) && GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='
'; if ($htmlname && GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).''; - if (! empty($notabletag)) $ret.=' : '; + if (! empty($notabletag) && $notabletag == 1) $ret.=' : '; if (empty($notabletag) && GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='
'; } @@ -512,15 +512,16 @@ class Form if (count($arrayofaction) == 0) return; $disabled=0; - $ret='
'; $ret.=''; foreach($arrayofaction as $code => $label) { $ret.=''; } $ret.=''; - // Warning: if you set submit button to disabled, post using Enter will no more work - $ret.=''; + // Warning: if you set submit button to disabled, post using 'Enter' will no more work. + $ret.=''; $ret.='
'; $ret.=' @@ -1615,9 +1616,13 @@ 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 * @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) + 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) { global $langs,$conf; @@ -1650,33 +1655,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; @@ -1767,8 +1776,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) @@ -1800,7 +1828,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++; @@ -1827,7 +1855,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 @@ -1907,13 +1935,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; @@ -1938,13 +1966,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); @@ -1966,15 +1994,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"); } @@ -2004,13 +2032,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); @@ -2025,13 +2053,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); @@ -2340,17 +2368,18 @@ class Form /** * Return list of suppliers prices for a product * - * @param int $productid Id of product - * @param string $htmlname Name of HTML field - * @return string|null + * @param int $productid Id of product + * @param string $htmlname Name of HTML field + * @param int $selected_supplier Pre-selected supplier if more than 1 result + * @return void */ - function select_product_fourn_price($productid,$htmlname='productfournpriceid') + function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='') { global $langs,$conf; $langs->load('stocks'); - $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration,"; + $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,"; $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,"; $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; @@ -2387,7 +2416,7 @@ class Form $opt = ''; foreach($this->cache_types_paiements as $id => $arraytypes) { @@ -3272,7 +3302,7 @@ 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=200, $width=500) @@ -3287,7 +3317,8 @@ class Form // Clean parameters $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice; - + if ($conf->browser->layout == 'phone') $width='95%'; + if (is_array($formquestion) && ! empty($formquestion)) { // First add hidden fields and value @@ -3895,8 +3926,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 @@ -3907,20 +3937,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 { @@ -4098,6 +4132,11 @@ class Form $out=''; $out.= ''; + $selectedfound=false; foreach ($this->cache_vatrates as $rate) { // Keep only 0 if seller is not subject to VAT @@ -4307,13 +4347,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']:''); @@ -4507,7 +4555,7 @@ class Form } } - if ($d && $h) $retstring.=' '; + if ($d && $h) $retstring.=($h==2?'
':' '); if ($h) { @@ -4674,7 +4722,7 @@ class Form } elseif ($typehour=='text') { - $retstring.=''; + $retstring.=''; } else return 'BadValueForParameterTypeHour'; @@ -4697,7 +4745,7 @@ class Form } elseif ($typehour=='text') { - $retstring.=''; + $retstring.=''; } $retstring.=' '.$langs->trans('MinuteShort'); $retstring.=" "; @@ -5272,11 +5320,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), @@ -5291,6 +5340,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"':'').'>'; @@ -5343,22 +5394,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) { @@ -461,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; @@ -470,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=''; @@ -500,6 +543,7 @@ class FormFile } } + // Set headershown to avoit to have table opened a second time later $headershown=1; $buttonlabeltoshow=$buttonlabel; @@ -508,7 +552,7 @@ class FormFile if (empty($noform)) $out.= '
    '; $out.= ''; $out.= ''; - + $out.= load_fiche_titre($titletoshow, '', ''); $out.= ''; @@ -604,7 +648,7 @@ class FormFile { $headershown=1; $out.= '
    '.$titletoshow.'
    '."\n"; - $out.= '
    '."\n"; + $out.= '
    '."\n"; } // Loop on each file found @@ -913,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 @@ -986,7 +1029,7 @@ class FormFile { // Delete or view link // ($param must start with &) - print '\n"; $out.= "\n"; } diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index 7adbe5fad42..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); @@ -1022,7 +1022,7 @@ class FormOther //var_dump($boxidactivatedforuser); // Class Form must have been already loaded - $selectboxlist.=''; + $selectboxlist.=''; $selectboxlist.=''; $selectboxlist.=''; $selectboxlist.=''; @@ -1030,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 f1ec7edae73..742bc1a0231 100644 --- a/htdocs/core/class/html.formprojet.class.php +++ b/htdocs/core/class/html.formprojet.class.php @@ -44,7 +44,7 @@ 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 @@ -58,9 +58,10 @@ class FormProjets * @param int $mode 0 for HTML mode and 1 for JSON mode * @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 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 = '', $nooutput=0) + 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; @@ -122,9 +123,10 @@ class FormProjets * @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 = '', $nooutput=0) + 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; @@ -143,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'; 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.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/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 2724d64f17f..6f01a4c1406 100644 --- a/htdocs/core/class/utils.class.php +++ b/htdocs/core/class/utils.class.php @@ -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/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 134de6018a5..321a21a9637 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -714,8 +714,11 @@ 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=array('nbmodules'=>0, 'errors'=>array(), 'nbperms'=>0); $modName = $value; @@ -740,25 +743,25 @@ 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) @@ -1292,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 51d43ad214e..8c738894998 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -224,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++; @@ -930,201 +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,$actioncode='') +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.='
    '; + print ''; if ($useinecm) { print ''.img_view('default', 0, 'class="paddingrightonly"').''; @@ -996,10 +1039,10 @@ class FormFile $newmodulepart=$modulepart; if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service'; - $disablecrop=0; - if ($modulepart == 'expensereport') $disablecrop=1; // TODO Remove this in future + $disablecrop=1; + if (in_array($modulepart, array('product','produit','service','holiday','project'))) $disablecrop=0; - if (image_format_supported($file['name']) > 0 && ! $disablecrop) + if (! $disablecrop && image_format_supported($file['name']) > 0) { if ($permtoeditline) { @@ -1162,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) @@ -1192,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; @@ -1446,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 96f6ddc3dd9..47cc7cd9d89 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -370,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.= "
    '; - $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; - if (! empty($actioncode)) $sql.= " AND c.code='".$actioncode."' "; - $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 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, $actioncode='') +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(); @@ -1140,23 +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; if (!empty($actioncode)) $sql.= " AND c.code='".$actioncode."' "; - $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 ($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); @@ -1168,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++; } @@ -1195,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 @@ -1222,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), @@ -1249,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); @@ -1258,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.=''; @@ -1396,8 +1309,11 @@ function show_actions_done($conf, $langs, $db, $object, $objcon='', $noprint=0, $out.=''; // Statut - $out.=''; + $out.=''; + // Actions + $out.=''; + $out.="\n"; $i++; } @@ -1405,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/files.lib.php b/htdocs/core/lib/files.lib.php index ba60121969b..3d43108e6a3 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -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 e98dd142e1e..50f4ff30cc6 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 @@ -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,13 +290,13 @@ 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); break; - case 'nohtml': - $out=dol_string_nohtmltag($out); - break; } } @@ -371,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])) { @@ -395,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; } @@ -713,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. @@ -907,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; @@ -924,21 +958,20 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r 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
    '; } @@ -949,21 +982,33 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r { if ($showimage) { - $morehtmlleft.='
    '; - if ($modulepart != 'unknown') $morehtmlleft.=$form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos); - else if ($object->element == 'action') + if ($modulepart != 'unknown') { - $cssclass='photorefcenter'; - $nophoto=img_picto('', 'title_agenda', '', false, 1); - $morehtmlleft.='
    No photo
    '; + $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos); + if ($phototoshow) + { + $morehtmlleft.='
    '; + $morehtmlleft.=$phototoshow; + $morehtmlleft.='
    '; + } } - else + elseif ($conf->browser->layout != 'phone') // Show no photo link { - $width=14; $cssclass='photorefcenter'; - $nophoto=img_picto('', 'object_'.$object->picto, '', false, 1); - $morehtmlleft.='
    No photo
    '; + $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.='
    '; } - $morehtmlleft.='
    '; } } if ($showbarcode) $morehtmlleft.='
    '.$form->showbarcode($object).'
    '; @@ -992,6 +1037,10 @@ function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='r if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt=$object->getLibStatut(5, $object->totalpaye); $morehtmlright.=$tmptxt; } + elseif ($object->element == 'facturerec') + { + $morehtmlright.=''; + } else { $tmptxt=$object->getLibStatut(6); if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt=$object->getLibStatut(5); @@ -1011,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 '
    '; @@ -1029,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; } @@ -2246,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 @@ -2261,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); } /** @@ -2463,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) { @@ -3146,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; @@ -3155,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++; } @@ -3176,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 @@ -3262,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) @@ -3271,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) @@ -3288,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=''; @@ -3306,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)) { @@ -3563,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]; } @@ -3577,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; @@ -3590,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; @@ -3862,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) @@ -4012,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) @@ -4216,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)) { @@ -4239,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; } @@ -4561,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) { @@ -5144,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 @@ -5426,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 '
    '; - 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') { @@ -1321,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']).'
    '; + 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').''; @@ -1534,7 +1864,7 @@ else $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $alreadypaid=$object->getSommePaiement(); - + /* * View card */ @@ -1645,9 +1975,8 @@ else // Supplier invoice 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); @@ -1687,37 +2016,17 @@ else } } $morehtmlref.='
    '; - + $object->totalpaye = $alreadypaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status - + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - - + print '
    '; print '
    '; print '
    '; - + print ''; - - // Ref - /* - print ''; - print "\n"; - - // Ref supplier - print ''; - - // Third party - print ''; - print ''; - */ - // Type 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 '
    '.$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').')
    '.$langs->trans('Type').''; print $object->getLibType(); @@ -1940,9 +2249,27 @@ else 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 @@ -1972,39 +2299,25 @@ else 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 '
    ' . 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).'
            '; @@ -1956,7 +2283,7 @@ else $s.=''.$langs->trans("Mode2").''; print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc",$calculationrulenum).'
    '.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('','help')); print '
    '.$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)) . '
    '; - + /* * List of payments */ - $nbrows=9; $nbcols=3; + $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,'; @@ -2016,7 +2329,7 @@ else $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) { @@ -2024,14 +2337,14 @@ else $i = 0; $totalpaye = 0; print ''; print ''; - print ''; + print ''; print ''; print ''; if (! empty($conf->banque->enabled)) print ''; print ''; print ''; print ''; - + $var=false; if ($num > 0) { @@ -2060,7 +2373,7 @@ else if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1,'transactions'); print ''; } - print ''; + print ''; print ''; } - + + /* if ($object->paye == 0) { print ''; @@ -2089,14 +2403,139 @@ else print ''; print ''; } - print '
    '.$langs->trans('Payments').'' . ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . ''.$langs->trans('Date').''.$langs->trans('Type').''.$langs->trans('BankAccount').''.$langs->trans('Amount').' 
    '.price($objp->amount).'' . price($sign * $objp->amount) . ''; if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) { @@ -2078,7 +2391,8 @@ else { print '
    '.$langs->trans("None").'
    '.$langs->trans('AlreadyPaid').' :'.price($totalpaye).'
    '.$langs->trans('RemainderToPay').' :'.price($resteapayer).'
    '; + */ + $db->free($result); } else { dol_print_error($db); } - + + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { + // Total already paid + print '
    '; + 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 '
    '; @@ -2123,16 +2562,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'; @@ -2140,7 +2575,7 @@ else print ''; - global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; + global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; $forceall=1; $senderissupplier=1; $dateSelector=0; $inputalsopricewithtax=1; // Show object lines @@ -2215,7 +2650,6 @@ else else print ''.$langs->trans('SendByMail').''; } - // Make payments if ($action != 'edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0) { @@ -2262,6 +2696,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) { @@ -2362,10 +2805,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 b8e90dbce10..ebe65f62122 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -435,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"; print ''."\n"; print ''."\n"; - print ''."\n"; - print ''."\n"; }*/ // jQuery Timepicker if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER')) @@ -1245,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"; + } } } @@ -1419,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 .=''; @@ -1430,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 '