diff --git a/.gitignore b/.gitignore index 1efe4f4bb82..1ece034ae94 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ Thumbs.db htdocs/includes/autoload.php htdocs/includes/bin/ htdocs/includes/composer/ +/.pydevproject diff --git a/.travis.yml b/.travis.yml index 10a2b6e8347..e30acd0068b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,8 @@ # from Dolibarr GitHub repository. # For syntax, see http://about.travis-ci.org/docs/user/languages/php/ -# We use dist: precise to have php 5.3 available -dist: precise +# We use dist: trusty to have php 5.4+ available +dist: trusty sudo: required language: php @@ -31,7 +31,6 @@ addons: - pgloader php: -- '5.3' - '5.4' - '5.5' - '5.6' @@ -64,8 +63,6 @@ matrix: - php: nightly # We exclude some combinations not usefull to save Travis CPU exclude: - - php: '5.4' - env: DB=postgresql - php: '5.5' env: DB=postgresql - php: '5.6' @@ -123,7 +120,7 @@ install: - | echo "Installing PHP Unit" - if [ "$TRAVIS_PHP_VERSION" = '5.3' ] || [ "$TRAVIS_PHP_VERSION" = '5.4' ] || [ "$TRAVIS_PHP_VERSION" = '5.5' ]; then + if [ "$TRAVIS_PHP_VERSION" = '5.4' ] || [ "$TRAVIS_PHP_VERSION" = '5.5' ]; then composer -n require phpunit/phpunit ^4 fi if [ "$TRAVIS_PHP_VERSION" = '5.6' ] || [ "$TRAVIS_PHP_VERSION" = '7.0' ] || [ "$TRAVIS_PHP_VERSION" = '7.1' ]; then @@ -143,137 +140,143 @@ install: echo "Adding path of binaries tools installed by composer to the PATH" export PATH="$TRAVIS_BUILD_DIR/htdocs/includes/bin:$PATH" echo - + + before_script: -- | - echo Start travis - echo Current dir is `pwd` - echo Home dir is `echo ~` - echo TRAVIS_BUILD_DIR is $TRAVIS_BUILD_DIR + - | + echo Start travis + echo Current dir is `pwd` + echo Home dir is `echo ~` + echo TRAVIS_BUILD_DIR is $TRAVIS_BUILD_DIR -- | - echo "Re-enabling Xdebug for PHP CodeSniffer and PHP Unit" - phpenv config-add /tmp/xdebug.ini - echo - -- | - echo "Setting up PHP" - echo - echo "Set timezone" - echo 'date.timezone = "Europe/Paris"' >> ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini - if [ "$TRAVIS_PHP_VERSION" = '5.3' ] || [ "$TRAVIS_PHP_VERSION" = '5.4' ]; then - #echo - #echo "Enabling APC for PHP <= 5.4" - # Documentation says it should be available for PHP <= 5.6 but it's not for 5.5 and 5.6! - #echo 'extension = apc.so' >> ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini + - | + echo "Re-enabling Xdebug for PHP CodeSniffer and PHP Unit" + phpenv config-add /tmp/xdebug.ini echo - echo "Enabling Memcached for PHP <= 5.4" - # Documentation says it should be available for all PHP versions but it's not for 5.5 and 5.6, 7.0, 7.1, 7.2 and nightly! - echo 'extension = memcached.so' >> ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini - fi - phpenv rehash - echo -- | - if [ "$DEBUG" = true ]; then - echo "Debugging informations" + - | + echo "Setting up PHP" + echo + echo "Set timezone" + echo 'date.timezone = "Europe/Paris"' >> ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini + if [ "$TRAVIS_PHP_VERSION" = '5.4' ]; then + #echo + #echo "Enabling APC for PHP <= 5.4" + # Documentation says it should be available for PHP <= 5.6 but it's not for 5.5 and 5.6! + #echo 'extension = apc.so' >> ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini + echo + echo "Enabling Memcached for PHP <= 5.4" + # Documentation says it should be available for all PHP versions but it's not for 5.5 and 5.6, 7.0, 7.1, 7.2 and nightly! + echo 'extension = memcached.so' >> ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini + fi + phpenv rehash + echo + + - | + echo "Versions information" # Check PHP - php -i + echo "PHP version" + php -i | head - # Check PHP CodeSniffer installation + echo "PHPCS version" which phpcs - phpcs --version - phpcs -i + phpcs --version | head - + phpcs -i | head - # Check PHPUnit installation + echo "PHPUnit version" which phpunit - phpunit --version - # Check MySQL - mysql --version - mysql -e "SELECT VERSION();" + phpunit --version | head - + # Check Apache version + echo "Apache version" + apache2 -v | head - + # Check MariaDb + echo "MariaDb version" + mysql --version | head - + mysql -e "SELECT VERSION();" | head - echo - fi -- | - echo "Setting up database" - if [ "$DB" = 'mysql' ] || [ "$DB" = 'mariadb' ] || [ "$DB" = 'postgresql' ]; then - echo "MySQL" - mysql -e 'DROP DATABASE IF EXISTS travis;' - mysql -e 'CREATE DATABASE IF NOT EXISTS travis;' - mysql -e 'GRANT ALL PRIVILEGES ON travis.* TO travis@127.0.0.1;' - mysql -e 'FLUSH PRIVILEGES;' - mysql -D travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql - fi - if [ "$DB" = 'postgresql' ]; then - #pgsql travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql - #pgloader mysql://root:pass@127.0.0.1/base postgresql://dolibarrowner@127.0.0.1/dolibarr - pgloader mysql://root@127.0.0.1/travis postgresql:///travis - fi - # TODO: SQLite - echo + - | + echo "Setting up database" + if [ "$DB" = 'mysql' ] || [ "$DB" = 'mariadb' ] || [ "$DB" = 'postgresql' ]; then + echo "MySQL" + mysql -e 'DROP DATABASE IF EXISTS travis;' + mysql -e 'CREATE DATABASE IF NOT EXISTS travis;' + mysql -e 'GRANT ALL PRIVILEGES ON travis.* TO travis@127.0.0.1;' + mysql -e 'FLUSH PRIVILEGES;' + mysql -D travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql + fi + if [ "$DB" = 'postgresql' ]; then + #pgsql travis < dev/initdemo/mysqldump_dolibarr_3.5.0.sql + #pgloader mysql://root:pass@127.0.0.1/base postgresql://dolibarrowner@127.0.0.1/dolibarr + pgloader mysql://root@127.0.0.1/travis postgresql:///travis + fi + # TODO: SQLite + echo -- | - export CONF_FILE=htdocs/conf/conf.php - echo "Setting up Dolibarr $CONF_FILE" - echo ' $CONF_FILE - echo '$'dolibarr_main_url_root=\'http://127.0.0.1\'';' >> $CONF_FILE - echo '$'dolibarr_main_document_root=\'$TRAVIS_BUILD_DIR/htdocs\'';' >> $CONF_FILE - echo '$'dolibarr_main_data_root=\'$TRAVIS_BUILD_DIR/documents\'';' >> $CONF_FILE - echo '$'dolibarr_main_db_host=\'127.0.0.1\'';' >> $CONF_FILE - echo '$'dolibarr_main_db_name=\'travis\'';' >> $CONF_FILE - echo '$'dolibarr_main_db_user=\'travis\'';' >> $CONF_FILE - if [ "$DB" = 'mysql' ] || [ "$DB" = 'mariadb' ]; then - echo '$'dolibarr_main_db_type=\'mysqli\'';' >> $CONF_FILE - fi - if [ "$DB" = 'postgresql' ]; then - echo '$'dolibarr_main_db_type=\'pgsql\'';' >> $CONF_FILE - fi - # TODO: SQLite - echo '$'dolibarr_main_authentication=\'dolibarr\'';' >> $CONF_FILE - cat $CONF_FILE - echo + - | + export CONF_FILE=htdocs/conf/conf.php + echo "Setting up Dolibarr $CONF_FILE" + echo ' $CONF_FILE + echo '$'dolibarr_main_url_root=\'http://127.0.0.1\'';' >> $CONF_FILE + echo '$'dolibarr_main_document_root=\'$TRAVIS_BUILD_DIR/htdocs\'';' >> $CONF_FILE + echo '$'dolibarr_main_data_root=\'$TRAVIS_BUILD_DIR/documents\'';' >> $CONF_FILE + echo '$'dolibarr_main_db_host=\'127.0.0.1\'';' >> $CONF_FILE + echo '$'dolibarr_main_db_name=\'travis\'';' >> $CONF_FILE + echo '$'dolibarr_main_db_user=\'travis\'';' >> $CONF_FILE + if [ "$DB" = 'mysql' ] || [ "$DB" = 'mariadb' ]; then + echo '$'dolibarr_main_db_type=\'mysqli\'';' >> $CONF_FILE + fi + if [ "$DB" = 'postgresql' ]; then + echo '$'dolibarr_main_db_type=\'pgsql\'';' >> $CONF_FILE + fi + # TODO: SQLite + echo '$'dolibarr_main_authentication=\'dolibarr\'';' >> $CONF_FILE + cat $CONF_FILE + echo -- | - echo "Create documents directory and set permissions" - # and admin/temp subdirectory needed for unit tests - mkdir -p documents/admin/temp - echo "first line" > documents/dolibarr.log - echo + - | + echo "Create documents directory and set permissions" + # and admin/temp subdirectory needed for unit tests + mkdir -p documents/admin/temp + echo "first line" > documents/dolibarr.log + echo -- | - echo "Setting up Apache + FPM" + + - echo "Setting up Apache + FPM" + - sudo apt-get update + - sudo apt-get install apache2 libapache2-mod-fastcgi # enable php-fpm - cp ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php-fpm.conf.default ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php-fpm.conf - if [ "$TRAVIS_PHP_VERSION" = '7.0' ] || [ "$TRAVIS_PHP_VERSION" = '7.1' ] || [ "$TRAVIS_PHP_VERSION" = '7.2' ] || [ "$TRAVIS_PHP_VERSION" = 'nightly' ]; then - # Copy the included pool - cp ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php-fpm.d/www.conf.default ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php-fpm.d/www.conf - fi - if [ "$DEBUG" = true ]; then - cat ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php-fpm.conf - fi - sudo a2enmod rewrite actions fastcgi alias - echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini - if [ "$DEBUG" = true ]; then - cat ~/.phpenv/versions/$PHP_VERSION_NAME/etc/php.ini - fi - ~/.phpenv/versions/$PHP_VERSION_NAME/sbin/php-fpm - # configure apache virtual hosts - sudo cp -f build/travis-ci/apache.conf /etc/apache2/sites-available/default - sudo sed -e "s?%TRAVIS_BUILD_DIR%?$TRAVIS_BUILD_DIR?g" --in-place /etc/apache2/sites-available/default - if [ "$DEBUG" = true ]; then - sudo cat /etc/apache2/sites-available/default - fi - sudo service apache2 restart - echo + - sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf + - | + if [ "$TRAVIS_PHP_VERSION" = '7.0' ] || [ "$TRAVIS_PHP_VERSION" = '7.1' ] || [ "$TRAVIS_PHP_VERSION" = '7.2' ] || [ "$TRAVIS_PHP_VERSION" = 'nightly' ]; then + # Copy the included pool + sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.d/www.conf + fi + - sudo a2enmod rewrite actions fastcgi alias + - echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + - sudo sed -i -e "s,www-data,travis,g" /etc/apache2/envvars + - sudo chown -R travis:travis /var/lib/apache2/fastcgi + - ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm + # configure apache virtual hosts for precise + #- sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default + #- sudo cat /etc/apache2/sites-available/default + # configure apache virtual hosts for trusty + - sudo cp -f build/travis-ci/apache.conf /etc/apache2/sites-available/000-default.conf + - sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/000-default.conf + - sudo cat /etc/apache2/sites-available/000-default.conf + - sudo service apache2 restart + + script: - | - echo "Checking webserver availability" + echo "Checking webserver availability by a wget -O - http://127.0.0.1" # Ensure we catch errors set -e - wget http://127.0.0.1 - if [ "$DEBUG" = true ]; then - cat index.html - fi + # The wget should return a page with line ' + wget -O - http://127.0.0.1 > test.html + head test.html set +e echo @@ -290,7 +293,8 @@ script: # Ensure we catch errors set -e # Exclusions are defined in the ruleset.xml file - phpcs -s -n -p -d memory_limit=-1 --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 . + #phpcs -s -n -p -d memory_limit=-1 --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 . + phpcs -s -p -d memory_limit=-1 --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true . set +e echo @@ -327,6 +331,9 @@ script: php upgrade.php 6.0.0 7.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade600700.log php upgrade2.php 6.0.0 7.0.0 MAIN_MODULE_WEBSITE,MAIN_MODULE_SUPPLIERPROPOSAL > $TRAVIS_BUILD_DIR/upgrade600700-2.log php step5.php 6.0.0 7.0.0 > $TRAVIS_BUILD_DIR/upgrade600700-3.log + php upgrade.php 7.0.0 8.0.0 ignoredbversion > $TRAVIS_BUILD_DIR/upgrade700800.log + php upgrade2.php 7.0.0 8.0.0 MAIN_MODULE_TICKETSUP > $TRAVIS_BUILD_DIR/upgrade700800-2.log + php step5.php 7.0.0 8.0.0 > $TRAVIS_BUILD_DIR/upgrade700800-3.log cd - set +e echo @@ -334,11 +341,11 @@ script: #cat $TRAVIS_BUILD_DIR/upgrade500600.log #cat $TRAVIS_BUILD_DIR/upgrade500600-2.log #cat $TRAVIS_BUILD_DIR/upgrade500600-3.log - #cat /tmp/dolibarr_install.log + #cat $TRAVIS_BUILD_DIR/upgrade600700-2.log + cat /tmp/dolibarr_install.log - | echo "Unit testing" - phpunit --version # Ensure we catch errors. Set this to +e if you want to go to the end to see dolibarr.log file. set -e phpunit -d memory_limit=-1 -c test/phpunit/phpunittest.xml test/phpunit/AllTests.php diff --git a/.tx/config b/.tx/config index 89d123b0362..db380163540 100644 --- a/.tx/config +++ b/.tx/config @@ -20,6 +20,12 @@ source_file = htdocs/langs/en_US/agenda.lang source_lang = en_US type = MOZILLAPROPERTIES +[dolibarr.assets] +file_filter = htdocs/langs//assets.lang +source_file = htdocs/langs/en_US/assets.lang +source_lang = en_US +type = MOZILLAPROPERTIES + [dolibarr.banks] file_filter = htdocs/langs//banks.lang source_file = htdocs/langs/en_US/banks.lang @@ -152,12 +158,6 @@ source_file = htdocs/langs/en_US/hrm.lang source_lang = en_US type = MOZILLAPROPERTIES -[dolibarr.incoterm] -file_filter = htdocs/langs//incoterm.lang -source_file = htdocs/langs/en_US/incoterm.lang -source_lang = en_US -type = MOZILLAPROPERTIES - [dolibarr.install] file_filter = htdocs/langs//install.lang source_file = htdocs/langs/en_US/install.lang @@ -356,6 +356,12 @@ source_file = htdocs/langs/en_US/supplier_proposal.lang source_lang = en_US type = MOZILLAPROPERTIES +[dolibarr.ticket] +file_filter = htdocs/langs//ticket.lang +source_file = htdocs/langs/en_US/ticket.lang +source_lang = en_US +type = MOZILLAPROPERTIES + [dolibarr.trips] file_filter = htdocs/langs//trips.lang source_file = htdocs/langs/en_US/trips.lang diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..9a84fdbbda0 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Code of Conduct + +## 1. Purpose + +A primary goal of Dolibarr is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof). + +This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior. + +We invite all those who participate in Dolibarr to help us create safe and positive experiences for everyone. + +## 2. Open Source Citizenship + +A supplemental goal of this Code of Conduct is to increase open source citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community. + +Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society. + +If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know. + +## 3. Expected Behavior + +The following behaviors are expected and requested of all community members: + +* Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community. +* Exercise consideration and respect in your speech and actions. +* Attempt collaboration before conflict. +* Refrain from demeaning, discriminatory, or harassing behavior and speech. +* Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential. +* Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations. + +## 4. Unacceptable Behavior + +The following behaviors are considered harassment and are unacceptable within our community: + +* Violence, threats of violence or violent language directed against another person. +* Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language. +* Posting or displaying sexually explicit or violent material. +* Posting or threatening to post other people’s personally identifying information ("doxing"). +* Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability. +* Inappropriate photography or recording. +* Inappropriate physical contact. You should have someone’s consent before touching them. +* Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances. +* Deliberate intimidation, stalking or following (online or in person). +* Advocating for, or encouraging, any of the above behavior. +* Sustained disruption of community events, including talks and presentations. + +## 5. Consequences of Unacceptable Behavior + +Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated. + +Anyone asked to stop unacceptable behavior is expected to comply immediately. + +If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event). + +## 6. Reporting Guidelines + +If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. contact@dolibarr.org. + + + +Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress. + +## 7. Addressing Grievances + +If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify Dolibarr with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies. + + + +## 8. Scope + +We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues–online and in-person–as well as in all one-on-one communications pertaining to community business. + +This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members. + +## 9. Contact info + +contact@dolibarr.org + +## 10. License and attribution + +This Code of Conduct is distributed under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/). + +Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy). + +Retrieved on November 22, 2016 from [http://citizencodeofconduct.org/](http://citizencodeofconduct.org/) diff --git a/ChangeLog b/ChangeLog index 62bcbb19754..ceb1d847ddb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -2,6 +2,196 @@ English Dolibarr ChangeLog -------------------------------------------------------------- +***** ChangeLog for 8.0.0 compared to 7.0.0 ***** + +For Users: +NEW: Experimental module: Ticket +NEW: Experimental module: WebDAV +NEW: Accept anonmymous events (no user assigned) +NEW: Accountancy - Add import on general ledger +NEW: Accountancy - Show journal name on journal page and hide button draft export (Add an option in admin) +NEW: Can create event from record card of a company and member +NEW: Add a button to create Stripe customer from the Payment mode tab +NEW: Add accounting account number on product tooltip +NEW: add any predefined mail content +NEW: Add arrows to navigate into containers in website module +NEW: Add a tab to specify accountant/auditor of the company +NEW: Add Date delivery and Availability on Propals List +NEW: Add date in goods reception supplier order table +NEW: Add delivery_time_days of suppliers in export profile +NEW: Add Docments'tab to expedition module +NEW: Use dol_print_phone in thirdparty list page to format phone +NEW: Add entry for the GDPR contact +NEW: Add extrafield type "html" +NEW: Add file number in accountant card and update export filename +NEW: Add files management on products lot +NEW: add filter on project task list +NEW: Add hidden option COMPANY_AQUARIUM_CLEAN_REGEX to clean generated +NEW: add internal stripe payment page for invoice +NEW: Add key __USER_REMOTE_IP__ into available substitution variables +NEW: Add link between credit note invoice and origin +NEW: Add linked file tab to vat +NEW: add link to stripe's info in bank menu +NEW: Add margin filters +NEW: Add mass action enable/disable on cron job list +NEW: Add mass action on project's list to close projects +NEW: Add method to register distributed payments on invoices +NEW: Add multicurrency support for product buy price for supplier propales, orders and invoices +NEW: Add name of day in the timesheet input page per day. +NEW: add new parameters for tcpf encryption +NEW: add optional esign field in pdf propal +NEW: Add option BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD +NEW: Add option CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES +NEW: Add param $dolibarr_main_restrict_ip in config file to limit ips +NEW: add pdf function to check if pdf file is protected/encrypted +NEW: Add pdf template for stock/warehouse module +NEW: Add phone format for a lot of countries +NEW: Add product and product categories filters on customer margins +NEW: Add product categories filter on product margin +NEW: Add romanian chart of accounts +NEW: Add stats in salaries module +NEW: add stripe transaction +NEW: Add tab contact on supplier proposals +NEW: Add total of time spent in timespent page at top of page too. +NEW: Add trigger CONTRACT_MODIFY +NEW: Add triggers on ECM object and add fill src_object_type/id fields +NEW: Add type of website container/page into dictionary +NEW: advance target filtering can be used everywhere with tpl and fk_element +NEW: Allow negative quantity for dispatch (supplier order) +NEW: bank reconcile: checkbox to select all bank operations +NEW: Better performance with openldap +NEW: Can add filter actiontype and notactiontype on event ical export +NEW: Can add product in supplier order/invoice even w/o predefined price +NEW: cancel orders on massaction +NEW: Can crop image files attached in "document" tabs of a member +NEW: Can delete dir content in media and ECM module recursively +NEW: Can dispatch if more than ordered (if hidden option set) +NEW: Can edit the text color for title line of tables +NEW: Can enter time spent from the list of time spent of project +NEW: Can export leave requests +NEW: Can filter on account range in general ledger grouped by account +NEW: Can filter on country and taxid into the binding page +NEW: Can filter on progression in timesheet +NEW: Can fix the bank account of a payment if payment not conciliated +NEW: Can force usage of shared link for photo of products +NEW: Can get template of email from its label +NEW: Can see Unit Purchase Value of product in stock movement +NEW: Can select from the user list into send form email (For field to and CC) +NEW: Can select sample to use when creating a new page +NEW: can send mail from project card +NEW: Can set position of images in module tickets +NEW: Can set the reply-to into email sent +NEW: Can set the start/end date of service line in invoice templates +NEW: Can share any file from the "Document" tab. +NEW: Can sort on priority in task scheduler list +NEW: Can sort order of files in attach tab for leave and expensereport +NEW: Can use setValueFrom without user modification field +NEW: Cat set the encryption algorithm for extrafields of type password +NEW: check idprof1 for country pt +NEW: default add action: new param $backurlforcard to redirect to card +NEW: default warehouse field for products + prefill warehouses when dispatching supplier orders +NEW: Display price HT on all commercial area boards +NEW: display total on contract service list +NEW: display weight volume in proposal +NEW: Edit of extrafields position page on the edit form +NEW: Experimental DAV module provides a public and private directory +NEW: export filter models can be share or not by user +NEW: Externalsite module can accept iframe content. +NEW: Filter export model is now by user +NEW: Finish implementation of option PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES +NEW: generalize use of button to create new element from list +NEW: hidden conf AGENDA_NB_WEEKS_IN_VIEW_PER_USER to set nb weeks to show into per user view +NEW: hidden conf to assign category to thirparty that are not customer nor prospect nor supplier +NEW: hidden conf to set nb weeks to show into user view +NEW: hidden option MAIN_DISABLE_FREE_LINES +NEW: improve way of adding users/sales representative to thirdparty +NEW: Introduce option THIRDPARTY_QUICKSEARCH_ON_FIELDS to personalize fields use to search on quick search. +NEW: Introduce permission "approve" for "leave request" like for "expense report" +NEW: Load product data optional fields to the line -> enables to use "line_options_{extrafield}" +NEW: Look and feel v8 - Show Picto "+" on all links "Add record" +NEW: Look and feel v8: Use a different picto for delete and unlink +NEW: mail templates for projects +NEW: Module variant supported on services +NEW: monthly VAT report show "Claimed for the period" + "Paid during this +NEW: Mutualize code for action="update_extras" +NEW: On invoice card, show accounting account linked +NEW: Online payment of invoice and subscription record the payment +NEW: OnSearchAndListGoOnCustomerOrSupplierCard conf +NEW: Optimize load of hooks classes (save 1-5Kb of memory) +NEW: Option MAIN_SHOW_REGION_IN_STATE renamed into MAIN_SHOW_REGION_IN_STATE_SELECT are more complete +NEW: Option to force all emails recipient +NEW: Hidden option to send to salaries into emails forms +NEW: order minimum amount +NEW: add price in burger menu on mouvement list +NEW: Report a list of leave requests for a month +NEW: Section of files generated by mass action not visible if empty +NEW: send mails from project card +NEW: Show also size in bytes in tooltip if visible unit is not bytes +NEW: Show keyboard shortcut of nav arrow into tooltip +NEW: Show last result code of cron jobs in error in red +NEW: Show region in company info & Global option to show state code MAIN_SHOW_STATE_CODE +NEW: Show total number of records by category +NEW: Show total of time consumed in week in time spent entry page +NEW: Stripe online payments reuse the same stripe customer account +NEW: Suggest link to pay online for customer orders +NEW: supplier credit notes is now supported like for customer credit notes +NEW: supplier order/order lines export: add supplier product ref +NEW: supplier relative discounts +NEW: Support alternative aliases of page name in website +NEW: syslog file autoclean +NEW: thirdparty categ filter on lists +NEW: Use a css style for weekend in time spent +NEW: Use common substitution rule for language to get translation in ODT +NEW: Variable __ONLINE_PAYMENT_URL__ available in email templates + +For developers: +NEW: class reposition can also work on POST (not only GET) +NEW: add a hook in dol_print_phone +NEW: The field "visible" on extrafield can accept expression as condition +NEW: Upgrade of Stripe lib to 6.4.1 +NEW: work on CommonObject 'array' field typeNew common object array +NEW: method Form::selectArrayFilter() + use in left menu search +NEW: [REST API] Add the possibility to remove a category from a thirdparty +NEW: doActions on categorycard +NEW: add "moreHtmlRef" hook +NEW: add hook for more permissions control +NEW: add hook moreHtmlStatus to complete to status on banners +NEW: Add hook printEmail +NEW: Add hook setContentSecurityPolicy +NEW: Add password_hash as a hash algorithm +NEW: Add dol_is_link function +NEW: Adds a contact to an invoice with REST API +NEW: Adds a payment for the list of invoices given as parameter +NEW: adds billing contacts ids to REST API returns +NEW: Add showempty parameter in country selection +NEW: add printUserListWhere hook +NEW: add "printUserPasswordField" hooks +NEW: Call to trigger on payment social contribution creation +NEW: Call to trigger on social contribution creation +NEW: hook getnomurltooltip is replaced with hook getNomUrl more powerfull + +WARNING: + +Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: +* Remove old deprecated hook 'insertExtraFields'. Triggers must be used for action on CRUD events. +* Hook 'maildao' was renamed into 'mail' into the method sendfile that send emails, and method was renamed from + 'doaction' into 'sendMail'. +* Rename trigger CONTRACT_SERVICE_ACTIVATE into LINECONTRACT_ACTIVATE and + CONTRACT_SERVICE_CLOSE into LINECONTRACT_CLOSE +* Remove triggers *_CLONE. The trigger CREATE with context 'createfromclone' is already called so this is + a duplicated feature. Cloning is not a business event, the business event is CREATE, so no trigger required. +* PHP 5.3 is no more supported. Minimum PHP is now 5.4+ +* Remove the old deprecated code of doActions and getInstanceDao in canvas. The doActions of standard hooks are + already available and are better. +* Removed method fetch_prods() and get_each_prod() not used, keep only get_arbo_each_prod() that is better. +* The hook contaxt commcard has been renamed thirdpartycomm +* The hook contaxt thirdpartycard has been renamed thirdpartycontact +* Remove method Categorie:get_nb_categories() that was not used. +* Hook getnomurltooltip provide a duplicate feature compared to hook getNomUrl so all hooks getnomurltooltip + are now replaced with hook getNomUrl. + + + ***** ChangeLog for 7.0.3 compared to 7.0.2 ***** FIX: 7.0 task contact card without withproject parameters FIX: #8722 @@ -197,7 +387,7 @@ FIX: Use of undefined constant _ROWS_2 FIX: warning when adding ECM files using old photo path -***** ChangeLog for 7.0.0 compared to 6.0.5 ***** +***** ChangeLog for 7.0.0 compared to 6.0.7 ***** For users: NEW: Add a preview icon after files that can be previewed (pdf + images) NEW: When payment is registered, PDF of invoices are also regenerated so payments diff --git a/README-FR.md b/README-FR.md index 8e6a2c5aac0..a9745bb8dbb 100644 --- a/README-FR.md +++ b/README-FR.md @@ -138,9 +138,10 @@ Voici un liste de fonctionnalites pas encore gérées par Dolibarr: Les documentations utilisateur, développeur et traducteur sont disponible sous forme de ressources de la communautés via la site [Wiki](https://wiki.dolibarr.org). -## CONTRIBUTING +## CONTRIBUER -Voir le fichier [CONTRIBUTING](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md) +Ce projet existe grâce à ses nombreux contributeurs [[Contribuer](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md)]. + ## CREDITS diff --git a/README.md b/README.md index 3d9ba75f1f5..5feec47e56f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # DOLIBARR ERP & CRM -![Build status](https://img.shields.io/travis/Dolibarr/dolibarr/develop.svg) ![Downloads per day](https://img.shields.io/sourceforge/dm/dolibarr.svg) +![Build status](https://img.shields.io/travis/Dolibarr/dolibarr/8.0.svg) ![Downloads per day](https://img.shields.io/sourceforge/dm/dolibarr.svg) Dolibarr ERP & CRM is a modern software package to manage your organization's activity (contacts, suppliers, invoices, orders, stocks, agenda…). @@ -162,7 +162,7 @@ See the [ChangeLog](https://github.com/Dolibarr/dolibarr/blob/develop/ChangeLog) Dolibarr can be extended with a lot of other external application or modules from third party developers available at the [DoliStore](https://www.dolistore.com). -## FUTURE +## WHAT DOLIBARR CAN'T DO YET These are features that Dolibarr does **not** yet fully support: @@ -179,7 +179,8 @@ Administrator, user, developer and translator's documentations are available alo ## CONTRIBUTING -See [CONTRIBUTING](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md) file +This project exists thanks to all the people who contribute. [[Contribute](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md)]. + ## CREDITS @@ -199,3 +200,8 @@ Follow Dolibarr project on: - [LinkedIn](https://www.linkedin.com/company/association-dolibarr) - [YouTube](https://www.youtube.com/user/DolibarrERPCRM) - [GitHub](https://github.com/Dolibarr/dolibarr) + + +### Sponsors + +Support this project by becoming a sponsor. Your logo will show up here. 🙏 [[Become a sponsor/backer](https://opencollective.com/dolibarr#backer)] diff --git a/build/exe/doliwamp/doliwamp.iss b/build/exe/doliwamp/doliwamp.iss index 7dcb8c738bd..2d4668b447c 100644 --- a/build/exe/doliwamp/doliwamp.iss +++ b/build/exe/doliwamp/doliwamp.iss @@ -28,9 +28,9 @@ OutputBaseFilename=__FILENAMEEXEDOLIWAMP__ SourceDir=..\..\.. AppId=doliwamp AppPublisher=NLTechno -AppPublisherURL=http://www.nltechno.com -AppSupportURL=http://www.dolibarr.org -AppUpdatesURL=http://www.dolibarr.org +AppPublisherURL=https://www.nltechno.com +AppSupportURL=https://www.dolibarr.org +AppUpdatesURL=https://www.dolibarr.org AppComments=DoliWamp includes Dolibarr, Apache, PHP and Mysql softwares. AppCopyright=Copyright (C) 2008-2017 Laurent Destailleur (NLTechno), Fabian Rodriguez (Le Goût du Libre) DefaultDirName=c:\dolibarr @@ -100,9 +100,9 @@ Source: "build\exe\doliwamp\builddemosslfiles.bat.install"; DestDir: "{app}\"; F Source: "build\exe\doliwamp\UsedPort.exe"; DestDir: "{app}\"; Flags: ignoreversion; ; PhpMyAdmin, Apache, Php, Mysql ; Put here path of Wampserver applications -; Value OK: apache 2.2.6, php 5.2.5 (5.2.11, 5.3.0 and 5.3.1 fails if php_exif, php_pgsql, php_zip is on), mysql 5.0.45 +; Value OK: apache 2.2.6, php 5.2.5 (5.2.11, 5.3.0 and 5.3.1 fails if php_exif, php_pgsql, php_zip is on), mysql 5.0.45 ; Value OK: apache 2.2.11, php 5.3.0 (if no php_exif, php_pgsql, php_zip), mysql 5.0.45 -; Value ???: apache 2.4.19, php 5.5.12, mysql 5.0.45 instead of 5.6.17 (wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe) +; Value OK: apache 2.4.19, php 5.5.12, mysql 5.0.45 instead of 5.6.17 (wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe) Source: "C:\Program Files\Wamp\apps\phpmyadmin4.1.14\*.*"; DestDir: "{app}\apps\phpmyadmin4.1.14"; Flags: ignoreversion recursesubdirs; Excludes: "config.inc.php,wampserver.conf,*.log,*_log,darkblue_orange" Source: "C:\Program Files\Wamp\bin\apache\apache2.4.9\*.*"; DestDir: "{app}\bin\apache\apache2.4.9"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,httpd.conf,wampserver.conf,*.log,*_log" Source: "C:\Program Files\Wamp\bin\php\php5.5.12\*.*"; DestDir: "{app}\bin\php\php5.5.12"; Flags: ignoreversion recursesubdirs; Excludes: "php.ini,phpForApache.ini,wampserver.conf,*.log,*_log" diff --git a/build/generate_filelist_xml.php b/build/generate_filelist_xml.php index 5f71ff54072..0764d64b491 100755 --- a/build/generate_filelist_xml.php +++ b/build/generate_filelist_xml.php @@ -47,7 +47,7 @@ $includeconstants=array(); if (empty($argv[1])) { - print "Usage: ".$script_file." release=auto|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; print "Example: ".$script_file." release=6.0.0 includecustom=1 includeconstant=FR:INVOICE_CAN_ALWAYS_BE_REMOVED:0 includeconstant=all:MAILING_NO_USING_PHPMAIL:1\n"; exit -1; } @@ -70,30 +70,52 @@ while ($i < $argc) $i++; } +if (empty($release)) +{ + print "Error: Missing release paramater\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + exit -1; +} + +$savrelease = $release; + // If release is auto, we take current version $tmpver=explode('-', $release, 2); -if ($tmpver[0] == 'auto') +if ($tmpver[0] == 'auto' || $tmpver[0] == 'autostable') { $release=DOL_VERSION; - if ($tmpver[1]) $release.='-'.$tmpver[1]; + if ($tmpver[1] && $tmpver[0] == 'auto') $release.='-'.$tmpver[1]; } if (empty($includecustom)) { - $tmpver=explode('-', $release, 2); - if (DOL_VERSION != $tmpver[0]) - { - print 'Error: When parameter "includecustom" is not set and there is no suffix in release parameter, version declared into filefunc.in.php ('.DOL_VERSION.') must be exact same value than "release" parameter ('.$tmpver[0].')'."\n"; - print "Usage: ".$script_file." release=x.y.z[-...] [includecustom=1]\n"; - exit -1; - } + $tmpverbis=explode('-', $release, 2); + if (empty($tmpverbis[1]) || $tmpver[0] == 'autostable') + { + if (DOL_VERSION != $tmpverbis[0] && $savrelease != 'auto') + { + print 'Error: When parameter "includecustom" is not set and there is no suffix in release parameter, version declared into filefunc.in.php ('.DOL_VERSION.') must be exact same value than "release" parameter ('.$tmpverbis[0].')'."\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + exit -1; + } + } + else + { + $tmpverter=explode('-', DOL_VERSION, 2); + if ($tmpverter[0] != $tmpverbis[0]) + { + print 'Error: When parameter "includecustom" is not set, version declared into filefunc.in.php ('.DOL_VERSION.') must have value without prefix ('.$tmpverter[0].') that is exact same value than "release" parameter ('.$tmpverbis[0].')'."\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + exit -1; + } + } } else { if (! preg_match('/'.preg_quote(DOL_VERSION,'/').'-/',$release)) { - print 'Error: When parameter "includecustom" is set, version declared into filefunc.inc.php ('.DOL_VERSION.') must be used with a suffix into "release" parmater (ex: '.DOL_VERSION.'-mydistrib).'."\n"; - print "Usage: ".$script_file." release=x.y.z[-...] [includecustom=1]\n"; + print 'Error: When parameter "includecustom" is set, version declared into filefunc.inc.php ('.DOL_VERSION.') must be used with a suffix into "release" parameter (ex: '.DOL_VERSION.'-mydistrib).'."\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; exit -1; } } diff --git a/build/perl/virtualmin/dolibarr.pl b/build/perl/virtualmin/dolibarr.pl index 08d02e8b2b8..589e2a3f55c 100644 --- a/build/perl/virtualmin/dolibarr.pl +++ b/build/perl/virtualmin/dolibarr.pl @@ -1,7 +1,7 @@ #---------------------------------------------------------------------------- # \file dolibarr.pl # \brief Dolibarr script install for Virtualmin Pro -# \author (c)2009-2017 Regis Houssin +# \author (c)2009-2018 Regis Houssin #---------------------------------------------------------------------------- @@ -30,7 +30,7 @@ return "Regis Houssin"; # script_dolibarr_versions() sub script_dolibarr_versions { -return ( "5.0.4", "4.0.6", "3.9.4" ); +return ( "7.0.0", "6.0.5", "5.0.7" ); } sub script_dolibarr_release @@ -386,14 +386,16 @@ sub script_dolibarr_check_latest { local ($ver) = @_; local @vers = &osdn_package_versions("dolibarr", - $ver >= 5.0 ? "dolibarr\\-(5\\.0\\.[0-9\\.]+)\\.tgz" : - $ver >= 4.0 ? "dolibarr\\-(4\\.0\\.[0-9\\.]+)\\.tgz" : - $ver >= 3.9 ? "dolibarr\\-(3\\.9\\.[0-9\\.]+)\\.tgz" : - $ver >= 3.8 ? "dolibarr\\-(3\\.8\\.[0-9\\.]+)\\.tgz" : - $ver >= 3.7 ? "dolibarr\\-(3\\.7\\.[0-9\\.]+)\\.tgz" : - $ver >= 3.6 ? "dolibarr\\-(3\\.6\\.[0-9\\.]+)\\.tgz" : - $ver >= 3.5 ? "dolibarr\\-(3\\.5\\.[0-9\\.]+)\\.tgz" : - $ver >= 2.9 ? "dolibarr\\-(2\\.9\\.[0-9\\.]+)\\.tgz" : + $ver >= 7.0 ? "dolibarr\\-(7\\.0\\.[0-9\\.]+)\\.tgz" : + $ver >= 6.0 ? "dolibarr\\-(6\\.0\\.[0-9\\.]+)\\.tgz" : + $ver >= 5.0 ? "dolibarr\\-(5\\.0\\.[0-9\\.]+)\\.tgz" : + $ver >= 4.0 ? "dolibarr\\-(4\\.0\\.[0-9\\.]+)\\.tgz" : + $ver >= 3.9 ? "dolibarr\\-(3\\.9\\.[0-9\\.]+)\\.tgz" : + $ver >= 3.8 ? "dolibarr\\-(3\\.8\\.[0-9\\.]+)\\.tgz" : + $ver >= 3.7 ? "dolibarr\\-(3\\.7\\.[0-9\\.]+)\\.tgz" : + $ver >= 3.6 ? "dolibarr\\-(3\\.6\\.[0-9\\.]+)\\.tgz" : + $ver >= 3.5 ? "dolibarr\\-(3\\.5\\.[0-9\\.]+)\\.tgz" : + $ver >= 2.9 ? "dolibarr\\-(2\\.9\\.[0-9\\.]+)\\.tgz" : "dolibarr\\-(2\\.8\\.[0-9\\.]+)\\.tgz"); return "Failed to find versions" if (!@vers); return $ver eq $vers[0] ? undef : $vers[0]; diff --git a/build/rpm/dolibarr_fedora.spec b/build/rpm/dolibarr_fedora.spec index 6df6ccf052e..d5a9189229e 100755 --- a/build/rpm/dolibarr_fedora.spec +++ b/build/rpm/dolibarr_fedora.spec @@ -160,6 +160,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/adherents %_datadir/dolibarr/htdocs/admin %_datadir/dolibarr/htdocs/api +%_datadir/dolibarr/htdocs/asset %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/blockedlog @@ -176,6 +177,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/core %_datadir/dolibarr/htdocs/cron %_datadir/dolibarr/htdocs/custom +%_datadir/dolibarr/htdocs/dav %_datadir/dolibarr/htdocs/don %_datadir/dolibarr/htdocs/ecm %_datadir/dolibarr/htdocs/expedition @@ -210,6 +212,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/supplier_proposal %_datadir/dolibarr/htdocs/support %_datadir/dolibarr/htdocs/theme +%_datadir/dolibarr/htdocs/ticket %_datadir/dolibarr/htdocs/user %_datadir/dolibarr/htdocs/variants %_datadir/dolibarr/htdocs/webservices diff --git a/build/rpm/dolibarr_generic.spec b/build/rpm/dolibarr_generic.spec index f99836b7f74..673d5919d1a 100755 --- a/build/rpm/dolibarr_generic.spec +++ b/build/rpm/dolibarr_generic.spec @@ -240,6 +240,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/adherents %_datadir/dolibarr/htdocs/admin %_datadir/dolibarr/htdocs/api +%_datadir/dolibarr/htdocs/asset %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/blockedlog @@ -256,6 +257,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/core %_datadir/dolibarr/htdocs/cron %_datadir/dolibarr/htdocs/custom +%_datadir/dolibarr/htdocs/dav %_datadir/dolibarr/htdocs/don %_datadir/dolibarr/htdocs/ecm %_datadir/dolibarr/htdocs/expedition @@ -290,6 +292,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/supplier_proposal %_datadir/dolibarr/htdocs/support %_datadir/dolibarr/htdocs/theme +%_datadir/dolibarr/htdocs/ticket %_datadir/dolibarr/htdocs/user %_datadir/dolibarr/htdocs/variants %_datadir/dolibarr/htdocs/webservices diff --git a/build/rpm/dolibarr_mandriva.spec b/build/rpm/dolibarr_mandriva.spec index 1034615c80a..e3d2a849db2 100755 --- a/build/rpm/dolibarr_mandriva.spec +++ b/build/rpm/dolibarr_mandriva.spec @@ -157,6 +157,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/adherents %_datadir/dolibarr/htdocs/admin %_datadir/dolibarr/htdocs/api +%_datadir/dolibarr/htdocs/asset %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/blockedlog @@ -173,6 +174,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/core %_datadir/dolibarr/htdocs/cron %_datadir/dolibarr/htdocs/custom +%_datadir/dolibarr/htdocs/dav %_datadir/dolibarr/htdocs/don %_datadir/dolibarr/htdocs/ecm %_datadir/dolibarr/htdocs/expedition @@ -207,6 +209,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/supplier_proposal %_datadir/dolibarr/htdocs/support %_datadir/dolibarr/htdocs/theme +%_datadir/dolibarr/htdocs/ticket %_datadir/dolibarr/htdocs/user %_datadir/dolibarr/htdocs/variants %_datadir/dolibarr/htdocs/webservices diff --git a/build/rpm/dolibarr_opensuse.spec b/build/rpm/dolibarr_opensuse.spec index eb1887f229f..5a64bec2e78 100755 --- a/build/rpm/dolibarr_opensuse.spec +++ b/build/rpm/dolibarr_opensuse.spec @@ -168,6 +168,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/adherents %_datadir/dolibarr/htdocs/admin %_datadir/dolibarr/htdocs/api +%_datadir/dolibarr/htdocs/asset %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/blockedlog @@ -184,6 +185,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/core %_datadir/dolibarr/htdocs/cron %_datadir/dolibarr/htdocs/custom +%_datadir/dolibarr/htdocs/dav %_datadir/dolibarr/htdocs/don %_datadir/dolibarr/htdocs/ecm %_datadir/dolibarr/htdocs/expedition @@ -218,6 +220,7 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/supplier_proposal %_datadir/dolibarr/htdocs/support %_datadir/dolibarr/htdocs/theme +%_datadir/dolibarr/htdocs/ticket %_datadir/dolibarr/htdocs/user %_datadir/dolibarr/htdocs/variants %_datadir/dolibarr/htdocs/webservices diff --git a/build/travis-ci/apache.conf b/build/travis-ci/apache.conf index 5ba713924f2..a4965c40d68 100644 --- a/build/travis-ci/apache.conf +++ b/build/travis-ci/apache.conf @@ -1,11 +1,10 @@ DocumentRoot %TRAVIS_BUILD_DIR%/htdocs - + Options FollowSymLinks MultiViews ExecCGI AllowOverride All - Order deny,allow - Allow from all + Require all granted # Wire up Apache to use Travis CI's php-fpm. @@ -14,5 +13,9 @@ Action php5-fcgi /php5-fcgi Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization + + + Require all granted + diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 9e6ab3a8ddc..cdbc2e2bb40 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -90,6 +90,14 @@ var vTmpNode=this.newNode(vTmpCell, 'div', null, ''); vTmpNode=this.newNode(vTmpNode, 'a', null, '', vLangs[vLang]['moreinfo']); vTmpNode.setAttribute('href',vTaskList[i].getLink()); +* Replace '% Comp.' to have a smaller text column header +'comp':'% Comp.' +with +'comp':'%' + + + + JCROP: ------ diff --git a/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index e5485b280ae..a43e4dde82b 100644 --- a/dev/setup/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -10,6 +10,7 @@ htdocs/conf.php */nltechno* */htdocs/includes + *.min.css @@ -82,7 +83,7 @@ - + @@ -138,9 +139,7 @@ - - 0 - + @@ -156,8 +155,8 @@ - - + + diff --git a/dev/tools/github_authors_peryear.sh b/dev/tools/github_authors_peryear.sh index 99b28d4d417..1f3a7fea5f6 100755 --- a/dev/tools/github_authors_peryear.sh +++ b/dev/tools/github_authors_peryear.sh @@ -1,7 +1,13 @@ #!/bin/sh -FROM=2016-01-01 -TO=2016-12-31 +if [ "x$1" = "x" ]; then + echo "Usage: $0 YEAR" + exit +fi + + +FROM=$1-01-01 +TO=$1-12-31 echo "git log --since $FROM --before $TO | grep ^Author | sort -u -f -i -b | wc -l" git log --since $FROM --before $TO | grep ^Author | sort -u -f -i -b | wc -l diff --git a/dev/tools/github_commits_perversion.sh b/dev/tools/github_commits_perversion.sh index 40ddafee617..bf76e68bc43 100755 --- a/dev/tools/github_commits_perversion.sh +++ b/dev/tools/github_commits_perversion.sh @@ -1,10 +1,11 @@ #/bin/bash -Releases=("3.8" "3.9" "4.0" "5.0", "develop") -Dates=("2010-01-01", "2011-01-01", "2012-01-01", "2013-01-01", "2014-01-01", "2015-01-01", "2016-07-01") +Releases=("3.8" "3.9" "4.0" "5.0" "6.0" " 7.0" "develop") +Dates=("2013-01-01", "2014-01-01", "2015-01-01", "2016-07-01", "2017-02-01", "2017-07-01", "2018-02-01", "2050-01-01") let "counter = 1" for i in "${Releases[@]}" do + echo "=== $counter git shortlog -s -n --after=${Dates[counter-1]} --before=${Dates[counter]}" git shortlog -s -n --after=${Dates[counter-1]} --before=${Dates[counter]} echo -n "Total $i: " git log --pretty=oneline --after=${Dates[counter-1]} --before=${Dates[counter]} | wc -l diff --git a/dev/tools/test/testtcpdf.php b/dev/tools/test/testtcpdf.php index ad67bce8af9..e14dae9c2a3 100755 --- a/dev/tools/test/testtcpdf.php +++ b/dev/tools/test/testtcpdf.php @@ -101,7 +101,7 @@ $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks -$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); +$pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); diff --git a/dev/tools/test/testutf.php b/dev/tools/test/testutf.php index cb83f431b93..c626a92a57d 100644 --- a/dev/tools/test/testutf.php +++ b/dev/tools/test/testutf.php @@ -76,7 +76,7 @@ $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks -$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); +$pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM); //set image scale factor //$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); diff --git a/dev/translation/sanity_check_en_langfiles.php b/dev/translation/sanity_check_en_langfiles.php index f65cefd7f94..2eedcda8760 100755 --- a/dev/translation/sanity_check_en_langfiles.php +++ b/dev/translation/sanity_check_en_langfiles.php @@ -295,6 +295,9 @@ if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($a if (preg_match('/^DescADHERENT_/', $value)) $qualifiedforclean=0; if (preg_match('/^SubmitTranslation/', $value)) $qualifiedforclean=0; if (preg_match('/^ModuleCompanyCode/', $value)) $qualifiedforclean=0; + // admin.lang + if (preg_match('/^DAV_ALLOW_PUBLIC_DIR/i', $value)) $qualifiedforclean=0; + if (preg_match('/^DAV_ALLOW_ECM_DIR/i', $value)) $qualifiedforclean=0; // boxes.lang if (preg_match('/^BoxTitleLast/', $value)) $qualifiedforclean=0; if (preg_match('/^BoxTitleLatest/', $value)) $qualifiedforclean=0; diff --git a/dev/translation/txpush.sh b/dev/translation/txpush.sh index f64b60f9d3b..339b24d2c30 100755 --- a/dev/translation/txpush.sh +++ b/dev/translation/txpush.sh @@ -15,7 +15,7 @@ then echo "This push local files to transifex for project $project." echo "Note: If you push a language file (not source), file will be skipped if transifex file is newer." echo " Using -f will overwrite translation but not memory." - echo "Usage: ./dev/translation/txpush.sh (source|xx_XX|all) [-r ".$project.".file] [-f] [--no-interactive]" + echo "Usage: ./dev/translation/txpush.sh (source|xx_XX|all) [-r $project.file] [-f] [--no-interactive]" exit fi diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 8eca415bff9..493c9e62717 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2016-2017 Laurent Destailleur + * Copyright (C) 2016-2018 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 @@ -28,18 +28,15 @@ 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'; -// Langs -$langs->load("compta"); -$langs->load("bills"); -$langs->load("admin"); -$langs->load("accountancy"); -$langs->load("salaries"); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","admin","accountancy","salaries")); $mesg = ''; $action = GETPOST('action','aZ09'); $cancel = GETPOST('cancel','alpha'); $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'accountingaccountlist'; // To manage different context of search $search_account = GETPOST("search_account"); $search_label = GETPOST("search_label"); @@ -74,8 +71,6 @@ $arrayfields=array( $accounting = new AccountingAccount($db); -// Initialize technical object to manage context to save list fields -$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'accountingaccountlist'; /* @@ -177,11 +172,10 @@ $sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.acco $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version AND aa.entity = " . $conf->entity; -// Dirty hack wainting that foreign key account_parent is an integer to be compared correctly with rowid -if ($db->type == 'pgsql') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = CAST(aa.account_parent AS INTEGER) AND a2.entity = " . $conf->entity; -else $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = CAST(aa.account_parent AS UNSIGNED) AND a2.entity = " . $conf->entity; +if ($db->type == 'pgsql') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = " . $conf->entity; +else $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as a2 ON a2.rowid = aa.account_parent AND a2.entity = " . $conf->entity; $sql .= " WHERE asy.rowid = " . $pcgver; - +//print $sql; if (strlen(trim($search_account))) $sql .= natural_search("aa.account_number", $search_account); if (strlen(trim($search_label))) $sql .= natural_search("aa.label", $search_label); if (strlen(trim($search_accountparent))) $sql .= natural_search("aa.account_parent", $search_accountparent); @@ -195,6 +189,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); $nbtotalofrecords = $db->num_rows($resql); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql .= $db->plimit($limit + 1, $offset); @@ -227,9 +226,11 @@ if ($resql) print ''; print ''; - $htmlbuttonadd = '' . $langs->trans("Addanaccount") . ''; + $newcardbutton = '' . $langs->trans("Addanaccount").''; + $newcardbutton.= ''; + $newcardbutton.= ''; - print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $htmlbuttonadd, '', $limit); + print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit); // Box to select active chart of account print $langs->trans("Selectchartofaccounts") . " : "; @@ -257,7 +258,7 @@ if ($resql) else dol_print_error($db); print ""; print ajax_combobox("chartofaccounts"); - print ''; + print ''; print '
'; print '
'; @@ -276,7 +277,7 @@ if ($resql) if (! empty($arrayfields['aa.pcg_type']['checked'])) print ''; if (! empty($arrayfields['aa.pcg_subtype']['checked'])) print ''; if (! empty($arrayfields['aa.active']['checked'])) print ' '; - print ''; + print ''; $searchpicto=$form->showFilterAndCheckAddButtons($massactionbutton?1:0, 'checkforselect', 1); print $searchpicto; print ''; @@ -310,7 +311,7 @@ if ($resql) if (! empty($arrayfields['aa.account_number']['checked'])) { print ""; - print $accountstatic->getNomUrl(1); + print $accountstatic->getNomUrl(1, 0, 0, '', 0, 1); print "\n"; if (! $i) $totalarray['nbfield']++; } diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index df4f5d7c3f5..f024f54c41c 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -4,7 +4,7 @@ * 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-2018 Philippe Grand * Copyright (C) 2011 Remy Younes * Copyright (C) 2012-2015 Marcos García * Copyright (C) 2012 Christophe Battarel @@ -41,6 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; +// Load translation files required by the page $langs->loadLangs(array("errors","admin","companies","resource","holiday","compta","accountancy","hrm")); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; @@ -617,25 +618,13 @@ 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 (empty($reshook)) { - if ($tabname[$id] == MAIN_DB_PREFIX.'c_email_templates' && $action == 'edit') - { - fieldListAccountModel($fieldlist,$obj,$tabname[$id],'hide'); - } - else - { - fieldListAccountModel($fieldlist,$obj,$tabname[$id],'add'); - } + fieldListAccountModel($fieldlist,$obj,$tabname[$id],'add'); } print ''; - if ($tabname[$id] != MAIN_DB_PREFIX.'c_email_templates' || $action != 'edit') - { - print ''; - } + print ''; print ''; print ""; @@ -657,7 +646,6 @@ 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; @@ -854,7 +842,7 @@ if ($id) $valuetoshow=price($valuetoshow); } else if ($fieldlist[$field]=='libelle_facture') { - $langs->load("bills"); + $langs->loadLangs(array("bills")); $key=$langs->trans("PaymentCondition".strtoupper($obj->code)); $valuetoshow=($obj->code && $key != "PaymentCondition".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); $valuetoshow=nl2br($valuetoshow); @@ -864,7 +852,7 @@ if ($id) $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"); + $langs->loadLangs(array("propal")); $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); } @@ -889,17 +877,17 @@ if ($id) $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'); + $langs->loadLangs(array("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"); + $langs->loadLangs(array("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"); + $langs->loadLangs(array("bills")); $key=$langs->trans("PaymentType".strtoupper($obj->code)); $valuetoshow=($obj->code && $key != "PaymentType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); } @@ -908,12 +896,12 @@ if ($id) $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"); + $langs->loadLangs(array("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"); + $langs->loadLangs(array("sendings")); $key=$langs->trans("SendingMethod".strtoupper($obj->code)); $valuetoshow=($obj->code && $key != "SendingMethod".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); } @@ -924,7 +912,7 @@ if ($id) } else if ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') { - $langs->load('trips'); + $langs->loadLangs(array("trips")); $key = $langs->trans(strtoupper($obj->code)); $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); } @@ -935,11 +923,11 @@ if ($id) $valuetoshow = $langs->getCurrencySymbol($obj->code,1); } else if ($fieldlist[$field]=='label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); + $langs->loadLangs(array("products")); $valuetoshow=$langs->trans($obj->{$fieldlist[$field]}); } else if ($fieldlist[$field]=='short_label' && $tabname[$_GET["id"]]==MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); + $langs->loadLangs(array("products")); $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); } else if (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) @@ -987,13 +975,7 @@ if ($id) // Active 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"); - } + else print $langs->trans("AlwaysActive"); print ""; // Modify link @@ -1042,7 +1024,6 @@ function fieldListAccountModel($fieldlist, $obj='', $tabname='', $context='') global $form; global $region_id; global $elementList,$sourceList; - global $bc; $formadmin = new FormAdmin($db); $formcompany = new FormCompany($db); @@ -1142,16 +1123,11 @@ function fieldListAccountModel($fieldlist, $obj='', $tabname='', $context='') } 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 ''; + 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); } diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index 82ba00a882c..9643227da64 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -31,9 +31,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; $error = 0; -// Langs -$langs->load("bills"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("bills","accountancy")); $mesg = ''; $action = GETPOST('action','aZ09'); @@ -188,12 +187,10 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) } } + /* * View */ -$title = $langs->trans('AccountAccounting') ." - ". $langs->trans('Card'); -$helpurl = ''; -llxheader('', $title, $helpurl); $form = new Form($db); $formaccounting = new FormAccounting($db); @@ -201,6 +198,11 @@ $formaccounting = new FormAccounting($db); $accountsystem = new AccountancySystem($db); $accountsystem->fetch($conf->global->CHARTOFACCOUNTS); +$title = $langs->trans('AccountAccounting') ." - ". $langs->trans('Card'); +$helpurl = ''; +llxheader('', $title, $helpurl); + + // Create mode if ($action == 'create') { print load_fiche_titre($langs->trans('NewAccountingAccount')); @@ -330,7 +332,7 @@ else if ($id > 0 || $ref) { print ''; } else { // View mode - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; dol_fiche_head($head, 'card', $langs->trans('AccountAccounting'), -1, 'billr'); @@ -397,4 +399,4 @@ else if ($id > 0 || $ref) { llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/accountancy/admin/categories.php b/htdocs/accountancy/admin/categories.php index 9c40802c925..aec34469559 100644 --- a/htdocs/accountancy/admin/categories.php +++ b/htdocs/accountancy/admin/categories.php @@ -29,8 +29,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; $error = 0; -$langs->load("bills"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("bills","accountancy")); $mesg = ''; $id = GETPOST('id', 'int'); @@ -53,6 +53,11 @@ if (empty($user->rights->accounting->chartofaccount)) $accountingcategory = new AccountancyCategory($db); + +/* + * Actions + */ + // si ajout de comptes if (! empty($selectcpt)) { $cpts = array (); @@ -66,7 +71,7 @@ if (! empty($selectcpt)) { if ($return<0) { setEventMessages($langs->trans('errors'), $accountingcategory->errors, 'errors'); } else { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); + setEventMessages($langs->trans('SetupSaved'), null, 'mesgs'); } } if ($action == 'delete') { @@ -83,6 +88,7 @@ if ($action == 'delete') { /* * View */ + $form = new Form($db); $formaccounting = new FormAccounting($db); @@ -99,13 +105,15 @@ print ''; dol_fiche_head(); print ''; -// Category + +// Select the category print ''; print ''; +// Select the accounts if (! empty($cat_id)) { $return = $accountingcategory->getAccountsWithNoCategory($cat_id); @@ -153,7 +161,7 @@ if ($action == 'display' || $action == 'delete') { print "\n"; if (! empty($cat_id)) { - $return = $accountingcategory->display($cat_id); + $return = $accountingcategory->display($cat_id); // This load ->lines_display if ($return < 0) { setEventMessages(null, $accountingcategory->errors, 'errors'); } diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index 40ea103a12f..15a50e7b8e8 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +// Load translation files required by the page $langs->loadLangs(array("errors","admin","companies","resource","holiday","accountancy","hrm")); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; @@ -178,7 +179,7 @@ if (GETPOST('actionadd') || GETPOST('actionmodify')) } if (! is_numeric(GETPOST('position','alpha'))) { - $langs->load("errors"); + $langs->loadLangs(array("errors")); $ok=0; setEventMessages($langs->transnoentities('ErrorFieldMustBeANumeric', $langs->transnoentities("Position")), null, 'errors'); } @@ -456,7 +457,6 @@ if ($id) if ($tabname[$id]) { $alabelisused=0; - $var=false; $fieldlist=explode(',',$tabfield[$id]); @@ -550,7 +550,6 @@ 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; @@ -720,7 +719,7 @@ if ($id) $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"); + $langs->loadLangs(array("propal")); $key=$langs->trans("AvailabilityType".strtoupper($obj->code)); $valuetoshow=($obj->code && $key != "AvailabilityType".strtoupper($obj->code)?$key:$obj->{$fieldlist[$field]}); } diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index c4b31c0f169..c33d4326836 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -34,12 +34,8 @@ 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 . '/core/class/html.formaccounting.class.php'; -$langs->load("compta"); -$langs->load("bills"); -$langs->load("admin"); -$langs->load("accountancy"); -$langs->load("salaries"); -$langs->load("loan"); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","admin","accountancy","salaries","loan")); // Security check if (empty($user->rights->accounting->chartofaccount)) diff --git a/htdocs/accountancy/admin/export.php b/htdocs/accountancy/admin/export.php index dbe2a3b0c1c..79588db5ac1 100644 --- a/htdocs/accountancy/admin/export.php +++ b/htdocs/accountancy/admin/export.php @@ -28,15 +28,12 @@ */ 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/accountancyexport.class.php'; -$langs->load("compta"); -$langs->load("bills"); -$langs->load("admin"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","admin","accountancy")); // Security access if (empty($user->rights->accounting->chartofaccount)) diff --git a/htdocs/accountancy/admin/fiscalyear.php b/htdocs/accountancy/admin/fiscalyear.php index 147c140bdd1..25223e70c68 100644 --- a/htdocs/accountancy/admin/fiscalyear.php +++ b/htdocs/accountancy/admin/fiscalyear.php @@ -39,8 +39,8 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield="f.rowid"; // Set here default search field if (! $sortorder) $sortorder="ASC"; -$langs->load("admin"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array("admin","compta")); // Security check if ($user->societe_id > 0) @@ -95,6 +95,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); @@ -153,4 +158,4 @@ if ($result) llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php index 78c6510469b..32df9afc932 100644 --- a/htdocs/accountancy/admin/fiscalyear_card.php +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -26,8 +26,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/fiscalyear.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/fiscalyear.class.php'; -$langs->load("admin"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array("admin","compta")); // Security check if ($user->societe_id > 0) diff --git a/htdocs/accountancy/admin/fiscalyear_info.php b/htdocs/accountancy/admin/fiscalyear_info.php index baadbdc0828..f16e3b9ca0e 100644 --- a/htdocs/accountancy/admin/fiscalyear_info.php +++ b/htdocs/accountancy/admin/fiscalyear_info.php @@ -26,8 +26,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/fiscalyear.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/fiscalyear.class.php'; -$langs->load("admin"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array("admin","compta")); // Security check if ($user->societe_id > 0) diff --git a/htdocs/accountancy/admin/importaccounts.php b/htdocs/accountancy/admin/importaccounts.php index 93d41b3cbc6..3af46eec1a4 100644 --- a/htdocs/accountancy/admin/importaccounts.php +++ b/htdocs/accountancy/admin/importaccounts.php @@ -24,16 +24,12 @@ */ require '../../main.inc.php'; -// Class 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 . '/core/class/html.formaccounting.class.php'; -// langs -$langs->load("compta"); -$langs->load("bills"); -$langs->load("main"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","accountancy")); // Security check if (! $user->admin) @@ -141,7 +137,6 @@ if ($result) { $form = new Form($db); $formaccounting = new FormAccounting($db); - $var = true; while ( $i < min($num_lines, $limit) ) { $objp = $db->fetch_object($result); print ''; diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 44c816530dd..e39d07fc35d 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2013-2018 Alexandre Spangaro * Copyright (C) 2014-2015 Ari Elbaz (elarifr) * Copyright (C) 2014 Marcos García * Copyright (C) 2014 Juanjo Menent @@ -32,10 +32,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -$langs->load("compta"); -$langs->load("bills"); -$langs->load("admin"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","admin","accountancy")); // Security access if (empty($user->rights->accounting->chartofaccount)) @@ -134,6 +132,18 @@ if ($action == 'setdisabledirectinput') { } } +if ($action == 'setenabledraftexport') { + $setenabledraftexport = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL", $setenabledraftexport, 'yesno', 0, '', $conf->entity); + if (! $res > 0) + $error ++; + if (! $error) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } else { + setEventMessages($langs->trans("Error"), null, 'mesgs'); + } +} + /* * View */ @@ -215,6 +225,19 @@ if (! empty($user->admin)) } print ''; + print ''; + print ''; + if (! empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) { + print ''; + } else { + print ''; + } + print ''; + print ''; print ''; if (! empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) { diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index f2f862a9cdd..ff3a38769b8 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -21,6 +21,7 @@ * \ingroup Advanced accountancy * \brief Setup page to configure journals */ + 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'; @@ -30,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +// Load translation files required by the page $langs->loadLangs(array("admin","compta","accountancy")); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; @@ -133,6 +135,7 @@ $elementList = array(); '3' => $langs->trans('AccountingJournalType3'), '4' => $langs->trans('AccountingJournalType4'), '5' => $langs->trans('AccountingJournalType5'), + '8' => $langs->trans('AccountingJournalType8'), '9' => $langs->trans('AccountingJournalType9') ); @@ -416,7 +419,6 @@ if ($id) if ($tabname[$id]) { $alabelisused=0; - $var=false; $fieldlist=explode(',',$tabfield[$id]); @@ -496,7 +498,6 @@ 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; @@ -601,6 +602,7 @@ if ($id) if (empty($reshook)) { + $langs->load("accountancy"); foreach ($fieldlist as $field => $value) { @@ -611,10 +613,12 @@ if ($id) $valuetoshow=$langs->trans('All'); } else if ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { - $langs->load("accountancy"); $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature)); - $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($obj->nature)?$key:$obj->{$fieldlist[$field]}); + $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($langs->trans($obj->nature))?$key:$obj->{$fieldlist[$field]}); } + else if ($fieldlist[$field]=='label' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') { + $valuetoshow=$langs->trans($obj->label); + } $class='tddict'; // Show value for field @@ -640,13 +644,7 @@ if ($id) // Active print '"; // Modify link diff --git a/htdocs/accountancy/admin/productaccount.php b/htdocs/accountancy/admin/productaccount.php index e07d0c24771..070e2f353c3 100644 --- a/htdocs/accountancy/admin/productaccount.php +++ b/htdocs/accountancy/admin/productaccount.php @@ -26,7 +26,6 @@ */ require '../../main.inc.php'; -// Class require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php'; @@ -35,12 +34,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; -// Langs -$langs->load("companies"); -$langs->load("compta"); -$langs->load("main"); -$langs->load("accountancy"); -$langs->load("products"); +// Load translation files required by the page +$langs->loadLangs(array("companies","compta","accountancy","products")); // Security check if (empty($conf->accounting->enabled)) { @@ -261,7 +256,13 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } + $sql .= $db->plimit($limit + 1, $offset); dol_syslog("/accountancy/admin/productaccount.php:: sql=" . $sql, LOG_DEBUG); @@ -272,8 +273,8 @@ if ($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 (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($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); @@ -300,10 +301,10 @@ if ($result) print ''; print ''; print "\n"; - print ''; + print ''; print '\n"; - print ''; + print ''; print '\n"; print "
' . $langs->trans("AccountingCategory") . ''; $formaccounting->select_accounting_category($cat_id, 'account_category', 1, 0, 0, 1); print ''; print '
' . $langs->trans("ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL") . ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
' . $langs->trans("BANK_DISABLE_DIRECT_INPUT") . ''; 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"); - } + else print $langs->trans("AlwaysActive"); print "
' . $langs->trans('Options') . '' . $langs->trans('Description') . '
' . $langs->trans('OptionModeProductSell') . '
' . $langs->trans('OptionModeProductSell') . ''.$langs->trans('OptionModeProductSellDesc'); print "
' . $langs->trans('OptionModeProductBuy') . '
' . $langs->trans('OptionModeProductBuy') . ''.$langs->trans('OptionModeProductBuyDesc')."
\n"; @@ -328,9 +329,9 @@ if ($result) print ''; if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print ''; // On sell - print ''; + if ($accounting_product_mode == 'ACCOUNTANCY_SELL') print ''; // On buy - print ''; + if ($accounting_product_mode == 'ACCOUNTANCY_BUY') print ''; // Current account print ''; print ''; @@ -348,11 +349,9 @@ if ($result) print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder); if (! empty($conf->global->ACCOUNTANCY_SHOW_PROD_DESC)) print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "p.description", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre("OnSell", $_SERVER["PHP_SELF"], "p.tosell", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre("OnBuy", $_SERVER["PHP_SELF"], "p.tobuy", "", $param, 'align="center"', $sortfield, $sortorder); - if ($accounting_product_mode == 'ACCOUNTANCY_BUY') { - $fieldtosortaccount="p.accountancy_code_buy"; - } + if ($accounting_product_mode == 'ACCOUNTANCY_SELL') print_liste_field_titre("OnSell", $_SERVER["PHP_SELF"], "p.tosell", "", $param, 'align="center"', $sortfield, $sortorder); + if ($accounting_product_mode == 'ACCOUNTANCY_BUY') print_liste_field_titre("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("CurrentDedicatedAccountingAccount", $_SERVER["PHP_SELF"], $fieldtosortaccount, "", $param, '', $sortfield, $sortorder); print_liste_field_titre("AssignDedicatedAccountingAccount"); @@ -362,7 +361,6 @@ if ($result) $product_static = new Product($db); - $var = true; $i=0; while ($i < min($num,$limit)) { @@ -410,9 +408,11 @@ if ($result) print '' . nl2br(dol_trunc($obj->description, $trunclengh)) . ''; } - print ''.$product_static->getLibStatut(3, 0).''; + if ($accounting_product_mode == 'ACCOUNTANCY_SELL') + print ''.$product_static->getLibStatut(3, 0).''; - print ''.$product_static->getLibStatut(3, 1).''; + if ($accounting_product_mode == 'ACCOUNTANCY_BUY') + print ''.$product_static->getLibStatut(3, 1).''; // Current accounting account print ''; @@ -496,4 +496,4 @@ if ($result) } llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 15e7acd7deb..284ead4fb56 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -1,7 +1,7 @@ - * Copyright (C) 2016 Florian Henry - * Copyright (C) 2016-2017 Alexandre Spangaro +/* Copyright (C) 2016 Olivier Geffroy + * Copyright (C) 2016 Florian Henry + * Copyright (C) 2016-2018 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -34,12 +34,12 @@ require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountancyexport.class.php require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; -// Langs -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("accountancy")); $page = GETPOST("page"); -$sortorder = GETPOST("sortorder"); -$sortfield = GETPOST("sortfield"); +$sortorder = GETPOST("sortorder", 'alpha'); +$sortfield = GETPOST("sortfield", 'alpha'); $action = GETPOST('action', 'alpha'); $search_date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); $search_date_end = dol_mktime(0, 0, 0, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int')); @@ -53,7 +53,7 @@ if ($search_accountancy_code_end == - 1) { $search_accountancy_code_end = ''; } -if (GETPOST("exportcsv")) $action = 'export_csv'; +if (GETPOST("exportcsv",'alpha')) $action = 'export_csv'; $limit = GETPOST('limit','int')?GETPOST('limit', 'int'):$conf->liste_limit; @@ -138,8 +138,7 @@ if ($action == 'export_csv') { $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - $journal = 'balance'; - + $filename = 'balance'; include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; $result = $object->fetchAllBalance($sortorder, $sortfield, 0, 0, $filter); @@ -153,7 +152,6 @@ if ($action == 'export_csv') { print $object->get_compte_desc($line->numero_compte) . $sep; print price($line->debit) . $sep; print price($line->credit) . $sep; - print price($line->debit) . $sep; print price($line->credit - $line->debit) . $sep; print "\n"; } @@ -189,7 +187,7 @@ else { print ''; $button = 'global->ACCOUNTING_EXPORT_FORMAT.')" />'; - print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, '', $result, $result, 'title_accountancy', 0, $button); + print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $options, $sortfield, $sortorder, $button, $result, $result, 'title_accountancy', 0); $moreforfilter = ''; @@ -254,8 +252,8 @@ else { print ''; // Permet d'afficher le compte comptable - if ($root_account_description != $displayed_account) { - + if (empty($displayed_account) || $root_account_description != $displayed_account) + { // Affiche un Sous-Total par compte comptable if ($displayed_account != "") { print '' . $langs->trans("SubTotal") . ':' . price($sous_total_debit) . '' . price($sous_total_credit) . '' . price($sous_total_credit - $sous_total_debit) . ''; @@ -263,9 +261,9 @@ else { print ''; } - // Affiche le compte comptable en d�but de ligne + // Affiche le compte comptable en debut de ligne print ""; - print '' . $root_account_description . ''; + print '' . $line->numero_compte . ($root_account_description ? ' - ' . $root_account_description : '') . ''; print ''; $displayed_account = $root_account_description; diff --git a/htdocs/accountancy/bookkeeping/balancebymonth.php b/htdocs/accountancy/bookkeeping/balancebymonth.php index 1d746b4d4df..03265e434f6 100644 --- a/htdocs/accountancy/bookkeeping/balancebymonth.php +++ b/htdocs/accountancy/bookkeeping/balancebymonth.php @@ -26,16 +26,11 @@ */ require '../../main.inc.php'; -// Class require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; -// Langs -$langs->load("main"); -$langs->load("compta"); -$langs->load("bills"); -$langs->load("other"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("bills","compta","accountancy","other")); // Filter $year = GETPOST("year",'int'); @@ -75,10 +70,23 @@ if ($result) { $y = $year_current; -$var = true; - print ''; -print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; $sql = "SELECT bk.numero_compte AS 'compte',"; $sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=1,bk.montant,0)),2) AS 'Janvier',"; @@ -108,7 +116,7 @@ if ($resql) { $row = $db->fetch_row($resql); - print ''; + print ''; print ''; print ''; print ''; @@ -133,4 +141,4 @@ if ($resql) { print "
' . $langs->trans("Label") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . 'Total
' . $langs->trans("Label") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . 'Total
' . length_accountg($row[0]) . '
' . length_accountg($row[0]) . '' . price($row[1]) . '' . price($row[2]) . '' . price($row[3]) . '
\n"; llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index 9dcb924779e..92c5713880c 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -1,8 +1,8 @@ - * Copyright (C) 2013-2017 Florian Henry - * Copyright (C) 2013-2017 Alexandre Spangaro - * Copyright (C) 2017 Laurent Destailleur +/* Copyright (C) 2013-2017 Olivier Geffroy + * Copyright (C) 2013-2017 Florian Henry + * Copyright (C) 2013-2018 Alexandre Spangaro + * Copyright (C) 2017 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -32,9 +32,8 @@ require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; -$langs->load("accountancy"); -$langs->load("bills"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array("accountancy", "bills", "compta")); $action = GETPOST('action','aZ09'); @@ -89,36 +88,36 @@ if ($action == "confirm_update") { if (! $error) { - $book = new BookKeeping($db); + $object = new BookKeeping($db); - $result = $book->fetch($id, null, $mode); + $result = $object->fetch($id, null, $mode); if ($result < 0) { $error++; - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { - $book->numero_compte = $account_number; - $book->subledger_account = $subledger_account; - $book->label_compte = $label_compte; - $book->label_operation= $label_operation; - $book->debit = $debit; - $book->credit = $credit; + $object->numero_compte = $account_number; + $object->subledger_account = $subledger_account; + $object->label_compte = $label_compte; + $object->label_operation= $label_operation; + $object->debit = $debit; + $object->credit = $credit; if (floatval($debit) != 0.0) { - $book->montant = $debit; - $book->sens = 'D'; + $object->montant = $debit; + $object->sens = 'D'; } if (floatval($credit) != 0.0) { - $book->montant = $credit; - $book->sens = 'C'; + $object->montant = $credit; + $object->sens = 'C'; } - $result = $book->update($user, false, $mode); + $result = $object->update($user, false, $mode); if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { if ($mode != '_tmp') { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } $debit = 0; @@ -147,39 +146,39 @@ else if ($action == "add") { } if (! $error) { - $book = new BookKeeping($db); + $object = new BookKeeping($db); - $book->numero_compte = $account_number; - $book->subledger_account = $subledger_account; - $book->label_compte = $label_compte; - $book->label_operation= $label_operation; - $book->debit = $debit; - $book->credit = $credit; - $book->doc_date = GETPOST('doc_date','alpha'); - $book->doc_type = GETPOST('doc_type','alpha'); - $book->piece_num = $piece_num; - $book->doc_ref = GETPOST('doc_ref','alpha'); - $book->code_journal = GETPOST('code_journal','alpha'); - $book->fk_doc = GETPOST('fk_doc','alpha'); - $book->fk_docdet = GETPOST('fk_docdet','alpha'); + $object->numero_compte = $account_number; + $object->subledger_account = $subledger_account; + $object->label_compte = $label_compte; + $object->label_operation= $label_operation; + $object->debit = $debit; + $object->credit = $credit; + $object->doc_date = GETPOST('doc_date','alpha'); + $object->doc_type = GETPOST('doc_type','alpha'); + $object->piece_num = $piece_num; + $object->doc_ref = GETPOST('doc_ref','alpha'); + $object->code_journal = GETPOST('code_journal','alpha'); + $object->fk_doc = GETPOST('fk_doc','alpha'); + $object->fk_docdet = GETPOST('fk_docdet','alpha'); if (floatval($debit) != 0.0) { - $book->montant = $debit; - $book->sens = 'D'; + $object->montant = $debit; + $object->sens = 'D'; } if (floatval($credit) != 0.0) { - $book->montant = $credit; - $book->sens = 'C'; + $object->montant = $credit; + $object->sens = 'C'; } - $result = $book->createStd($user, false, $mode); + $result = $object->createStd($user, false, $mode); if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { if ($mode != '_tmp') { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } $debit = 0; @@ -191,17 +190,17 @@ else if ($action == "add") { } else if ($action == "confirm_delete") { - $book = new BookKeeping($db); + $object = new BookKeeping($db); - $result = $book->fetch($id, null, $mode); - $piece_num = $book->piece_num; + $result = $object->fetch($id, null, $mode); + $piece_num = $object->piece_num; if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { - $result = $book->delete($user, false, $mode); + $result = $object->delete($user, false, $mode); if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } $action = ''; @@ -210,7 +209,7 @@ else if ($action == "confirm_delete") { else if ($action == "confirm_create") { $error = 0; - $book = new BookKeeping($db); + $object = new BookKeeping($db); if (! GETPOST('code_journal','alpha') || GETPOST('code_journal','alpha') == '-1') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Journal")), null, 'errors'); @@ -225,29 +224,29 @@ else if ($action == "confirm_create") { if (! $error) { - $book->label_compte = ''; - $book->debit = 0; - $book->credit = 0; - $book->doc_date = $date_start = dol_mktime(0, 0, 0, GETPOST('doc_datemonth','int'), GETPOST('doc_dateday','int'), GETPOST('doc_dateyear','int')); - $book->doc_type = GETPOST('doc_type','alpha'); - $book->piece_num = GETPOST('next_num_mvt','alpha'); - $book->doc_ref = GETPOST('doc_ref','alpha'); - $book->code_journal = GETPOST('code_journal','alpha'); - $book->fk_doc = 0; - $book->fk_docdet = 0; - $book->montant = 0; + $object->label_compte = ''; + $object->debit = 0; + $object->credit = 0; + $object->doc_date = $date_start = dol_mktime(0, 0, 0, GETPOST('doc_datemonth','int'), GETPOST('doc_dateday','int'), GETPOST('doc_dateyear','int')); + $object->doc_type = GETPOST('doc_type','alpha'); + $object->piece_num = GETPOST('next_num_mvt','alpha'); + $object->doc_ref = GETPOST('doc_ref','alpha'); + $object->code_journal = GETPOST('code_journal','alpha'); + $object->fk_doc = 0; + $object->fk_docdet = 0; + $object->montant = 0; - $result = $book->createStd($user,0, $mode); + $result = $object->createStd($user,0, $mode); if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { if ($mode != '_tmp') { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } $action = 'update'; - $id=$book->id; - $piece_num = $book->piece_num; + $id=$object->id; + $piece_num = $object->piece_num; } } } @@ -260,7 +259,7 @@ if ($action == 'setdate') { } else { if ($mode != '_tmp') { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } $action = ''; } @@ -274,7 +273,7 @@ if ($action == 'setjournal') { } else { if ($mode != '_tmp') { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } $action = ''; } @@ -288,7 +287,7 @@ if ($action == 'setdocref') { } else { if ($mode != '_tmp') { - setEventMessages($langs->trans('Saved'), null, 'mesgs'); + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); } $action = ''; } @@ -326,8 +325,8 @@ if ($action == 'create') { print load_fiche_titre($langs->trans("CreateMvts")); - $book = new BookKeeping($db); - $next_num_mvt = $book->getNextNumMvt('_tmp'); + $object = new BookKeeping($db); + $next_num_mvt = $object->getNextNumMvt('_tmp'); if (empty($next_num_mvt)) { @@ -361,7 +360,7 @@ if ($action == 'create') print ''; print ''; - print '' . $langs->trans("Docref") . ''; + print '' . $langs->trans("Piece") . ''; print ''; print ''; @@ -384,13 +383,13 @@ if ($action == 'create') print ''; } else { - $book = new BookKeeping($db); - $result = $book->fetchPerMvt($piece_num, $mode); + $object = new BookKeeping($db); + $result = $object->fetchPerMvt($piece_num, $mode); if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } - if (! empty($book->piece_num)) + if (! empty($object->piece_num)) { $backlink = '' . $langs->trans('BackToList') . ''; @@ -398,14 +397,14 @@ if ($action == 'create') $head=array(); $h=0; - $head[$h][0] = $_SERVER['PHP_SELF'].'?piece_num='.$book->piece_num.($mode?'&mode='.$mode:''); + $head[$h][0] = $_SERVER['PHP_SELF'].'?piece_num='.$object->piece_num.($mode?'&mode='.$mode:''); $head[$h][1] = $langs->trans("Transaction"); $head[$h][2] = 'transaction'; $h++; dol_fiche_head($head, 'transaction', '', -1); - //dol_banner_tab($book, '', $backlink); + //dol_banner_tab($object, '', $backlink); print '
'; print '
'; @@ -416,7 +415,7 @@ if ($action == 'create') // Account movement print ''; print '' . $langs->trans("NumMvts") . ''; - print '' . $book->piece_num . ''; + print '' . $object->piece_num . ''; print ''; // Date @@ -425,19 +424,19 @@ if ($action == 'create') print $langs->trans('Docdate'); print ''; if ($action != 'editdate') - print 'piece_num .'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('SetDate'),1).''; + print 'piece_num .'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('SetDate'),1).''; print ''; print ''; if ($action == 'editdate') { - print '
'; + print ''; print ''; print ''; print ''; - $form->select_date($book->doc_date ? $book->doc_date : - 1, 'doc_date', '', '', '', "setdate"); + $form->select_date($object->doc_date ? $object->doc_date : - 1, 'doc_date', '', '', '', "setdate"); print ''; print '
'; } else { - print $book->doc_date ? dol_print_date($book->doc_date, 'day') : ' '; + print $object->doc_date ? dol_print_date($object->doc_date, 'day') : ' '; } print ''; print ''; @@ -448,19 +447,19 @@ if ($action == 'create') print $langs->trans('Codejournal'); print ''; if ($action != 'editjournal') - print 'piece_num.'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; + print 'piece_num.'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).''; print ''; print ''; if ($action == 'editjournal') { - print '
'; + print ''; print ''; print ''; print ''; - print $formaccounting->select_journal($book->code_journal,'code_journal',0,0,array(),1,1); + print $formaccounting->select_journal($object->code_journal,'code_journal',0,0,array(),1,1); print ''; print '
'; } else { - print $book->code_journal ; + print $object->code_journal ; } print ''; print ''; @@ -468,22 +467,22 @@ if ($action == 'create') // Ref document print ''; print ''; if ($action != 'editdocref') - print ''; + print ''; print '
'; - print $langs->trans('Docref'); + print $langs->trans('Piece'); print 'piece_num.'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'piece_num.'&mode='. $mode .'">'.img_edit($langs->transnoentitiesnoconv('Edit'),1).'
'; print ''; if ($action == 'editdocref') { - print '
'; + print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; print '
'; } else { - print $book->doc_ref ; + print $object->doc_ref ; } print ''; print ''; @@ -498,11 +497,11 @@ if ($action == 'create') print ''; // Doc type - if(! empty($book->doc_type)) + if(! empty($object->doc_type)) { print ''; print ''; - print ''; + print ''; print ''; } @@ -510,7 +509,7 @@ if ($action == 'create') print ''; print ''; print ''; print ''; @@ -519,7 +518,7 @@ if ($action == 'create') print ''; print ''; print ''; print ''; - if ($book->doc_type == 'customer_invoice') + if ($object->doc_type == 'customer_invoice') { $sqlmid = 'SELECT rowid as ref'; $sqlmid .= " FROM ".MAIN_DB_PREFIX."facture as fac"; - $sqlmid .= " WHERE fac.rowid=" . $book->fk_doc; + $sqlmid .= " WHERE fac.rowid=" . $object->fk_doc; dol_syslog("accountancy/bookkeeping/card.php::sqlmid=" . $sqlmid, LOG_DEBUG); $resultmid = $db->query($sqlmid); if ($resultmid) { @@ -556,31 +555,32 @@ if ($action == 'create') */ print "
' . $langs->trans("Doctype") . '' . $book->doc_type . '' . $object->doc_type . '
' . $langs->trans("DateCreation") . ''; - print $book->date_creation ? dol_print_date($book->date_creation, 'day') : ' '; + print $object->date_creation ? dol_print_date($object->date_creation, 'day') : ' '; print '
' . $langs->trans("Status") . ''; - if (empty($book->validated)) { + if (empty($object->validated)) { print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; @@ -536,11 +535,11 @@ if ($action == 'create') /* print '
' . $langs->trans("Control") . '
\n"; - print '
'; - print ''; + print ''; + + dol_fiche_end(); print '
'; print '
'; - $result = $book->fetchAllPerMvt($piece_num, $mode); + $result = $object->fetchAllPerMvt($piece_num, $mode); if ($result < 0) { - setEventMessages($book->error, $book->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } else { print load_fiche_titre($langs->trans("ListeMvts"), '', ''); - print '
'; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; + print ''; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; print '' . "\n"; print ""; - if (count($book->linesmvt) > 0) { + if (count($object->linesmvt) > 0) { $total_debit = 0; $total_credit = 0; @@ -597,7 +597,7 @@ if ($action == 'create') print "\n"; - foreach ($book->linesmvt as $line) { + foreach ($object->linesmvt as $line) { print ''; $total_debit += $line->debit; $total_credit += $line->credit; @@ -619,7 +619,7 @@ if ($action == 'create') } print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; print ''; print ''; } @@ -692,11 +692,11 @@ if ($action == 'create') print '
'; if ($total_debit == $total_credit) { - print ''.$langs->trans("ValidTransaction").''; + print ''.$langs->trans("ValidTransaction").''; } else { - print ''; + print ''; } print '   '; @@ -713,5 +713,6 @@ if ($action == 'create') } dol_fiche_end(); + llxFooter(); $db->close(); diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 57f52a4a77f..b0a91f7ce36 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -32,8 +32,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -// Langs -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("accountancy")); $action = GETPOST('action', 'alpha'); $search_mvt_num = GETPOST('search_mvt_num', 'int'); @@ -272,6 +272,7 @@ if (! empty($search_credit)) { $param .= '&search_credit=' . urlencode($search_credit); } + if ($action == 'delbookkeeping') { $import_key = GETPOST('importkey', 'alpha'); @@ -437,10 +438,12 @@ else $button.= $langs->trans("ExportList"); $button.= ''; -$groupby = ' ' . $langs->trans("GroupByAccountAccounting") . ''; -$addbutton = '' . $langs->trans("NewAccountingMvt") . ''; +$groupby = ' ' . $langs->trans("GroupByAccountAccounting") . ''; +$newcardbutton = '' . $langs->trans("NewAccountingMvt").''; +$newcardbutton.= ''; +$newcardbutton.= ''; -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $button, $result, $nbtotalofrecords, 'title_accountancy', 0, $groupby.$addbutton, '', $limit); +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $button, $result, $nbtotalofrecords, 'title_accountancy', 0, $groupby.$newcardbutton, '', $limit); $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields @@ -701,7 +704,7 @@ if ($num > 0) } // Action column - print '
'; @@ -739,7 +742,7 @@ print ''; // TODO Replace this with mass delete action print ''; diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index c450fb5bb63..80a4f0db5e8 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -1,8 +1,8 @@ - * Copyright (C) 2013-2016 Olivier Geffroy - * Copyright (C) 2013-2016 Florian Henry - * Copyright (C) 2013-2017 Alexandre Spangaro +/* Copyright (C) 2016 Neil Orley + * Copyright (C) 2013-2016 Olivier Geffroy + * Copyright (C) 2013-2016 Florian Henry + * Copyright (C) 2013-2018 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,35 +26,39 @@ require '../../main.inc.php'; -// Class require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -// Langs -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("accountancy")); $page = GETPOST("page"); $sortorder = GETPOST("sortorder"); $sortfield = GETPOST("sortfield"); $action = GETPOST('action', 'alpha'); -$search_date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); -$search_date_end = dol_mktime(0, 0, 0, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int')); +$search_date_start = dol_mktime(0, 0, 0, GETPOST('search_date_startmonth', 'int'), GETPOST('search_date_startday', 'int'), GETPOST('search_date_startyear', 'int')); +$search_date_end = dol_mktime(0, 0, 0, GETPOST('search_date_endmonth', 'int'), GETPOST('search_date_endday', 'int'), GETPOST('search_date_endyear', 'int')); $search_doc_date = dol_mktime(0, 0, 0, GETPOST('doc_datemonth', 'int'), GETPOST('doc_dateday', 'int'), GETPOST('doc_dateyear', 'int')); - - $search_accountancy_code = GETPOST("search_accountancy_code"); $search_accountancy_code_start = GETPOST('search_accountancy_code_start', 'alpha'); if ($search_accountancy_code_start == - 1) { $search_accountancy_code_start = ''; } -$search_label_account = GETPOST('search_label_account', 'alpha'); -$search_mvt_label = GETPOST('search_mvt_label', 'alpha'); +$search_accountancy_code_end = GETPOST('search_accountancy_code_end', 'alpha'); +if ($search_accountancy_code_end == - 1) { + $search_accountancy_code_end = ''; +} +$search_doc_ref = GETPOST('search_doc_ref', 'alpha'); +$search_label_operation = GETPOST('search_label_operation', 'alpha'); $search_direction = GETPOST('search_direction', 'alpha'); $search_ledger_code = GETPOST('search_ledger_code', 'alpha'); +$search_debit = GETPOST('search_debit', 'alpha'); +$search_credit = GETPOST('search_credit', 'alpha'); // Load variable for pagination $limit = GETPOST('limit','int')?GETPOST('limit', 'int'):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); @@ -96,63 +100,86 @@ if (empty($search_date_start) && empty($search_date_end)) { $object = new BookKeeping($db); - -$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_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 (! GETPOST('button_removefilter_x','alpha') && ! GETPOST('button_removefilter.x','alpha') && ! GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers -{ - if (! empty($search_accountancy_code_start)) { - $filter['t.numero_compte'] = $search_accountancy_code_start; - $options .= '&search_accountancy_code_start=' . urlencode($search_accountancy_code_start); - } - if (! empty($search_label_account)) { - $filter['t.label_operation'] = $search_label_account; - $options .= '&search_label_account=' . urlencode($search_label_account); - } - if (! empty($search_mvt_label)) { - $filter['t.label_operation'] = $search_mvt_label; - $options .= '&search_mvt_label=' . urlencode($search_mvt_label); - } - if (! empty($search_direction)) { - $filter['t.sens'] = $search_direction; - $options .= '&search_direction=' . urlencode($search_direction); - } - if (! empty($search_ledger_code)) { - $filter['t.code_journal'] = $search_ledger_code; - $options .= '&search_ledger_code=' . urlencode($search_ledger_code); - } -} - - /* * Action */ - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { $search_doc_date = ''; $search_accountancy_code = ''; $search_accountancy_code_start = ''; - $search_label_account = ''; - $search_mvt_label = ''; + $search_accountancy_code_end = ''; + $search_label_account = ''; + $search_doc_ref = ''; + $search_label_operation = ''; $search_direction = ''; $search_ledger_code = ''; + $search_date_start=''; + $search_date_end=''; + $search_date_startyear=''; + $search_date_startmonth=''; + $search_date_startday=''; + $search_date_endyear=''; + $search_date_endmonth=''; + $search_date_endday=''; + $search_debit = ''; + $search_credit = ''; } +// Must be after the remove filter action, before the export. +$param = ''; +$filter = array (); + +if (! empty($search_date_start)) { + $filter['t.doc_date>='] = $search_date_start; + $param .= '&search_date_startmonth=' . GETPOST('search_date_startmonth', 'int') . '&search_date_startday=' . GETPOST('search_date_startday', 'int') . '&search_date_startyear=' . GETPOST('search_date_startyear', 'int'); +} +if (! empty($search_date_end)) { + $filter['t.doc_date<='] = $search_date_end; + $param .= '&search_date_endmonth=' . GETPOST('search_date_endmonth', 'int') . '&search_date_endday=' . GETPOST('search_date_endday', 'int') . '&search_date_endyear=' . GETPOST('search_date_endyear', 'int'); +} +if (! empty($search_doc_date)) { + $filter['t.doc_date'] = $search_doc_date; + $param .= '&doc_datemonth=' . GETPOST('doc_datemonth', 'int') . '&doc_dateday=' . GETPOST('doc_dateday', 'int') . '&doc_dateyear=' . GETPOST('doc_dateyear', 'int'); +} +if (! empty($search_accountancy_code_start)) { + $filter['t.numero_compte>='] = $search_accountancy_code_start; + $param .= '&search_accountancy_code_start=' . urlencode($search_accountancy_code_start); +} +if (! empty($search_accountancy_code_end)) { + $filter['t.numero_compte<='] = $search_accountancy_code_end; + $param .= '&search_accountancy_code_end=' . urlencode($search_accountancy_code_end); +} +if (! empty($search_label_account)) { + $filter['t.label_compte'] = $search_label_account; + $param .= '&search_label_compte=' . urlencode($search_label_account); +} +if (! empty($search_doc_ref)) { + $filter['t.doc_ref'] = $search_doc_ref; + $param .= '&search_doc_ref=' . urlencode($search_doc_ref); +} +if (! empty($search_label_operation)) { + $filter['t.label_operation'] = $search_label_operation; + $param .= '&search_label_operation=' . urlencode($search_label_operation); +} +if (! empty($search_direction)) { + $filter['t.sens'] = $search_direction; + $param .= '&search_direction=' . urlencode($search_direction); +} +if (! empty($search_ledger_code)) { + $filter['t.code_journal'] = $search_ledger_code; + $param .= '&search_ledger_code=' . urlencode($search_ledger_code); +} +if (! empty($search_debit)) { + $filter['t.debit'] = $search_debit; + $param .= '&search_debit=' . urlencode($search_debit); +} +if (! empty($search_credit)) { + $filter['t.credit'] = $search_credit; + $param .= '&search_credit=' . urlencode($search_credit); +} + + if ($action == 'delmouvconfirm') { $mvt_num = GETPOST('mvt_num', 'int'); @@ -176,7 +203,7 @@ $formaccounting = new FormAccounting($db); $formother = new FormOther($db); $form = new Form($db); -$title_page = $langs->trans("Bookkeeping") . ' ' . strtolower($langs->trans("By")) . ' ' . $langs->trans("AccountAccounting"); +$title_page = $langs->trans("Bookkeeping") . ' ' . strtolower($langs->trans("By")) . ' ' . strtolower($langs->trans("AccountAccounting")); llxHeader('', $title_page); @@ -226,41 +253,50 @@ if ($action == 'delbookkeepingyear') { } -$param=$options; - print ''; -$viewflat = ' ' . $langs->trans("ViewFlatList") . ''; -$addbutton = '' . $langs->trans("NewAccountingMvt") . ''; +$viewflat = ' ' . $langs->trans("ViewFlatList") . ''; +$newcardbutton = '' . $langs->trans("NewAccountingMvt").''; +$newcardbutton.= ''; +$newcardbutton.= ''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); -print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $viewflat.$addbutton, '', $limit); +print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $viewflat.$newcardbutton, '', $limit); // Reverse sort order if ( preg_match('/^asc/i', $sortorder) ) - $sortorder = "asc"; + $sortorder = "asc"; else - $sortorder = "desc"; + $sortorder = "desc"; print '
'; @@ -656,7 +656,7 @@ if ($action == 'create') if ($total_debit != $total_credit) { - setEventMessages(null, array($langs->trans('MvtNotCorrectlyBalanced', $total_credit, $total_debit)), 'warnings'); + setEventMessages(null, array($langs->trans('MvtNotCorrectlyBalanced', $total_debit, $total_credit)), 'warnings'); } if ($action == "" || $action == 'add') { @@ -677,9 +677,9 @@ if ($action == 'create') } print '
'; + print ''; print '' . img_edit() . ' '; print '' . img_delete() . ''; print '
'; print ''; -print ''; +print ''; print ''; print ''; -print ''; -print ''; -print ''; -print ''; -print ''; +print ''; +print ''; +print ''; +print ''; +print ''; print ''; print ''; print_liste_field_titre("AccountAccountingShort", $_SERVER['PHP_SELF']); -print_liste_field_titre("TransactionNumShort", $_SERVER['PHP_SELF'], "t.piece_num", "", $options, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre("Docdate", $_SERVER['PHP_SELF'], "t.doc_date", "", $options, 'align="center"', $sortfield, $sortorder); -print_liste_field_titre("Docref", $_SERVER['PHP_SELF'], "t.doc_ref", "", $options, "", $sortfield, $sortorder); +print_liste_field_titre("TransactionNumShort", $_SERVER['PHP_SELF'], "t.piece_num", "", $param, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre("Docdate", $_SERVER['PHP_SELF'], "t.doc_date", "", $param, 'align="center"', $sortfield, $sortorder); +print_liste_field_titre("Piece", $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("Label"); -print_liste_field_titre("Debit", $_SERVER['PHP_SELF'], "t.debit", "", $options, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre("Credit", $_SERVER['PHP_SELF'], "t.credit", "", $options, 'align="right"', $sortfield, $sortorder); -print_liste_field_titre("Codejournal", $_SERVER['PHP_SELF'], "t.code_journal", "", $options, 'align="center"', $sortfield, $sortorder); -print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $options, "", 'width="60" align="center"', $sortfield, $sortorder); +print_liste_field_titre("Debit", $_SERVER['PHP_SELF'], "t.debit", "", $param, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre("Credit", $_SERVER['PHP_SELF'], "t.credit", "", $param, 'align="right"', $sortfield, $sortorder); +print_liste_field_titre("Codejournal", $_SERVER['PHP_SELF'], "t.code_journal", "", $param, 'align="center"', $sortfield, $sortorder); +print_liste_field_titre('', $_SERVER["PHP_SELF"], "", $param, "", 'width="60" align="center"', $sortfield, $sortorder); print "\n"; print ''; @@ -295,34 +331,34 @@ while ($i < min($num, $limit)) $total_debit += $line->debit; $total_credit += $line->credit; - $accountg = length_accountg($line->numero_compte); + $accountg = length_accountg($line->numero_compte); //if (empty($accountg)) $accountg = '-'; // Is it a break ? - if ($accountg != $displayed_account_number || ! isset($displayed_account_number)) { + 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 "\n"; - print ''; - } + // Affiche un Sous-Total par compte comptable + if (isset($displayed_account_number)) { + print ''; + print "\n"; + print "\n"; + print ''; + } - // Show the break account - $colspan = 9; - print ""; - print ''; - 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; - } + $displayed_account_number = $accountg; + //if (empty($displayed_account_number)) $displayed_account_number='-'; + $sous_total_debit = 0; + $sous_total_credit = 0; + } print ''; print ''; @@ -331,22 +367,27 @@ while ($i < min($num, $limit)) // TODO Add a link according to doc_type and fk_doc print ''; + print ''; - // Affiche un lien vers la facture client/fournisseur - $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref); - print strlen(length_accounta($line->subledger_account)) == 0 ? '' : ''; + // Affiche un lien vers la facture client/fournisseur + $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref); + print strlen(length_accounta($line->subledger_account)) == 0 ? '' : ''; print ''; print ''; - print ''; + + $accountingjournal = new AccountingJournal($db); + $result = $accountingjournal->fetch('',$line->code_journal); + $journaltoshow = (($result > 0)?$accountingjournal->getNomUrl(0,0,0,'',0) : $line->code_journal); + print ''; + print ''; print "\n"; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php index 550ea1d933a..9bf287bf3c9 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage.php @@ -33,6 +33,9 @@ require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; +// Load translation files required by the page +$langs->loadLangs(array("compta")); + $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); @@ -141,7 +144,6 @@ if ($object->check_codeclient() != 0) print ''; print ''; -$langs->load('compta'); print ''; print ''; print ''; -$langs->load('compta'); print ''; print ''; } -else { +else +{ print '\n"; clearstatcache(); -$var=true; foreach ($dirmodels as $reldir) { foreach (array('','/doc') as $valdir) @@ -507,7 +501,6 @@ foreach ($dirmodels as $reldir) if ($modulequalified) { - $var = !$var; print ''; @@ -2264,7 +2300,7 @@ if ($action == 'create') $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1); // Form to add new line - if ($object->statut == Propal::STATUS_DRAFT && $user->rights->propal->creer) + if ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines') { if ($action != 'editline') { @@ -2299,8 +2335,7 @@ if ($action == 'create') // Validate if ($object->statut == Propal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) + if ($usercanvalidate) { print ''; } @@ -2313,34 +2348,34 @@ if ($action == 'create') print ''; }*/ // Edit - if ($object->statut == Propal::STATUS_VALIDATED && $user->rights->propal->creer) { + if ($object->statut == Propal::STATUS_VALIDATED && $usercancreate) { print ''; } // ReOpen - if (($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) && $user->rights->propal->cloturer) { + if (($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) && $usercanclose) { print ''; } // Send if ($object->statut == Propal::STATUS_VALIDATED || $object->statut == Propal::STATUS_SIGNED) { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->propal->propal_advance->send) { - print ''; + if ($usercansend) { + print ''; } else - print ''; + print ''; } // Create an order if (! empty($conf->commande->enabled) && $object->statut == Propal::STATUS_SIGNED) { - if ($user->rights->commande->creer) { + if ($usercancreateorder) { print ''; } } // Create an intervention if (! empty($conf->service->enabled) && ! empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) { - if ($user->rights->ficheinter->creer) { + if ($usercancreateintervention) { $langs->load("interventions"); print ''; } @@ -2350,7 +2385,7 @@ if ($action == 'create') if ($conf->contrat->enabled && $object->statut == Propal::STATUS_SIGNED) { $langs->load("contracts"); - if ($user->rights->contrat->creer) { + if ($usercancreatecontract) { print ''; } } @@ -2358,7 +2393,7 @@ if ($action == 'create') // Create an invoice and classify billed if ($object->statut == Propal::STATUS_SIGNED) { - if (! empty($conf->facture->enabled) && $user->rights->facture->creer) + if (! empty($conf->facture->enabled) && $usercancreateinvoice) { print ''; } @@ -2371,18 +2406,18 @@ if ($action == 'create') } // Set accepted/refused - if ($object->statut == Propal::STATUS_VALIDATED && $user->rights->propal->cloturer) { + if ($object->statut == Propal::STATUS_VALIDATED && $usercanclose) { print ''; } // Clone - if ($user->rights->propal->creer) { + if ($usercancreate) { print ''; } // Delete - if ($user->rights->propal->supprimer) { + if ($usercandelete) { print ''; } @@ -2403,10 +2438,10 @@ if ($action == 'create') * Documents generes */ $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->propal->dir_output . "/" . dol_sanitizeFileName($object->ref); + $filedir = $conf->propal->multidir_output[$object->entity] . "/" . dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->propal->lire; - $delallowed = $user->rights->propal->creer; + $genallowed = $usercanread; + $delallowed = $usercancreate; print $formfile->showdocuments('propal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang, '', $object); @@ -2444,7 +2479,7 @@ if ($action == 'create') // Presend form $modelmail='propal_send'; $defaulttopic='SendPropalRef'; - $diroutput = $conf->propal->dir_output; + $diroutput = $conf->propal->multidir_output[$object->entity]; $trackid = 'pro'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 63b26373f60..39857d88365 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -77,6 +77,9 @@ class Proposals extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + // Add external contacts ids + $this->propal->contacts_ids = $this->propal->liste_contact(-1,'external',1); + $this->propal->fetchObjectLinked(); return $this->_cleanObjectDatas($this->propal); } @@ -156,6 +159,8 @@ class Proposals extends DolibarrApi $obj = $db->fetch_object($result); $proposal_static = new Propal($db); if($proposal_static->fetch($obj->rowid)) { + // Add external contacts ids + $proposal_static->contacts_ids = $proposal_static->liste_contact(-1,'external',1); $obj_ret[] = $this->_cleanObjectDatas($proposal_static); } $i++; @@ -176,7 +181,7 @@ class Proposals extends DolibarrApi * @param array $request_data Request data * @return int ID of proposal */ - function post($request_data = NULL) + function post($request_data = null) { if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401, "Insuffisant rights"); @@ -241,7 +246,7 @@ class Proposals extends DolibarrApi * * @return int */ - function postLine($id, $request_data = NULL) + function postLine($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); @@ -307,7 +312,7 @@ class Proposals extends DolibarrApi * * @return object */ - function putLine($id, $lineid, $request_data = NULL) + function putLine($id, $lineid, $request_data = null) { if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); @@ -410,7 +415,7 @@ class Proposals extends DolibarrApi * * @return int */ - function put($id, $request_data = NULL) { + function put($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } @@ -708,7 +713,7 @@ class Proposals extends DolibarrApi $object = parent::_cleanObjectDatas($object); - unset($object->note); + unset($object->note); unset($object->name); unset($object->lastname); unset($object->firstname); diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index a9782d21dac..cf7610a218e 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -12,6 +12,7 @@ * Copyright (C) 2012 Cedric Salvador * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2015 Marcos García + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -142,9 +143,9 @@ class Propal extends CommonObject public $cond_reglement_code; public $mode_reglement_code; - public $remise; - public $remise_percent; - public $remise_absolue; + public $remise = 0; + public $remise_percent = 0; + public $remise_absolue = 0; public $fk_address; public $address_type; public $address; @@ -198,6 +199,7 @@ class Propal extends CommonObject */ const STATUS_BILLED = 4; // Todo rename into STATUS_CLOSE ? + /** * Constructor * @@ -210,26 +212,13 @@ class Propal extends CommonObject global $conf,$langs; $this->db = $db; + $this->socid = $socid; $this->id = $propalid; + $this->products = array(); - $this->remise = 0; - $this->remise_percent = 0; - $this->remise_absolue = 0; $this->duree_validite=$conf->global->PROPALE_VALIDITY_DURATION; - - $langs->load("propal"); - $this->labelstatut[0]=(! empty($conf->global->PROPAL_STATUS_DRAFT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFT_LABEL : $langs->trans("PropalStatusDraft")); - $this->labelstatut[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATED_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATED_LABEL : $langs->trans("PropalStatusValidated")); - $this->labelstatut[2]=(! empty($conf->global->PROPAL_STATUS_SIGNED_LABEL) ? $conf->global->PROPAL_STATUS_SIGNED_LABEL : $langs->trans("PropalStatusSigned")); - $this->labelstatut[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNED_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNED_LABEL : $langs->trans("PropalStatusNotSigned")); - $this->labelstatut[4]=(! empty($conf->global->PROPAL_STATUS_BILLED_LABEL) ? $conf->global->PROPAL_STATUS_BILLED_LABEL : $langs->trans("PropalStatusBilled")); - $this->labelstatut_short[0]=(! empty($conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL) ? $conf->global->PROPAL_STATUS_DRAFTSHORT_LABEL : $langs->trans("PropalStatusDraftShort")); - $this->labelstatut_short[1]=(! empty($conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_VALIDATEDSHORT_LABEL : $langs->trans("Opened")); - $this->labelstatut_short[2]=(! empty($conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_SIGNEDSHORT_LABEL : $langs->trans("PropalStatusSignedShort")); - $this->labelstatut_short[3]=(! empty($conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_NOTSIGNEDSHORT_LABEL : $langs->trans("PropalStatusNotSignedShort")); - $this->labelstatut_short[4]=(! empty($conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL) ? $conf->global->PROPAL_STATUS_BILLEDSHORT_LABEL : $langs->trans("PropalStatusBilledShort")); } @@ -1116,12 +1105,8 @@ class Propal extends CommonObject { $action='update'; - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('propaldao')); - $parameters=array('socid'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) + // Actions on extra fields + if (! $error) { if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { @@ -1132,9 +1117,8 @@ class Propal extends CommonObject } } } - else if ($reshook < 0) $error++; - if (! $notrigger) + if (! $error && ! $notrigger) { // Call trigger $result=$this->call_trigger('PROPAL_CREATE',$user); @@ -1212,7 +1196,7 @@ class Propal extends CommonObject // get extrafields so they will be clone foreach($this->lines as $line) - $line->fetch_optionals($line->rowid); + $line->fetch_optionals(); // Load dest object $clonedObj = clone $this; @@ -1291,11 +1275,6 @@ class Propal extends CommonObject $reshook=$hookmanager->executeHooks('createFrom',$parameters,$clonedObj,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; } - - // Call trigger - $result=$clonedObj->call_trigger('PROPAL_CLONE',$user); - if ($result < 0) { $error++; } - // End call triggers } unset($this->context['createfromclone']); @@ -1350,16 +1329,19 @@ class Propal extends CommonObject $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; $sql.= ", cr.code as cond_reglement_code, cr.libelle as cond_reglement, cr.libelle_facture as cond_reglement_libelle_doc"; $sql.= ", cp.code as mode_reglement_code, cp.libelle as mode_reglement"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_propalst as c, ".MAIN_DB_PREFIX."propal as p"; + $sql.= " FROM ".MAIN_DB_PREFIX."propal as p"; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_propalst as c ON p.fk_statut = c.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as cp ON p.fk_mode_reglement = cp.id AND cp.entity IN ('.getEntity('c_paiement').')'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON p.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON p.fk_availability = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON p.fk_input_reason = dr.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON p.fk_incoterms = i.rowid'; - $sql.= " WHERE p.fk_statut = c.id"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; - if ($ref) $sql.= " AND p.ref='".$ref."'"; - else $sql.= " AND p.rowid=".$rowid; + + if ($ref) { + $sql.= " WHERE p.entity IN (".getEntity('propal').")"; // Dont't use entity if you use rowid + $sql.= " AND p.ref='".$this->db->escape($ref)."'"; + } + else $sql.= " WHERE p.rowid=".$rowid; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -1444,12 +1426,9 @@ class Propal extends CommonObject $this->brouillon = 1; } - // Retreive all extrafield for invoice + // Retreive all extrafield // fetch optionals attributes and labels - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + $this->fetch_optionals(); $this->db->free($resql); @@ -1486,6 +1465,8 @@ class Propal extends CommonObject */ function update(User $user, $notrigger=0) { + global $conf; + $error=0; // Clean parameters @@ -1534,17 +1515,23 @@ class Propal extends CommonObject $error++; $this->errors[]="Error ".$this->db->lasterror(); } - if (! $error) + if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) { - if (! $notrigger) + $result=$this->insertExtraFields(); + if ($result < 0) { - // Call trigger - $result=$this->call_trigger('PROPAL_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers + $error++; } } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('PROPAL_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } + // Commit or rollback if ($error) { @@ -1670,7 +1657,7 @@ class Propal extends CommonObject $this->db->free($result); - return 1; + return $num; } else { @@ -1761,8 +1748,8 @@ class Propal extends CommonObject // to not lose the linked files $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); - $dirsource = $conf->propal->dir_output.'/'.$oldref; - $dirdest = $conf->propal->dir_output.'/'.$newref; + $dirsource = $conf->propal->multidir_output[$this->entity].'/'.$oldref; + $dirdest = $conf->propal->multidir_output[$this->entity].'/'.$newref; if (file_exists($dirsource)) { @@ -1771,7 +1758,7 @@ class Propal extends CommonObject { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref - $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + $listoffiles=dol_dir_list($dirdest, 'files', 1, '^'.preg_quote($oldref,'/')); foreach($listoffiles as $fileentry) { $dirsource=$fileentry['name']; @@ -2540,21 +2527,6 @@ class Propal extends CommonObject } } - /** - * Class invoiced the Propal - * - * @return int <0 si ko, >0 si ok - * @deprecated - * @see classifyBilled() - */ - function classer_facturee() - { - global $user; - dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING); - - return $this->classifyBilled($user); - } - /** * Set draft status * @@ -2827,9 +2799,9 @@ class Propal extends CommonObject { // We remove directory $ref = dol_sanitizeFileName($this->ref); - if ($conf->propal->dir_output && !empty($this->ref)) + if ($conf->propal->multidir_output[$this->entity] && !empty($this->ref)) { - $dir = $conf->propal->dir_output . "/" . $ref ; + $dir = $conf->propal->multidir_output[$this->entity] . "/" . $ref ; $file = $dir . "/" . $ref . ".pdf"; if (file_exists($file)) { @@ -3123,10 +3095,26 @@ class Propal extends CommonObject * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto * @return string Label */ - function LibStatut($statut,$mode=1) + function LibStatut($statut,$mode=1) { - global $langs; - $langs->load("propal"); + global $conf; + + // Init/load array of translation of status + if (empty($this->labelstatut) || empty($this->labelstatut_short)) + { + global $langs; + $langs->load("propal"); + $this->labelstatut[0]=$langs->trans("PropalStatusDraft"); + $this->labelstatut[1]=$langs->trans("PropalStatusValidated"); + $this->labelstatut[2]=$langs->trans("PropalStatusSigned"); + $this->labelstatut[3]=$langs->trans("PropalStatusNotSigned"); + $this->labelstatut[4]=$langs->trans("PropalStatusBilled"); + $this->labelstatut_short[0]=$langs->trans("PropalStatusDraftShort"); + $this->labelstatut_short[1]=$langs->trans("Opened"); + $this->labelstatut_short[2]=$langs->trans("PropalStatusSignedShort"); + $this->labelstatut_short[3]=$langs->trans("PropalStatusNotSignedShort"); + $this->labelstatut_short[4]=$langs->trans("PropalStatusBilledShort"); + } $statuttrans=''; if ($statut==self::STATUS_DRAFT) $statuttrans='statut0'; @@ -3372,12 +3360,19 @@ class Propal extends CommonObject global $conf,$langs; $langs->load("propal"); - if (! empty($conf->global->PROPALE_ADDON)) + $constant = 'PROPALE_ADDON_'.$this->entity; + + if (! empty($conf->global->$constant)) { + $classname = $conf->global->$constant; // for multicompany proposal sharing + } else { + $classname = $conf->global->PROPALE_ADDON; + } + + if (! empty($classname)) { $mybool=false; - $file = $conf->global->PROPALE_ADDON.".php"; - $classname = $conf->global->PROPALE_ADDON; + $file = $classname.".php"; // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); @@ -3605,9 +3600,10 @@ class Propal extends CommonObject * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information * @return int 0 if KO, 1 if OK */ - public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null) { global $conf,$langs; @@ -3626,7 +3622,7 @@ class Propal extends CommonObject $modelpath = "core/modules/propale/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref,$moreparams); } /** @@ -3846,6 +3842,8 @@ class PropaleLigne extends CommonObjectLine $this->multicurrency_total_tva = $objp->multicurrency_total_tva; $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc; + $this->fetch_optionals(); + $this->db->free($result); return 1; @@ -3980,7 +3978,7 @@ class PropaleLigne extends CommonObjectLine } } - if (! $notrigger) + if (! $error && ! $notrigger) { // Call trigger $result=$this->call_trigger('LINEPROPAL_INSERT',$user); @@ -4163,7 +4161,7 @@ class PropaleLigne extends CommonObjectLine } } - if (! $notrigger) + if (! $error && ! $notrigger) { // Call trigger $result=$this->call_trigger('LINEPROPAL_UPDATE',$user); diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index 01e851769a7..5e21f493c64 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -32,10 +32,8 @@ 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.'/projet/class/project.class.php'; -$langs->load("facture"); -$langs->load("orders"); -$langs->load("sendings"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('facture', 'orders', 'sendings', 'companies')); $id=GETPOST('id','int'); $ref= GETPOST('ref','alpha'); @@ -164,7 +162,7 @@ if ($object->id > 0) $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); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php index ba373c78f44..1c8d494214d 100644 --- a/htdocs/comm/propal/document.php +++ b/htdocs/comm/propal/document.php @@ -36,9 +36,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load('compta'); -$langs->load('other'); -$langs->load('companies'); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'other', 'companies')); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm','alpha'); @@ -75,7 +74,7 @@ $object->fetch($id,$ref); if ($object->id > 0) { $object->fetch_thirdparty(); - $upload_dir = $conf->propal->dir_output.'/'.dol_sanitizeFileName($object->ref); + $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; } @@ -90,7 +89,7 @@ $form = new Form($db); if ($object->id > 0) { - $upload_dir = $conf->propal->dir_output.'/'.dol_sanitizeFileName($object->ref); + $upload_dir = $conf->propal->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); $head = propal_prepare_head($object); dol_fiche_head($head, 'document', $langs->trans('Proposal'), -1, 'propal'); @@ -114,7 +113,7 @@ if ($object->id > 0) $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); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { @@ -160,7 +159,7 @@ if ($object->id > 0) // Files infos print '
'; - print ''; + print ''; print "
' . $object->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, '') . ''; +print '
'; +print $langs->trans('From').' '; +print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array (), 1, 1, 'maxwidth200'); +print '
'; +print '
'; +print $langs->trans('to').' '; +print $formaccounting->select_account($search_accountancy_code_end, 'search_accountancy_code_end', 1, array (), 1, 1, 'maxwidth200'); +print '
'; +print '
'; print $langs->trans('From') . ': '; -print $form->select_date($search_date_start, 'date_start', 0, 0, 1); +print $form->select_date($search_date_start, 'search_date_start', 0, 0, 1); print '
'; print $langs->trans('to') . ': '; -print $form->select_date($search_date_end, 'date_end', 0, 0, 1); +print $form->select_date($search_date_end, 'search_date_end', 0, 0, 1); print '
  '; $searchpicto=$form->showFilterAndCheckAddButtons(0); print $searchpicto; @@ -268,14 +304,14 @@ 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 '
'; + 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 '
 '; - //if ($line->doc_type == 'supplier_invoice') - //if ($line->doc_type == 'customer_invoice') + //if ($line->doc_type == 'supplier_invoice') + //if ($line->doc_type == 'customer_invoice') print $line->doc_ref; - print '' . $line->label_operation . '' . $line->label_operation . '
(' . length_accounta($line->subledger_account) . ')
' . $line->label_operation . '' . $line->label_operation . '
(' . length_accounta($line->subledger_account) . ')
' . ($line->debit ? price($line->debit) :''). '' . ($line->credit ? price($line->credit) : '') . '' . $line->code_journal . '' . $journaltoshow . ''; print '' . img_edit() . ' '; - print '' . img_delete() . ''; + print '' . img_delete() . ''; print '
'; print $form->editfieldkey("CustomerAccountancyCode", 'customeraccountancycode', $object->code_compta, $object, $user->rights->societe->creer); diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php index 35bdcfa23fe..cf278c26903 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettrage_supplier.php @@ -35,6 +35,9 @@ require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; +// Load translation files required by the page +$langs->loadLangs(array("compta")); + $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); @@ -157,7 +160,6 @@ if ($object->check_codefournisseur() != 0) print '
'; print $form->editfieldkey("SupplierAccountancyCode", 'supplieraccountancycode', $object->code_compta_fournisseur, $object, $user->rights->societe->creer); diff --git a/htdocs/accountancy/class/accountancycategory.class.php b/htdocs/accountancy/class/accountancycategory.class.php index 3c28d4b6932..27254ef31d1 100644 --- a/htdocs/accountancy/class/accountancycategory.class.php +++ b/htdocs/accountancy/class/accountancycategory.class.php @@ -28,40 +28,345 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; /** * Class to manage categories of an accounting account */ -class AccountancyCategory +class AccountancyCategory // extends CommonObject { - private $db; - public $error; - public $errors = array (); - public $element = 'accounting_category'; - public $table_element = 'c_accounting_category'; + public $db; //!< To store db handler + public $error; //!< To return error code (or message) + public $errors=array(); //!< To return several error codes (or messages) + public $element='c_accounting_category'; //!< Id that identify managed objects + public $table_element='c_accounting_category'; //!< Name of table without prefix where object is stored + public $id; + public $code; + public $label; + public $range_account; + public $sens; + public $category_type; + public $formula; + public $position; + public $fk_country; + public $active; + public $lines_cptbk; public $lines_display; public $sdc; + + /** - * Constructor + * Constructor * - * @param DoliDB $db Database handler + * @param DoliDb $db Database handler */ - public function __construct($db) { + function __construct($db) + { $this->db = $db; } + + /** + * Create object into database + * + * @param User $user User that create + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + function create($user, $notrigger=0) + { + global $conf, $langs; + $error=0; + + // Clean parameters + if (isset($this->code)) $this->code=trim($this->code); + if (isset($this->label)) $this->label=trim($this->label); + if (isset($this->range_account)) $this->range_account=trim($this->range_account); + if (isset($this->sens)) $this->sens=trim($this->sens); + if (isset($this->category_type)) $this->category_type=trim($this->category_type); + if (isset($this->formula)) $this->formula=trim($this->formula); + if (isset($this->position)) $this->position=trim($this->position); + if (isset($this->fk_country)) $this->fk_country=trim($this->fk_country); + if (isset($this->active)) $this->active=trim($this->active); + + // Check parameters + // Put here code to add control on parameters values + + // Insert request + $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_accounting_category("; + if ($this->rowid > 0) $sql.= "rowid,"; + $sql.= "code,"; + $sql.= "label,"; + $sql.= "range_account,"; + $sql.= "sens,"; + $sql.= "category_type,"; + $sql.= "formula,"; + $sql.= "position,"; + $sql.= "fk_country,"; + $sql.= "active"; + $sql.= ") VALUES ("; + if ($this->rowid > 0) $sql.= " ".$this->rowid.","; + $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; + $sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").","; + $sql.= " ".(! isset($this->range_account)?'NULL':"'".$this->db->escape($this->range_account)."'").","; + $sql.= " ".(! isset($this->sens)?'NULL':"'".$this->db->escape($this->sens)."'").","; + $sql.= " ".(! isset($this->category_type)?'NULL':"'".$this->db->escape($this->category_type)."'").","; + $sql.= " ".(! isset($this->formula)?'NULL':"'".$this->db->escape($this->formula)."'").","; + $sql.= " ".(! isset($this->position)?'NULL':$this->db->escape($this->position)).","; + $sql.= " ".(! isset($this->fk_country)?'NULL':$this->db->escape($this->fk_country)).","; + $sql.= " ".(! isset($this->active)?'NULL':$this->db->escape($this->active)); + $sql.= ")"; + + $this->db->begin(); + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_accounting_category"); + + if (! $notrigger) + { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return $this->id; + } + } + + + /** + * Load object in memory from database + * + * @param int $id Id object + * @param string $code Code + * @param string $label Label + * @return int <0 if KO, >0 if OK + */ + function fetch($id,$code='',$label='') + { + global $langs; + $sql = "SELECT"; + $sql.= " t.rowid,"; + $sql.= " t.code,"; + $sql.= " t.label,"; + $sql.= " t.range_account,"; + $sql.= " t.sens,"; + $sql.= " t.category_type,"; + $sql.= " t.formula,"; + $sql.= " t.position,"; + $sql.= " t.fk_country,"; + $sql.= " t.active"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as t"; + if ($id) $sql.= " WHERE t.rowid = ".$id; + elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'"; + elseif ($label) $sql.= " WHERE t.label = '".$this->db->escape($label)."'"; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->code = $obj->code; + $this->label = $obj->label; + $this->range_account = $obj->range_account; + $this->sens = $obj->sens; + $this->category_type = $obj->category_type; + $this->formula = $obj->formula; + $this->position = $obj->position; + $this->fk_country = $obj->fk_country; + $this->active = $obj->active; + } + $this->db->free($resql); + + return 1; + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update object into database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function update($user=null, $notrigger=0) + { + global $conf, $langs; + $error=0; + + // Clean parameters + if (isset($this->code)) $this->code=trim($this->code); + if (isset($this->label)) $this->label=trim($this->label); + if (isset($this->range_account)) $this->range_account=trim($this->range_account); + if (isset($this->sens)) $this->sens=trim($this->sens); + if (isset($this->category_type)) $this->category_type=trim($this->category_type); + if (isset($this->formula)) $this->formula=trim($this->formula); + if (isset($this->position)) $this->position=trim($this->position); + if (isset($this->fk_country)) $this->fk_country=trim($this->fk_country); + if (isset($this->active)) $this->active=trim($this->active); + + + // Check parameters + // Put here code to add control on parameters values + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."c_accounting_category SET"; + $sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").","; + $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").","; + $sql.= " range_account=".(isset($this->range_account)?"'".$this->db->escape($this->range_account)."'":"null").","; + $sql.= " sens=".(isset($this->sens)?$this->sens:"null").","; + $sql.= " category_type=".(isset($this->category_type)?$this->category_type:"null").","; + $sql.= " formula=".(isset($this->formula)?"'".$this->db->escape($this->formula)."'":"null").","; + $sql.= " position=".(isset($this->position)?$this->position:"null").","; + $sql.= " fk_country=".(isset($this->fk_country)?$this->fk_country:"null").","; + $sql.= " active=".(isset($this->active)?$this->active:"null").""; + $sql.= " WHERE rowid=".$this->id; + + $this->db->begin(); + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } + + + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function delete($user, $notrigger=0) + { + global $conf, $langs; + $error=0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_accounting_category"; + $sql.= " WHERE rowid=".$this->id; + + $this->db->begin(); + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action call a trigger. + + //// Call triggers + //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + //$interface=new Interfaces($this->db); + //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); + //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //// End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } + + /** * Function to select all accounting accounts from an accounting category * * @param int $id Id - * * @return int <0 if KO, 0 if not found, >0 if OK */ public function display($id) { + global $conf; $sql = "SELECT t.rowid, t.account_number, t.label"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as t"; $sql .= " WHERE t.fk_accounting_category = " . $id; + $sql .= " AND t.entity = " . $conf->entity; - $this->lines_display = array (); + $this->lines_display = array(); dol_syslog(__METHOD__ . " sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); @@ -97,13 +402,14 @@ class AccountancyCategory $sql .= " WHERE t.numero_compte NOT IN ("; $sql .= " SELECT t.account_number"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as t"; - $sql .= " WHERE t.fk_accounting_category = " . $id . ")"; + $sql .= " WHERE t.fk_accounting_category = " . $id . " AND t.entity = " . $conf->entity.")"; $sql .= " AND t.numero_compte IN ("; $sql .= " SELECT DISTINCT aa.account_number"; $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 = " . $conf->global->CHARTOFACCOUNTS; - $sql .= " AND aa.active = 1)"; + $sql .= " AND aa.active = 1"; + $sql .= " AND aa.entity = = " . $conf->entity . ")"; $sql .= " GROUP BY t.numero_compte, t.label_operation, t.doc_ref"; $sql .= " ORDER BY t.numero_compte"; @@ -145,6 +451,7 @@ class AccountancyCategory $sql .= " WHERE (aa.fk_accounting_category != ".$id." OR aa.fk_accounting_category IS NULL)"; $sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS; $sql .= " AND aa.active = 1"; + $sql .= " AND aa.entity = " . $conf->entity; $sql .= " GROUP BY aa.account_number, aa.label"; $sql .= " ORDER BY aa.account_number, aa.label"; @@ -189,6 +496,7 @@ class AccountancyCategory $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; $sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS; $sql .= " AND aa.active = 1"; + $sql .= " AND aa.entity = " . $conf->entity; $this->db->begin(); @@ -278,7 +586,7 @@ class AccountancyCategory */ public function getCatsCpts() { - global $mysoc; + global $mysoc,$conf; $sql = ""; @@ -292,8 +600,10 @@ class AccountancyCategory $sql .= " WHERE t.fk_accounting_category IN ( SELECT c.rowid "; $sql .= " FROM " . MAIN_DB_PREFIX . "c_accounting_category as c"; $sql .= " WHERE c.active = 1"; + $sql .= " AND c.entity = " . $conf->entity; $sql .= " AND (c.fk_country = ".$mysoc->country_id." OR c.fk_country = 0)"; $sql .= " AND cat.rowid = t.fk_accounting_category"; + $sql .= " AND t.entity = " . $conf->entity; $sql .= " ORDER BY cat.position ASC"; $resql = $this->db->query($sql); @@ -382,7 +692,7 @@ class AccountancyCategory */ public function getCats($categorytype=-1) { - global $db, $langs, $user, $mysoc; + global $db, $langs, $user, $mysoc, $conf; if (empty($mysoc->country_id)) { dol_print_error('', 'Call to select_accounting_account with mysoc country not yet defined'); @@ -392,6 +702,7 @@ class AccountancyCategory $sql = "SELECT c.rowid, c.code, c.label, c.formula, c.position, c.category_type"; $sql .= " FROM " . MAIN_DB_PREFIX . "c_accounting_category as c"; $sql .= " WHERE c.active = 1 "; + $sql .= " AND c.entity = " . $conf->entity; if ($categorytype >= 0) $sql.=" AND c.category_type = 1"; $sql .= " AND (c.fk_country = ".$mysoc->country_id." OR c.fk_country = 0)"; $sql .= " ORDER BY c.position ASC"; @@ -428,65 +739,6 @@ class AccountancyCategory } - // calcule - - /* I try to replace this with dol_eval() - - const PATTERN = '/(?:\-?\d+(?:\.?\d+)?[\+\-\*\/])+\-?\d+(?:\.?\d+)?/'; - - const PARENTHESIS_DEPTH = 10; - - public function calculate($input) - { - global $langs; - - if(strpos($input, '+') != null || strpos($input, '-') != null || strpos($input, '/') != null || strpos($input, '*') != null){ - // Remove white spaces and invalid math chars - $input = str_replace($langs->trans("ThousandSeparator"), '', $input); - $input = str_replace(',', '.', $input); - $input = preg_replace('[^0-9\.\+\-\*\/\(\)]', '', $input); - - // Calculate each of the parenthesis from the top - $i = 0; - while(strpos($input, '(') || strpos($input, ')')){ - $input = preg_replace_callback('/\(([^\(\)]+)\)/', 'self::callback', $input); - - $i++; - if($i > self::PARENTHESIS_DEPTH){ - break; - } - } - - // Calculate the result - if(preg_match(self::PATTERN, $input, $match)){ - return $this->compute($match[0]); - } - - return 0; - } - - return $input; - } - - private function compute($input){ - $compute = create_function('', 'return '.$input.';'); - - return 0 + $compute(); - } - - private function callback($input){ - if(is_numeric($input[1])){ - return $input[1]; - } - elseif(preg_match(self::PATTERN, $input[1], $match)){ - return $this->compute($match[0]); - } - - return 0; - } - */ - - /** * Get all accounting account of a group. * You must choose between first parameter (personalized group) or the second (free criteria filter) diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index 3a12d606fdd..52b5f1c411f 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -1,14 +1,14 @@ - * Copyright (C) 2014 Juanjo Menent - * Copyright (C) 2015 Florian Henry - * Copyright (C) 2015 Raphaël Doursenaud - * Copyright (C) 2016 Pierre-Henry Favre - * Copyright (C) 2016-2017 Alexandre Spangaro - * Copyright (C) 2013-2017 Olivier Geffroy - * Copyright (C) 2017 Elarifr. Ari Elbaz - * Copyright (C) 2017 Frédéric France + * Copyright (C) 2007-2012 Laurent Destailleur + * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2015 Florian Henry + * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) 2016 Pierre-Henry Favre + * Copyright (C) 2016-2018 Alexandre Spangaro + * Copyright (C) 2013-2017 Olivier Geffroy + * Copyright (C) 2017 Elarifr. Ari Elbaz + * Copyright (C) 2017 Frédéric France * * This program is free software; you can redistribute it and/or modify @@ -177,7 +177,7 @@ class AccountancyExport */ public static function downloadFile() { global $conf; - $journal = 'bookkepping'; + $filename = 'general_ledger'; include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php'; } diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 3544f98d418..257c2af0111 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -385,14 +385,15 @@ class AccountingAccount extends CommonObject /** * Return clicable name (with picto eventually) * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $withlabel 0=No label, 1=Include label of account - * @param int $nourl 1=Disable url - * @param string $moretitle Add more text to title tooltip - * @param int $notooltip 1=Disable tooltip + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $withlabel 0=No label, 1=Include label of account + * @param int $nourl 1=Disable url + * @param string $moretitle Add more text to title tooltip + * @param int $notooltip 1=Disable tooltip + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @return string String with URL */ - function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle='',$notooltip=0) + function getNomUrl($withpicto = 0, $withlabel = 0, $nourl = 0, $moretitle='',$notooltip=0, $save_lastsearch_value=-1) { global $langs, $conf, $user; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; @@ -403,6 +404,11 @@ class AccountingAccount extends CommonObject $url = DOL_URL_ROOT . '/accountancy/admin/card.php?id=' . $this->id; + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + $picto = 'billr'; $label=''; @@ -561,7 +567,7 @@ class AccountingAccount extends CommonObject function LibStatut($statut,$mode=0) { global $langs; - $langs->load('users'); + $langs->loadLangs(array("users")); if ($mode == 0) { diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php index 3e2c0840f8a..454de6d7b84 100644 --- a/htdocs/accountancy/class/accountingjournal.class.php +++ b/htdocs/accountancy/class/accountingjournal.class.php @@ -36,7 +36,7 @@ class AccountingJournal extends CommonObject public $code; public $label; - public $nature; // 0:various operations, 1:sale, 2:purchase, 3:bank, 4:expense-report, 9: has-new + public $nature; // 1:various operations, 2:sale, 3:purchase, 4:bank, 5:expense-report, 8:inventory, 9: has-new public $active; public $lines; @@ -256,7 +256,7 @@ class AccountingJournal extends CommonObject { global $langs; - $langs->load("accountancy"); + $langs->loadLangs(array("accountancy")); if ($mode == 0) { diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 0ad91a30f56..f7fed2e2b5b 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -170,7 +170,7 @@ class BookKeeping extends CommonObject // Check parameters if (empty($this->numero_compte) || $this->numero_compte == '-1' || $this->numero_compte == 'NotDefined') { - $langs->load("errors"); + $langs->loadLangs(array("errors")); if (in_array($this->doc_type, array('bank', 'expense_report'))) { $this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet, $this->doc_type); @@ -246,9 +246,6 @@ class BookKeeping extends CommonObject } $now = dol_now(); - if (empty($this->date_create)) { - $this->date_create = $now; - } $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " ("; $sql .= "doc_date"; @@ -291,7 +288,7 @@ class BookKeeping extends CommonObject $sql .= "," . $this->montant; $sql .= ",'" . $this->db->escape($this->sens) . "'"; $sql .= ",'" . $this->db->escape($this->fk_user_author) . "'"; - $sql .= ",'" . $this->db->idate($this->date_create). "'"; + $sql .= ",'" . $this->db->idate($now). "'"; $sql .= ",'" . $this->db->escape($this->code_journal) . "'"; $sql .= ",'" . $this->db->escape($this->journal_label) . "'"; $sql .= "," . $this->db->escape($this->piece_num); @@ -496,9 +493,6 @@ class BookKeeping extends CommonObject $this->credit = price2num($this->credit, 'MT'); $now = dol_now(); - if (empty($this->date_create)) { - $this->date_create = $now; - } // Check parameters // Put here code to add control on parameters values @@ -545,7 +539,7 @@ class BookKeeping extends CommonObject $sql .= ' ' . (! isset($this->montant) ? 'NULL' : $this->montant ). ','; $sql .= ' ' . (! isset($this->sens) ? 'NULL' : "'" . $this->db->escape($this->sens) . "'") . ','; $sql .= ' ' . $user->id . ','; - $sql .= ' ' . "'" . $this->db->idate($this->date_create) . "',"; + $sql .= ' ' . "'" . $this->db->idate($now) . "',"; $sql .= ' ' . (empty($this->code_journal) ? 'NULL' : "'" . $this->db->escape($this->code_journal) . "'") . ','; $sql .= ' ' . (empty($this->journal_label) ? 'NULL' : "'" . $this->db->escape($this->journal_label) . "'") . ','; $sql .= ' ' . (empty($this->piece_num) ? 'NULL' : $this->db->escape($this->piece_num)).','; @@ -737,12 +731,12 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key . '=' . $value; } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') { $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; - } elseif ($key == 't.label_operation') { - $sqlwhere[] = $key . ' LIKE \'' . $this->db->escape($value) . '%\''; } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') { $sqlwhere[] = $key . '\'' . $this->db->idate($value) . '\''; + } elseif ($key == 't.credit' || $key == 't.debit') { + $sqlwhere[] = natural_search($key, $value, 1, 1); } else { - $sqlwhere[] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; + $sqlwhere[] = natural_search($key, $value, 0, 1); } } } @@ -1163,7 +1157,7 @@ class BookKeeping extends CommonObject $this->db->begin(); $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . $mode . " as ab"; - $sql .= ' SET ab.' . $field . '=' . (is_numeric($value)?$value:"'".$value."'"); + $sql .= ' SET ab.' . $field . '=' . (is_numeric($value)?$value:"'".$this->db->escape($value)."'"); $sql .= ' WHERE ab.piece_num=' . $piece_num ; $resql = $this->db->query($sql); @@ -1246,7 +1240,7 @@ class BookKeeping extends CommonObject // first check if line not yet in bookkeeping $sql = "DELETE"; $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element; - $sql .= " WHERE import_key = '" . $importkey . "'"; + $sql .= " WHERE import_key = '" . $this->db->escape($importkey) . "'"; $resql = $this->db->query($sql); @@ -1284,7 +1278,7 @@ class BookKeeping extends CommonObject $sql.= " FROM " . MAIN_DB_PREFIX . $this->table_element.$mode; $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($journal)) $sql.= " AND code_journal = '".$this->db->escape($journal)."'"; $sql .= " AND entity IN (" . getEntity('accountancy') . ")"; $resql = $this->db->query($sql); diff --git a/htdocs/accountancy/customer/card.php b/htdocs/accountancy/customer/card.php index 92d8f7b1c37..7e1387db951 100644 --- a/htdocs/accountancy/customer/card.php +++ b/htdocs/accountancy/customer/card.php @@ -24,13 +24,11 @@ */ require '../../main.inc.php'; -// Class require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -// Langs -$langs->load("bills"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("bills","accountancy")); $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); @@ -162,4 +160,4 @@ if (! empty($id)) { } llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index 28657e352b4..18e23826314 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -31,12 +31,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; -// Langs -$langs->load("compta"); -$langs->load("bills"); -$langs->load("other"); -$langs->load("main"); -$langs->load("accountancy"); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","other","main","accountancy")); // Security check if (empty($conf->accounting->enabled)) { @@ -144,6 +140,7 @@ llxHeader('', $langs->trans("CustomersVentilation")); $textprevyear = '' . img_previous() . ''; $textnextyear = ' ' . img_next() . ''; + print load_fiche_titre($langs->trans("CustomersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear, '', 'title_accountancy'); print $langs->trans("DescVentilCustomer") . '
'; @@ -155,8 +152,8 @@ $y = $year_current; $buttonbind = '' . $langs->trans("ValidateHistory") . ''; - -print_fiche_titre($langs->trans("OverviewOfAmountOfLinesNotBound"), $buttonbind, ''); +print_barre_liste($langs->trans("OverviewOfAmountOfLinesNotBound"), '', '', '', '', '', '', -1, '', '', 0, $buttonbind, '', 0, 1, 1); +//print_fiche_titre($langs->trans("OverviewOfAmountOfLinesNotBound"), $buttonbind, ''); print '
'; print ''; @@ -231,7 +228,8 @@ print ''; print '
'; -print_fiche_titre($langs->trans("OverviewOfAmountOfLinesBound"), '', ''); +print_barre_liste($langs->trans("OverviewOfAmountOfLinesBound"), '', '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1); +//print_fiche_titre($langs->trans("OverviewOfAmountOfLinesBound"), '', ''); print '
'; print '
'; @@ -310,7 +308,8 @@ if ($conf->global->MAIN_FEATURES_LEVEL > 0) // This part of code looks strange. print '
'; print '
'; - print_fiche_titre($langs->trans("OtherInfo"), '', ''); + print_barre_liste($langs->trans("OtherInfo"), '', '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1); + //print_fiche_titre($langs->trans("OtherInfo"), '', ''); print '
'; print '
'; diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index b3de47879a9..cc0ced6b067 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -27,7 +27,6 @@ */ require '../../main.inc.php'; -// Class require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; @@ -35,12 +34,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; -// Langs -$langs->load("bills"); -$langs->load("compta"); -$langs->load("main"); -$langs->load("accountancy"); -$langs->load("productbatch"); +// Load translation files required by the page +$langs->loadLangs(array("bills","compta","accountancy","productbatch")); $account_parent = GETPOST('account_parent'); $changeaccount = GETPOST('changeaccount'); @@ -173,20 +168,24 @@ print ''."\n"; + + print ''; + print ''; + print ''; + + print '
'; + print ''."\n"; + + // Name + print ''."\n"; + + // Address + print ''."\n"; + + print ''."\n"; + + print ''."\n"; + + // Country + print ''."\n"; + + print ''."\n"; + + print ''; + print ''."\n"; + + print ''; + print ''."\n"; + + print ''; + print ''."\n"; + + // Web + print ''; + print ''."\n"; + + // Code + print ''."\n"; + + // Note + print ''; + print ''; + + print '
'.$langs->trans("CompanyInfo").''.$langs->trans("Value").'
'; + print '
'; + print '
'; + print '
'; + print '
'; + //if (empty($country_selected)) $country_selected=substr($langs->defaultlang,-2); // By default, country of localization + print $form->select_country($conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY, 'country_id'); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + print '
'; + $formcompany->select_departement($conf->global->MAIN_INFO_ACCOUNTANT_STATE, $conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY, 'state_id'); + print '
'; + print '
'; + print '
'; + print '
'; + print '
'; + print '
'; + print '
'; + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + print '
'; + + print ''; +} +else +{ + /* + * Show parameters + */ + + // Actions buttons + //print '
'; + //print ''.$langs->trans("Modify").''; + //print '

'; + + print '
'; + print ''; + print ''; + + + print ''; + + + print ''; + + + print ''; + + + print ''; + + + print ''; + + + if (! empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT)) print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print '
'.$langs->trans("CompanyInfo").''.$langs->trans("Value").'
'.$langs->trans("CompanyName").''; + print $conf->global->MAIN_INFO_ACCOUNTANT_NAME; + print '
'.$langs->trans("CompanyAddress").'' . nl2br(empty($conf->global->MAIN_INFO_ACCOUNTANT_ADDRESS)?'':$conf->global->MAIN_INFO_ACCOUNTANT_ADDRESS) . '
'.$langs->trans("CompanyZip").'' . (empty($conf->global->MAIN_INFO_ACCOUNTANT_ZIP)?'':$conf->global->MAIN_INFO_ACCOUNTANT_ZIP) . '
'.$langs->trans("CompanyTown").'' . (empty($conf->global->MAIN_INFO_ACCOUNTANT_TOWN)?'':$conf->global->MAIN_INFO_ACCOUNTANT_TOWN) . '
'.$langs->trans("CompanyCountry").''; + if (! empty($conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY)) + { + $code = getCountry($conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY, 2); + $img=picto_from_langcode($code); + print $img?$img.' ':''; + print getCountry($conf->global->MAIN_INFO_ACCOUNTANT_COUNTRY,1); + } + print '
'.$langs->trans("Region-State").''; + else print '
'.$langs->trans("State").''; + if (! empty($conf->global->MAIN_INFO_ACCOUNTANT_STATE)) print getState($conf->global->MAIN_INFO_ACCOUNTANT_STATE,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); + else print ' '; + print '
'.$langs->trans("Phone").'' . dol_print_phone($conf->global->MAIN_INFO_ACCOUNTANT_PHONE,$mysoc->country_code) . '
'.$langs->trans("Fax").'' . dol_print_phone($conf->global->MAIN_INFO_ACCOUNTANT_FAX,$mysoc->country_code) . '
'.$langs->trans("Mail").'' . dol_print_email($conf->global->MAIN_INFO_ACCOUNTANT_MAIL,0,0,0,80) . '
'.$langs->trans("Web").'' . dol_print_url($conf->global->MAIN_INFO_ACCOUNTANT_WEB,'_blank',80) . '
'.$langs->trans("AccountantFileNumber").'' . $conf->global->MAIN_INFO_ACCOUNTANT_CODE . '
'.$langs->trans("Note").'' . (! empty($conf->global->MAIN_INFO_ACCOUNTANT_NOTE) ? nl2br($conf->global->MAIN_INFO_ACCOUNTANT_NOTE) : '') . '
'; + print "
"; + + print ''; + + // Actions buttons + print '
'; + print ''; + print '
'; +} + +llxFooter(); + +$db->close(); diff --git a/htdocs/admin/agenda.php b/htdocs/admin/agenda.php index 748fc7a0309..6fedfa6d2cb 100644 --- a/htdocs/admin/agenda.php +++ b/htdocs/admin/agenda.php @@ -31,9 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("agenda"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'agenda')); $action = GETPOST('action','alpha'); $cancel = GETPOST('cancel','alpha'); diff --git a/htdocs/admin/agenda_extrafields.php b/htdocs/admin/agenda_extrafields.php index 4c61500494d..fadb144b883 100644 --- a/htdocs/admin/agenda_extrafields.php +++ b/htdocs/admin/agenda_extrafields.php @@ -34,9 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("agenda"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'agenda')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/admin/agenda_extsites.php b/htdocs/admin/agenda_extsites.php index dc995a4f88b..906ecd8d092 100644 --- a/htdocs/admin/agenda_extsites.php +++ b/htdocs/admin/agenda_extsites.php @@ -34,9 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; if (!$user->admin) accessforbidden(); -$langs->load("agenda"); -$langs->load("admin"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array('agenda', 'admin', 'other')); $def = array(); $actiontest=GETPOST('test','alpha'); @@ -48,9 +47,11 @@ $MAXAGENDA=$conf->global->AGENDA_EXT_NB; // List of aviable colors $colorlist=array('BECEDD','DDBECE','BFDDBE','F598B4','F68654','CBF654','A4A4A5'); + /* * Actions */ + if ($actionsave) { $db->begin(); @@ -146,7 +147,6 @@ print "
\n"; $selectedvalue=$conf->global->AGENDA_DISABLE_EXT; if ($selectedvalue==1) $selectedvalue=0; else $selectedvalue=1; -$var=true; print ""; print ""; @@ -200,7 +200,6 @@ print ''; print ""; $i=1; -$var=true; while ($i <= $MAXAGENDA) { $key=$i; diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php index b6b332a4b99..2d20d285720 100644 --- a/htdocs/admin/agenda_other.php +++ b/htdocs/admin/agenda_other.php @@ -34,9 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("agenda"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'agenda')); $action = GETPOST('action','alpha'); $value = GETPOST('value','alpha'); diff --git a/htdocs/admin/agenda_reminder.php b/htdocs/admin/agenda_reminder.php index fac49dcfcde..e78a8e089ed 100644 --- a/htdocs/admin/agenda_reminder.php +++ b/htdocs/admin/agenda_reminder.php @@ -29,9 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("agenda"); +// Load translation files required by the page +$langs->loadLangs(array("admin","other","agenda")); $action = GETPOST('action','alpha'); $value = GETPOST('value','alpha'); @@ -173,8 +172,6 @@ llxHeader(); $linkback=''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("AgendaSetup"),$linkback,'title_setup'); -print "
\n"; - diff --git a/htdocs/admin/agenda_xcal.php b/htdocs/admin/agenda_xcal.php index 68561d4390b..481a850790e 100644 --- a/htdocs/admin/agenda_xcal.php +++ b/htdocs/admin/agenda_xcal.php @@ -32,9 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("agenda"); +// Load translation files required by the page +$langs->loadLangs(array("admin","other","agenda")); $def = array(); $actionsave=GETPOST('save','alpha'); @@ -173,11 +172,12 @@ $message.='
'; $message.='
'; print $message; -$message=$langs->trans("AgendaUrlOptions1",$user->login,$user->login).'
'; +$message =$langs->trans("AgendaUrlOptions1",$user->login,$user->login).'
'; $message.=$langs->trans("AgendaUrlOptions3",$user->login,$user->login).'
'; $message.=$langs->trans("AgendaUrlOptionsNotAdmin",$user->login,$user->login).'
'; $message.=$langs->trans("AgendaUrlOptions4",$user->login,$user->login).'
'; -$message.=$langs->trans("AgendaUrlOptionsProject",$user->login,$user->login); +$message.=$langs->trans("AgendaUrlOptionsProject",$user->login,$user->login).'
'; +$message.=$langs->trans("AgendaUrlOptionsNotAutoEvent",'systemauto','systemauto').'
'; print info_admin($message); diff --git a/htdocs/admin/bank.php b/htdocs/admin/bank.php index 236a494c060..a4e9e4bb210 100644 --- a/htdocs/admin/bank.php +++ b/htdocs/admin/bank.php @@ -1,9 +1,9 @@ +/* Copyright (C) 2009 Laurent Destailleur * Copyright (C) 2010-2016 Juanjo Menent - * Copyright (C) 2013-2014 Philippe Grand - * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2013-2018 Philippe Grand + * 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 @@ -31,11 +31,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php'; -$langs->load("admin"); -$langs->load("companies"); -$langs->load("bills"); -$langs->load("other"); -$langs->load("banks"); +// Load translation files required by the page +$langs->loadLangs(array("admin","companies","bills","other","banks")); if (!$user->admin) accessforbidden(); @@ -178,10 +175,6 @@ print load_fiche_titre($langs->trans("BankSetupModule"), $linkback, $head = bank_admin_prepare_head(null); dol_fiche_head($head, 'general', $langs->trans("BankSetupModule"), -1, 'account'); -$var = true; - -$var = !$var; - //Show bank account order print load_fiche_titre($langs->trans("BankOrderShow"), '', ''); @@ -201,12 +194,10 @@ $bankorder[1][0] = $langs->trans("BankOrderES"); $bankorder[1][1] = $langs->trans("BankOrderESDesc"); $bankorder[1][2] = 'BankCode DeskCode BankAccountNumberKey BankAccountNumber'; -$var = true; $i = 0; $nbofbank = count($bankorder); while ($i < $nbofbank) { - $var = !$var; print ''; print '
'.$langs->trans("Color").'
' . $bankorder[$i][0] . "\n"; @@ -238,7 +229,6 @@ while ($i < $nbofbank) { print '
' . "\n"; - print '

'; @@ -430,7 +420,8 @@ if ($conf->global->BANK_REPORT_LAST_NUM_RELEVE) { print ''; print '
' . "\n"; print '' . img_picto($langs->trans("Disabled"), 'switch_off') . ''; diff --git a/htdocs/admin/bank_extrafields.php b/htdocs/admin/bank_extrafields.php index aba65f63887..19446092923 100644 --- a/htdocs/admin/bank_extrafields.php +++ b/htdocs/admin/bank_extrafields.php @@ -30,8 +30,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("banks"); -$langs->load("admin"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'admin')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/admin/barcode.php b/htdocs/admin/barcode.php index 313a852e384..a7a863c4725 100644 --- a/htdocs/admin/barcode.php +++ b/htdocs/admin/barcode.php @@ -28,6 +28,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; +// Load translation files required by the page $langs->load("admin"); if (!$user->admin) accessforbidden(); @@ -157,7 +158,6 @@ foreach($dirbarcode as $reldir) /* * CHOIX ENCODAGE */ -$var=true; print '
'; print load_fiche_titre($langs->trans("BarcodeEncodeModule"),'',''); @@ -185,7 +185,6 @@ if ($resql) { $num = $db->num_rows($resql); $i = 0; - $var=true; while ($i < $num) { @@ -277,7 +276,6 @@ print "
"; print ''; print ""; -$var=true; print ''; print ''; print ''; @@ -371,7 +369,6 @@ if ($conf->produit->enabled) } $modBarCode = new $file(); - $var = !$var; print ''; print ''; print ''; print ''; print "\n"; -$var=true; - -$var=! $var; $substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); diff --git a/htdocs/admin/clicktodial.php b/htdocs/admin/clicktodial.php index e9224ba4688..c2cfaf9f72a 100644 --- a/htdocs/admin/clicktodial.php +++ b/htdocs/admin/clicktodial.php @@ -26,6 +26,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +// Load translation files required by the page $langs->load("admin"); if (!$user->admin) accessforbidden(); @@ -72,8 +73,6 @@ print ''; print ''; print ''; -$var=true; - print '
'.$langs->trans("Parameter").'
'.(isset($modBarCode->name)?$modBarCode->name:$modBarCode->nom)."\n"; diff --git a/htdocs/admin/boxes.php b/htdocs/admin/boxes.php index bc1dc74f6c4..04fd76e96fc 100644 --- a/htdocs/admin/boxes.php +++ b/htdocs/admin/boxes.php @@ -28,8 +28,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -$langs->load("admin"); -$langs->load("boxes"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'boxes')); if (! $user->admin) accessforbidden(); diff --git a/htdocs/admin/chequereceipts.php b/htdocs/admin/chequereceipts.php index 86b38283649..df628ecc87f 100644 --- a/htdocs/admin/chequereceipts.php +++ b/htdocs/admin/chequereceipts.php @@ -1,7 +1,7 @@ * Copyright (C) 2010-2016 Juanjo Menent - * Copyright (C) 2013-2014 Philippe Grand + * Copyright (C) 2013-2018 Philippe Grand * Copyright (C) 2015 Jean-François Ferry * * This program is free software; you can redistribute it and/or modify @@ -31,11 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; -$langs->load("admin"); -$langs->load("companies"); -$langs->load("bills"); -$langs->load("other"); -$langs->load("banks"); +// Load translation files required by the page +$langs->loadLangs(array("admin","companies","bills","other","banks")); if (!$user->admin) accessforbidden(); @@ -133,8 +130,6 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - $var=true; - while (($file = readdir($handle))!==false) { if (! is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) @@ -166,7 +161,6 @@ foreach ($dirmodels as $reldir) if ($module->isEnabled()) { - $var = !$var; print '
'; print (empty($module->name)?$name:$module->name); print "\n"; @@ -254,9 +248,6 @@ print ''.$langs->trans("Parameters").'  
'; print ''; print ''; diff --git a/htdocs/admin/commande.php b/htdocs/admin/commande.php index 5db56c82aa2..cee12e4b08e 100644 --- a/htdocs/admin/commande.php +++ b/htdocs/admin/commande.php @@ -36,10 +36,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php'; -$langs->load("admin"); -$langs->load("errors"); -$langs->load("orders"); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors', 'orders', 'other')); if (! $user->admin) accessforbidden(); @@ -286,7 +284,6 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - $var=true; while (($file = readdir($handle))!==false) { @@ -406,7 +403,6 @@ print "\n"; clearstatcache(); -$var=true; foreach ($dirmodels as $reldir) { foreach (array('','/doc') as $valdir) @@ -537,7 +533,6 @@ print ''; print ''; print "\n"; print "\n"; -$var=true; $substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); @@ -545,7 +540,6 @@ $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; -$var=! $var; print ''; print ''; print ''; diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 94c2cd72b40..949038b4413 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -1,10 +1,11 @@ - * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005-2017 Regis Houssin * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2011-2017 Philippe Grand * Copyright (C) 2015 Alexandre Spangaro + * Copyright (C) 2017 Rui Strecht * * 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 @@ -37,17 +38,17 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; $action=GETPOST('action','aZ09'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'admincompany'; // To manage different context of search -$langs->load("admin"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'companies')); if (! $user->admin) accessforbidden(); $error=0; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$contextpage=array('admincompany','globaladmin'); -$hookmanager->initHooks($contextpage); +$hookmanager->initHooks(array('admincompany','globaladmin')); /* * Actions @@ -74,10 +75,11 @@ if ( ($action == 'update' && ! GETPOST("cancel",'alpha')) } dolibarr_set_const($db, "MAIN_INFO_SOCIETE_NOM", GETPOST("nom",'nohtml'),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ADDRESS", GETPOST("address",'nohtml'),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TOWN", GETPOST("town",'nohtml'),'chaine',0,'',$conf->entity); - dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ZIP", GETPOST("zipcode",'alpha'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ADDRESS", GETPOST("MAIN_INFO_SOCIETE_ADDRESS",'nohtml'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TOWN", GETPOST("MAIN_INFO_SOCIETE_TOWN",'nohtml'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_ZIP", GETPOST("MAIN_INFO_SOCIETE_ZIP",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_STATE", GETPOST("state_id",'alpha'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_INFO_SOCIETE_REGION", GETPOST("region_code",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MONNAIE", GETPOST("currency",'aZ09'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_TEL", GETPOST("tel",'alpha'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_FAX", GETPOST("fax",'alpha'),'chaine',0,'',$conf->entity); @@ -155,6 +157,7 @@ if ( ($action == 'update' && ! GETPOST("cancel",'alpha')) } dolibarr_set_const($db, "MAIN_INFO_SOCIETE_MANAGERS", GETPOST("MAIN_INFO_SOCIETE_MANAGERS",'nohtml'),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_INFO_GDPR", GETPOST("MAIN_INFO_GDPR",'nohtml'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_CAPITAL", GETPOST("capital",'nohtml'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SOCIETE_FORME_JURIDIQUE", GETPOST("forme_juridique_code",'nohtml'),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_INFO_SIREN", GETPOST("siren",'nohtml'),'chaine',0,'',$conf->entity); @@ -293,7 +296,11 @@ $countrynotdefined=''.$langs->trans("ErrorSetACountryFirst") print load_fiche_titre($langs->trans("CompanyFoundation"),'','title_setup'); -print $langs->trans("CompanyFundationDesc")."
\n"; +$head = company_admin_prepare_head(); + +dol_fiche_head($head, 'company', $langs->trans("Company"), -1, 'company'); + +print ''.$langs->trans("CompanyFundationDesc", $langs->transnoentities("Modify"), $langs->transnoentities("Save"))."
\n"; print "
\n"; if ($action == 'edit' || $action == 'updateedit') @@ -324,16 +331,16 @@ if ($action == 'edit' || $action == 'updateedit') // Addresse - print '
'."\n"; + print ''."\n"; - print ''."\n"; + print ''."\n"; - print ''."\n"; + print ''."\n"; // Country @@ -418,6 +425,13 @@ if ($action == 'edit' || $action == 'updateedit') print ''; + // GDPR contact + + print ''; + // Capital print ''; - print ''; @@ -808,6 +823,11 @@ else print ''; + // GDPR Contact + + print ''; + // Capital print '\n"; clearstatcache(); -$var=true; foreach ($dirmodels as $reldir) { foreach (array('','/doc') as $valdir) @@ -377,7 +374,6 @@ foreach ($dirmodels as $reldir) if ($modulequalified) { - $var = !$var; print ''; print ''; print ''; print "\n"; -$var=true; $substitutionarray=pdf_getSubstitutionArray($langs, array('objectamount'), null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); @@ -480,7 +475,6 @@ $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; -$var=! $var; print '
'; echo ''; echo ''; -$var=true; foreach ($rules as $rule) { - echo ''; - + echo ''; + echo ''; - - + + echo ''; - - - + + echo ''; - - + + echo ''; - - + + echo ''; - - + + echo ''; - - + + echo ''; - - + + echo ''; - + echo ''; - $var=!$var; } @@ -355,12 +348,12 @@ echo ''; dol_fiche_end(); llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/admin/export.php b/htdocs/admin/export.php new file mode 100644 index 00000000000..b6f12a723ff --- /dev/null +++ b/htdocs/admin/export.php @@ -0,0 +1,102 @@ + + * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2004 Sebastien Di Cintio + * Copyright (C) 2004 Benoit Mortier + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2011-2012 Juanjo Menent + * Copyright (C) 2011-2015 Philippe Grand + * + * 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/expedition.php + * \ingroup expedition + * \brief Page d'administration/configuration du module Expedition + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array('admin', 'exports')); + +$langs->load('other'); + +if (! $user->admin) + accessforbidden(); + +$action=GETPOST('action','alpha'); +$value=GETPOST('value','alpha'); + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; + + +/* + * View + */ + +$page_name = "ExportSetup"; +llxHeader('', $langs->trans($page_name)); + +// Subheader +$linkback = '' + . $langs->trans("BackToModuleList") . ''; +print_fiche_titre($langs->trans($page_name), $linkback); + +// Configuration header + +dol_fiche_head( + $head, + 'settings', + $langs->trans("ExportsArea"), + 0, + "exports" +); + +// Setup page goes here +$form=new Form($db); +$var=false; +print '
'.$langs->trans("Name").'
'.$langs->trans("Parameter").''.$langs->trans("Value").' 
'; - print '
'; + print '
'; - print '
'; + print '
'; - print '
'; + print '
'; print '
'; + print $form->textwithpicto($langs->trans("GDPRContact"), $langs->trans("GDPRContactDesc")); + print ''; + print '
'; @@ -726,8 +740,9 @@ else print '
'.$langs->trans("State").''; - if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print getState($conf->global->MAIN_INFO_SOCIETE_STATE); + if (! empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT)) print '
'.$langs->trans("Region-State").''; + else print '
'.$langs->trans("State").''; + if (! empty($conf->global->MAIN_INFO_SOCIETE_STATE)) print getState($conf->global->MAIN_INFO_SOCIETE_STATE,$conf->global->MAIN_SHOW_STATE_CODE,0,$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); else print ' '; print '
'.$langs->trans("ManagingDirectors").''; print $conf->global->MAIN_INFO_SOCIETE_MANAGERS . '
'.$langs->trans("GDPRContact").''; + print $conf->global->MAIN_INFO_GDPR . '
'.$langs->trans("Capital").''; @@ -1131,8 +1151,6 @@ else print '
'; print ''; print '
'; - - print '
'; } diff --git a/htdocs/admin/compta.php b/htdocs/admin/compta.php index 3f765d3e18c..8e17541bfef 100644 --- a/htdocs/admin/compta.php +++ b/htdocs/admin/compta.php @@ -29,9 +29,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -$langs->load('admin'); -$langs->load('compta'); -$langs->load('accountancy'); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'compta', 'accountancy')); if (!$user->admin) accessforbidden(); diff --git a/htdocs/admin/confexped.php b/htdocs/admin/confexped.php index cd771cdb0f7..e4691a42e78 100644 --- a/htdocs/admin/confexped.php +++ b/htdocs/admin/confexped.php @@ -29,9 +29,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/expedition.lib.php'; -$langs->load("admin"); -$langs->load("sendings"); -$langs->load("deliveries"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'sendings', 'deliveries')); if (!$user->admin) accessforbidden(); diff --git a/htdocs/admin/const.php b/htdocs/admin/const.php index c91caea435c..9dd68c16326 100644 --- a/htdocs/admin/const.php +++ b/htdocs/admin/const.php @@ -27,6 +27,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +// Load translation files required by the page $langs->load("admin"); if (! $user->admin) diff --git a/htdocs/admin/contract.php b/htdocs/admin/contract.php index 83c3634c35c..74f7acb04f3 100644 --- a/htdocs/admin/contract.php +++ b/htdocs/admin/contract.php @@ -1,6 +1,6 @@ - * Copyright (C) 2011-2015 Philippe Grand + * Copyright (C) 2011-2018 Philippe Grand * * 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 @@ -28,9 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php'; -$langs->load("admin"); -$langs->load("errors"); -$langs->load("contracts"); +// Load translation files required by the page +$langs->loadLangs(array("admin","errors","contracts")); if (!$user->admin) accessforbidden(); @@ -220,7 +219,6 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - $var=true; while (($file = readdir($handle))!==false) { @@ -339,7 +337,6 @@ print "
'; print (empty($module->name)?$name:$module->name); print "\n"; @@ -472,7 +468,6 @@ print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnContracts"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'tooltiphelp'); print '
'; diff --git a/htdocs/admin/dav.php b/htdocs/admin/dav.php new file mode 100644 index 00000000000..ea4bbf97af0 --- /dev/null +++ b/htdocs/admin/dav.php @@ -0,0 +1,148 @@ + + * + * 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/dav.php + * \ingroup dav + * \brief Page to setup DAV server + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/dav/dav.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array("admin","other","agenda")); + +if (!$user->admin) + accessforbidden(); + +// Parameters +$action = GETPOST('action', 'alpha'); +$backtopage = GETPOST('backtopage', 'alpha'); + +$arrayofparameters=array( + 'DAV_ALLOW_PUBLIC_DIR'=>array('css'=>'minwidth200', 'enabled'=>1), + 'DAV_ALLOW_ECM_DIR'=>array('css'=>'minwidth200', 'enabled'=>$conf->ecm->enabled) +); + + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; + + + +/* + * View + */ + + +llxHeader('', $langs->trans("DAVSetup"), $wikihelp); + +$linkback=''.$langs->trans("BackToModuleList").''; +print load_fiche_titre($langs->trans("DAVSetup"),$linkback,'title_setup'); + + +print ''; +print ''; + +$head=dav_admin_prepare_head(); + +dol_fiche_head($head, 'webdav', '', -1, 'action'); + + +if ($action == 'edit') +{ + print ''; + print ''; + print ''; + + print ''; + print ''; + + foreach($arrayofparameters as $key => $val) + { + if (isset($val['enabled']) && empty($val['enabled'])) continue; + + print ''; + } + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + print $form->textwithpicto($langs->trans($key), $langs->trans($key.'Tooltip')); + print '
'; + + print '
'; + print ''; + print '
'; + + print ''; + print '
'; +} +else +{ + print ''; + print ''; + + foreach($arrayofparameters as $key => $val) + { + print ''; + } + + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; + print $form->textwithpicto($langs->trans($key),$langs->trans($key.'Tooltip')); + print '' . $conf->global->$key . '
'; + + print '
'; + print ''.$langs->trans("Modify").''; + print '
'; +} + + +dol_fiche_end(); + +/*print '
'; +print "trans("Save")."\">"; +print "
"; +*/ +print "\n"; + + +clearstatcache(); + +print $langs->trans("WebDAVSetupDesc")."
\n"; +print "
"; + + +// 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 + + +// Show message +$message=''; +$url=''.$urlwithroot.'/dav/fileserver.php'; +$message.=img_picto('','object_globe.png').' '.$langs->trans("WebDavServer",'WebDAV',$url); +$message.='
'; +print $message; + + +llxFooter(); +$db->close(); diff --git a/htdocs/admin/defaultvalues.php b/htdocs/admin/defaultvalues.php index 03c31180af3..84271cff38f 100644 --- a/htdocs/admin/defaultvalues.php +++ b/htdocs/admin/defaultvalues.php @@ -1,6 +1,6 @@ - * Copyright (C) 2017 Regis Houssin +/* Copyright (C) 2017 Laurent Destailleur + * Copyright (C) 2017-2018 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 @@ -26,12 +26,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; -$langs->load("companies"); -$langs->load("products"); -$langs->load("admin"); -$langs->load("sms"); -$langs->load("other"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'products', 'admin', 'sms', 'other', 'errors')); if (!$user->admin) accessforbidden(); @@ -212,9 +208,9 @@ print "
\n"; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($optioncss != '') $param.='&optioncss='.$optioncss; -if (defaulturl) $param.='&defaulturl='.urlencode(defaulturl); -if (defaultkey) $param.='&defaultkey='.urlencode(defaultkey); -if (defaultvalue) $param.='&defaultvalue='.urlencode(defaultvalue); +if ($defaulturl) $param.='&defaulturl='.urlencode($defaulturl); +if ($defaultkey) $param.='&defaultkey='.urlencode($defaultkey); +if ($defaultvalue) $param.='&defaultvalue='.urlencode($defaultvalue); print '
entity) && $debug)?'?debug=1':'').'" method="POST">'; diff --git a/htdocs/admin/delais.php b/htdocs/admin/delais.php index 37f66427225..ae3c43c5b24 100644 --- a/htdocs/admin/delais.php +++ b/htdocs/admin/delais.php @@ -27,6 +27,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +// Load translation files required by the page $langs->load("admin"); if (! $user->admin) accessforbidden(); @@ -144,7 +145,7 @@ if ($action == 'update') $plus=''; if(!empty($conf->global->MAIN_USE_METEO_WITH_PERCENTAGE)) $plus = '_PERCENTAGE'; // Update values - for($i=0;$i<4;$i++) { + for($i=0; $i<4; $i++) { if(isset($_POST['MAIN_METEO'.$plus.'_LEVEL'.$i])) dolibarr_set_const($db, 'MAIN_METEO'.$plus.'_LEVEL'.$i, GETPOST('MAIN_METEO'.$plus.'_LEVEL'.$i, 'int'),'chaine',0,'',$conf->entity); } @@ -172,7 +173,6 @@ if ($action == 'edit') print ''; print ''; print ''; - $var=true; print ''; print ''; @@ -215,7 +215,6 @@ else print '
'.$langs->trans("DelaysOfToleranceBeforeWarning").''.$langs->trans("Value").'
'; print ''; - $var=true; foreach($modules as $module => $delays) { @@ -241,7 +240,6 @@ else print '
'.$langs->trans("DelaysOfToleranceBeforeWarning").''.$langs->trans("Value").'
'; print ''; - $var=false; print ''; print ''; diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index 72ac51e1799..32995bce38f 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2004 Benoit Mortier * Copyright (C) 2005-2017 Regis Houssin * Copyright (C) 2010-2016 Juanjo Menent @@ -41,14 +41,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -$langs->load("errors"); -$langs->load("admin"); -$langs->load("main"); -$langs->load("companies"); -$langs->load("resource"); -$langs->load("holiday"); -$langs->load("accountancy"); -$langs->load("hrm"); +// Load translation files required by the page +$langs->loadLangs(array("errors","admin","main","companies","resource","holiday","accountancy","hrm","orders","contracts","projects","propal","bills","interventions")); $action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; $confirm=GETPOST('confirm','alpha'); @@ -60,6 +54,7 @@ $code=GETPOST('code','alpha'); $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 ($id == 17 && ! empty($user->rights->accounting->chartofaccount)) $allowed=1; // Dictionary with type of expense report and accounting account allowed to manager of chart account if (! $allowed) accessforbidden(); $acts[0] = "activate"; @@ -93,7 +88,7 @@ $hookmanager->initHooks(array('admin')); // Put here declaration of dictionaries properties // Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this. -$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,24,28,17,35,36,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,26,0,); +$taborder=array(9,0,4,3,2,0,1,8,19,16,27,0,5,11,0,33,34,0,6,0,29,0,7,24,28,17,35,36,0,10,23,12,13,0,14,0,22,20,18,21,0,15,30,0,26,0,25,0); // Name of SQL tables of dictionaries $tabname=array(); @@ -121,7 +116,7 @@ $tabname[21]= MAIN_DB_PREFIX."c_availability"; $tabname[22]= MAIN_DB_PREFIX."c_input_reason"; $tabname[23]= MAIN_DB_PREFIX."c_revenuestamp"; $tabname[24]= MAIN_DB_PREFIX."c_type_resource"; -//$tabname[25]= MAIN_DB_PREFIX."c_email_templates"; +$tabname[25]= MAIN_DB_PREFIX."c_type_container"; $tabname[26]= MAIN_DB_PREFIX."c_units"; $tabname[27]= MAIN_DB_PREFIX."c_stcomm"; $tabname[28]= MAIN_DB_PREFIX."c_holiday_types"; @@ -160,7 +155,7 @@ $tablib[21]= "DictionaryAvailability"; $tablib[22]= "DictionarySource"; $tablib[23]= "DictionaryRevenueStamp"; $tablib[24]= "DictionaryResourceType"; -//$tablib[25]= "DictionaryEMailTemplates"; +$tablib[25]= "DictionaryTypeOfContainer"; $tablib[26]= "DictionaryUnits"; $tablib[27]= "DictionaryProspectStatus"; $tablib[28]= "DictionaryHolidayTypes"; @@ -188,7 +183,7 @@ $tabsql[10]= "SELECT t.rowid, t.code, t.taux, t.localtax1_type, t.localtax1, t.l $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.type_cdr, c.decalage, c.active, c.sortorder, c.entity FROM ".MAIN_DB_PREFIX."c_payment_term AS c WHERE c.entity = " . getEntity($tabname[12]); $tabsql[13]= "SELECT c.id as rowid, c.code, c.libelle, c.type, c.active, c.entity FROM ".MAIN_DB_PREFIX."c_paiement AS c WHERE c.entity = " . getEntity($tabname[13]); -$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[14]= "SELECT e.rowid as rowid, e.code as code, e.label, 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"; $tabsql[16]= "SELECT code, label as libelle, sortorder, active FROM ".MAIN_DB_PREFIX."c_prospectlevel"; $tabsql[17]= "SELECT id as rowid, code, label, accountancy_code, active FROM ".MAIN_DB_PREFIX."c_type_fees"; @@ -199,7 +194,7 @@ $tabsql[21]= "SELECT c.rowid as rowid, code, label, active FROM ".MAIN_DB_PREFIX $tabsql[22]= "SELECT rowid as rowid, code, label, active FROM ".MAIN_DB_PREFIX."c_input_reason"; $tabsql[23]= "SELECT t.rowid as rowid, t.taux, t.revenuestamp_type, c.label as country, c.code as country_code, t.fk_pays as country_id, t.note, t.active, t.accountancy_code_sell, t.accountancy_code_buy FROM ".MAIN_DB_PREFIX."c_revenuestamp as t, ".MAIN_DB_PREFIX."c_country as c WHERE t.fk_pays=c.rowid"; $tabsql[24]= "SELECT rowid as rowid, code, label, active FROM ".MAIN_DB_PREFIX."c_type_resource"; -//$tabsql[25]= "SELECT rowid as rowid, label, type_template, private, position, topic, content_lines, content, active FROM ".MAIN_DB_PREFIX."c_email_templates WHERE entity IN (".getEntity('email_template').")"; +$tabsql[25]= "SELECT rowid as rowid, code, label, active, module FROM ".MAIN_DB_PREFIX."c_type_container as t WHERE t.entity IN (".getEntity('c_type_container').")"; $tabsql[26]= "SELECT rowid as rowid, code, label, short_label, active FROM ".MAIN_DB_PREFIX."c_units"; $tabsql[27]= "SELECT id as rowid, code, libelle, active FROM ".MAIN_DB_PREFIX."c_stcomm"; $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"; @@ -237,8 +232,8 @@ $tabsqlsort[20]="code ASC, libelle ASC"; $tabsqlsort[21]="code ASC, label ASC"; $tabsqlsort[22]="code ASC, label ASC"; $tabsqlsort[23]="country ASC, taux ASC"; -$tabsqlsort[24]="code ASC,label ASC"; -//$tabsqlsort[25]="label ASC"; +$tabsqlsort[24]="code ASC, label ASC"; +$tabsqlsort[25]="t.module ASC, t.code ASC, t.label ASC"; $tabsqlsort[26]="code ASC"; $tabsqlsort[27]="code ASC"; $tabsqlsort[28]="country ASC, code ASC"; @@ -266,7 +261,7 @@ $tabfield[10]= "country_id,country,code,taux,localtax1_type,localtax1,localtax2_ $tabfield[11]= "element,source,code,libelle,position"; $tabfield[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder,entity"; $tabfield[13]= "code,libelle,type,entity"; -$tabfield[14]= "code,libelle,price,organization,country_id,country"; +$tabfield[14]= "code,label,price,organization,country"; $tabfield[15]= "code,libelle,width,height,unit"; $tabfield[16]= "code,libelle,sortorder"; $tabfield[17]= "code,label,accountancy_code"; @@ -277,7 +272,7 @@ $tabfield[21]= "code,label"; $tabfield[22]= "code,label"; $tabfield[23]= "country_id,country,taux,revenuestamp_type,accountancy_code_sell,accountancy_code_buy,note"; $tabfield[24]= "code,label"; -//$tabfield[25]= "label,type_template,private,position,topic,content_lines,content"; +$tabfield[25]= "code,label"; $tabfield[26]= "code,label,short_label"; $tabfield[27]= "code,libelle"; $tabfield[28]= "code,label,affect,delay,newbymonth,country_id,country"; @@ -305,7 +300,7 @@ $tabfieldvalue[10]= "country,code,taux,localtax1_type,localtax1,localtax2_type,l $tabfieldvalue[11]= "element,source,code,libelle,position"; $tabfieldvalue[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder"; $tabfieldvalue[13]= "code,libelle,type"; -$tabfieldvalue[14]= "code,libelle,price,organization,country"; +$tabfieldvalue[14]= "code,label,price,organization,country"; $tabfieldvalue[15]= "code,libelle,width,height,unit"; $tabfieldvalue[16]= "code,libelle,sortorder"; $tabfieldvalue[17]= "code,label,accountancy_code"; @@ -316,7 +311,7 @@ $tabfieldvalue[21]= "code,label"; $tabfieldvalue[22]= "code,label"; $tabfieldvalue[23]= "country,taux,revenuestamp_type,accountancy_code_sell,accountancy_code_buy,note"; $tabfieldvalue[24]= "code,label"; -//$tabfieldvalue[25]= "label,type_template,private,position,topic,content_lines,content"; +$tabfieldvalue[25]= "code,label"; $tabfieldvalue[26]= "code,label,short_label"; $tabfieldvalue[27]= "code,libelle"; $tabfieldvalue[28]= "code,label,affect,delay,newbymonth,country"; @@ -344,7 +339,7 @@ $tabfieldinsert[10]= "fk_pays,code,taux,localtax1_type,localtax1,localtax2_type, $tabfieldinsert[11]= "element,source,code,libelle,position"; $tabfieldinsert[12]= "code,libelle,libelle_facture,nbjour,type_cdr,decalage,sortorder,entity"; $tabfieldinsert[13]= "code,libelle,type,entity"; -$tabfieldinsert[14]= "code,libelle,price,organization,fk_pays"; +$tabfieldinsert[14]= "code,label,price,organization,fk_pays"; $tabfieldinsert[15]= "code,label,width,height,unit"; $tabfieldinsert[16]= "code,label,sortorder"; $tabfieldinsert[17]= "code,label,accountancy_code"; @@ -355,7 +350,7 @@ $tabfieldinsert[21]= "code,label"; $tabfieldinsert[22]= "code,label"; $tabfieldinsert[23]= "fk_pays,taux,revenuestamp_type,accountancy_code_sell,accountancy_code_buy,note"; $tabfieldinsert[24]= "code,label"; -//$tabfieldinsert[25]= "label,type_template,private,position,topic,content_lines,content,entity"; +$tabfieldinsert[25]= "code,label"; $tabfieldinsert[26]= "code,label,short_label"; $tabfieldinsert[27]= "code,libelle"; $tabfieldinsert[28]= "code,label,affect,delay,newbymonth,fk_country"; @@ -383,7 +378,7 @@ $tabrowid[8] = "id"; $tabrowid[9] = "code_iso"; $tabrowid[10]= ""; $tabrowid[11]= "rowid"; -$tabrowid[12]= "rowid"; +$tabrowid[12]= ""; $tabrowid[13]= "id"; $tabrowid[14]= ""; $tabrowid[15]= ""; @@ -396,7 +391,7 @@ $tabrowid[21]= "rowid"; $tabrowid[22]= "rowid"; $tabrowid[23]= ""; $tabrowid[24]= ""; -//$tabrowid[25]= ""; +$tabrowid[25]= ""; $tabrowid[26]= ""; $tabrowid[27]= "id"; $tabrowid[28]= ""; @@ -424,7 +419,7 @@ $tabcond[10]= true; $tabcond[11]= (! empty($conf->societe->enabled)); $tabcond[12]= (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->fournisseur->enabled)); $tabcond[13]= (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->fournisseur->enabled)); -$tabcond[14]= (! empty($conf->product->enabled) && ! empty($conf->ecotax->enabled)); +$tabcond[14]= (! empty($conf->product->enabled) && (! empty($conf->ecotax->enabled) || ! empty($conf->global->MAIN_SHOW_ECOTAX_DICTIONNARY))); $tabcond[15]= true; $tabcond[16]= (! empty($conf->societe->enabled) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)); $tabcond[17]= (! empty($conf->deplacement->enabled) || ! empty($conf->expensereport->enabled)); @@ -435,7 +430,7 @@ $tabcond[21]= ! empty($conf->propal->enabled); $tabcond[22]= (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled)); $tabcond[23]= true; $tabcond[24]= ! empty($conf->resource->enabled); -//$tabcond[25]= true; // && ! empty($conf->global->MAIN_EMAIL_EDIT_TEMPLATE_FROM_DIC); +$tabcond[25]= ! empty($conf->website->enabled); $tabcond[26]= ! empty($conf->product->enabled); $tabcond[27]= ! empty($conf->societe->enabled); $tabcond[28]= ! empty($conf->holiday->enabled); @@ -474,7 +469,7 @@ $tabhelp[21] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[22] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[23] = array('revenuestamp_type'=>'FixedOfPercent'); $tabhelp[24] = array('code'=>$langs->trans("EnterAnyCode")); -//$tabhelp[25] = array('topic'=>$langs->trans('SeeSubstitutionVars'),'content'=>$langs->trans('SeeSubstitutionVars'),'content_lines'=>$langs->trans('SeeSubstitutionVars'),'type_template'=>$langs->trans("TemplateForElement"),'private'=>$langs->trans("TemplateIsVisibleByOwnerOnly"), 'position'=>$langs->trans("PositionIntoComboList")); +$tabhelp[25] = array('code'=>$langs->trans('EnterAnyCode')); $tabhelp[26] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[27] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[28] = array('affect'=>$langs->trans("FollowedByACounter"),'delay'=>$langs->trans("MinimumNoticePeriod"), 'newbymonth'=>$langs->trans("NbAddedAutomatically")); @@ -513,7 +508,7 @@ $tabfieldcheck[21] = array(); $tabfieldcheck[22] = array(); $tabfieldcheck[23] = array(); $tabfieldcheck[24] = array(); -//$tabfieldcheck[25] = array(); +$tabfieldcheck[25] = array(); $tabfieldcheck[26] = array(); $tabfieldcheck[27] = array(); $tabfieldcheck[28] = array(); @@ -543,33 +538,27 @@ $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'), + 'supplier_proposal' => $langs->trans('SupplierProposal'), 'order_supplier' => $langs->trans('SupplierOrder'), + 'invoice_supplier' => $langs->trans('SupplierBill'), // 'intervention' => $langs->trans('InterventionCard'), // 'contract' => $langs->trans('Contract'), 'project' => $langs->trans('Project'), 'project_task' => $langs->trans('Task'), 'agenda' => $langs->trans('Agenda'), + 'resource' => $langs->trans('Resource'), // 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') + 'fichinter' => $langs->trans('InterventionCard'), + 'contrat' => $langs->trans('Contract') ); if (! empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) $elementList["societe"] = $langs->trans('ThirdParty'); @@ -1072,8 +1061,7 @@ if ($id) if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); $class='width100'; } if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { - if ($id != 25) $valuetoshow=$form->textwithtooltip($langs->trans("Label"), $langs->trans("LabelUsedByDefault"),2,1,img_help(1,'')); - else $valuetoshow=$langs->trans("Label"); + $valuetoshow=$form->textwithtooltip($langs->trans("Label"), $langs->trans("LabelUsedByDefault"),2,1,img_help(1,'')); } if ($fieldlist[$field]=='libelle_facture') { $valuetoshow=$form->textwithtooltip($langs->trans("LabelOnDocuments"), $langs->trans("LabelUsedByDefault"),2,1,img_help(1,'')); @@ -1298,12 +1286,7 @@ if ($id) if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } if ($fieldlist[$field]=='position') { $align='right'; } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') - { - //if ($id != 25) $valuetoshow=$form->textwithtooltip($langs->trans("Label"), $langs->trans("LabelUsedByDefault"),2,1,img_help(1,'')); - //else $valuetoshow=$langs->trans("Label"); - $valuetoshow=$langs->trans("Label"); - } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } if ($fieldlist[$field]=='libelle_facture') { //$valuetoshow=$form->textwithtooltip($langs->trans("LabelOnDocuments"), $langs->trans("LabelUsedByDefault"),2,1,img_help(1,'')); $valuetoshow=$langs->trans("LabelOnDocuments"); diff --git a/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php index 10653df9dc0..de3ca683519 100644 --- a/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php +++ b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php @@ -118,9 +118,9 @@ class PrestaShopWebservice public function executeRequest($url, $curl_params = array()) { $defaultParams = array( - CURLOPT_HEADER => TRUE, - CURLOPT_RETURNTRANSFER => TRUE, - CURLINFO_HEADER_OUT => TRUE, + CURLOPT_HEADER => true, + CURLOPT_RETURNTRANSFER => true, + CURLINFO_HEADER_OUT => true, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => $this->key.':', CURLOPT_HTTPHEADER => array( 'Expect:' ) diff --git a/htdocs/admin/dolistore/class/dolistore.class.php b/htdocs/admin/dolistore/class/dolistore.class.php index 07dbec4b902..660886c835d 100644 --- a/htdocs/admin/dolistore/class/dolistore.class.php +++ b/htdocs/admin/dolistore/class/dolistore.class.php @@ -42,19 +42,21 @@ class Dolistore /** * Constructor + * + * @param boolean $debug Enable debug of request on screen */ - function __construct() + function __construct($debug=false) { global $conf, $langs; $this->url = DOL_URL_ROOT.'/admin/modules.php?mode=marketplace'; $this->shop_url = 'https://www.dolistore.com/index.php?controller=product&id_product='; $this->vat_rate = 1.2; // 20% de TVA - $this->debug_api = false; + $this->debug_api = $debug; $langtmp = explode('_', $langs->defaultlang); $lang = $langtmp[0]; - $lang_array = array('en'=>0, 'fr'=>1, 'es'=>2, 'it'=>3, 'de'=>4); // Into table ps_lang of Prestashop - 1 + $lang_array = array('en'=>1, 'fr'=>2, 'es'=>3, 'it'=>4, 'de'=>5); // Into table ps_lang of Prestashop - 1 if (! in_array($lang, array_keys($lang_array))) $lang = 'en'; $this->lang = $lang_array[$lang]; } @@ -81,18 +83,25 @@ class Dolistore } try { - $this->api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, - $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $this->debug_api); + $this->api = new PrestaShopWebservice($conf->global->MAIN_MODULE_DOLISTORE_API_SRV, $conf->global->MAIN_MODULE_DOLISTORE_API_KEY, $this->debug_api); + dol_syslog("Call API with MAIN_MODULE_DOLISTORE_API_SRV = ".$conf->global->MAIN_MODULE_DOLISTORE_API_SRV); + // $conf->global->MAIN_MODULE_DOLISTORE_API_KEY is for the login of basic auth. There is no password as it is public data. // Here we set the option array for the Webservice : we want products resources $opt = array(); $opt['resource'] = 'products'; + $opt2 = array(); // make a search to limit the id returned. if ($this->search != '') { - $opt2 = array(); $opt2['url'] = $conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'/api/search?query='.$this->search.'&language='.$this->lang; + // Call + //var_dump($this->api); + + dol_syslog("Call API with opt = ".var_export($opt, true)); + dol_syslog("Call API with opt2 = ".var_export($opt2, true)); + $xml = $this->api->get($opt2); $products = array(); foreach ($xml->products->children() as $product) { @@ -100,7 +109,6 @@ class Dolistore } $opt['filter[id]'] = '['.implode('|', $products).']'; } elseif ($this->categorie != 0) { - $opt2 = array(); $opt2['resource'] = 'categories'; $opt2['id'] = $this->categorie; // Call @@ -117,7 +125,10 @@ class Dolistore $opt['limit'] = "$this->start,$this->end"; // $opt['filter[id]'] contais list of product id that are result of search + // Call API to get the detail + dol_syslog("Call API with opt = ".var_export($opt, true)); + dol_syslog("Call API with opt2 = ".var_export($opt2, true)); $xml = $this->api->get($opt); $this->products = $xml->products->children(); @@ -135,7 +146,11 @@ class Dolistore $trace = $e->getTrace(); if ($trace[0]['args'][0] == 404) die('Bad ID'); else if ($trace[0]['args'][0] == 401) die('Bad auth key'); - else die('Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV); + else + { + print 'Can not access to '.$conf->global->MAIN_MODULE_DOLISTORE_API_SRV.'
'; + print $e->getMessage(); + } } } diff --git a/htdocs/admin/ecm.php b/htdocs/admin/ecm.php index 2d8bd936b50..dc2f3e489f7 100644 --- a/htdocs/admin/ecm.php +++ b/htdocs/admin/ecm.php @@ -25,6 +25,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +// Load translation files required by the page $langs->load("admin"); if (! $user->admin) accessforbidden(); @@ -80,7 +81,6 @@ print '
'; print ''."\n"; print ''; -$var=true; $form = new Form($db); // Mail required for members @@ -110,4 +110,4 @@ print ''; print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_DISABLE_METEO").'' . yn($conf->global->MAIN_DISABLE_METEO) . '
 '.$langs->trans("Value").'
'; llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/admin/events.php b/htdocs/admin/events.php index b2d9bd97980..1d1ec548853 100644 --- a/htdocs/admin/events.php +++ b/htdocs/admin/events.php @@ -31,9 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("users"); -$langs->load("admin"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array("users","admin","other")); $action=GETPOST('action','aZ09'); @@ -42,7 +41,6 @@ $securityevent=new Events($db); $eventstolog=$securityevent->eventstolog; - /* * Actions */ @@ -88,8 +86,6 @@ $head=security_prepare_head(); dol_fiche_head($head, 'audit', $langs->trans("Security"), -1); - -$var=true; print ""; print ""; print ""; @@ -98,8 +94,7 @@ print "\n"; foreach ($eventstolog as $key => $arr) { if ($arr['id']) - { - + { print ''; print ''; print '\n"; clearstatcache(); -$var=true; foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/expensereport/doc"); @@ -376,7 +371,6 @@ foreach ($dirmodels as $reldir) if (file_exists($dir.'/'.$file)) { - $name = substr($file, 4, dol_strlen($file) -16); $classname = substr($file, 0, dol_strlen($file) -12); @@ -480,7 +474,6 @@ print ''; print ''; print ''; print "\n"; -$var=true; $substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); @@ -488,7 +481,6 @@ $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; -$var=! $var; print ''; echo ''; echo ''; - + if ($Tab['active'] == 0) continue; - + $tranche=1; - $var = true; + foreach ($Tab['ranges'] as $k => $range) { if (isset($Tab['ranges'][$k+1])) $label = $langs->trans('expenseReportRangeFromTo', $range->range_ik, ($Tab['ranges'][$k+1]->range_ik-1)); else $label = $langs->trans('expenseReportRangeMoreThan', $range->range_ik); - + if ($range->range_active == 0) $label = $form->textwithpicto($label, $langs->trans('expenseReportRangeDisabled'), 1, 'help', '', 0, 3); - - echo ''; - + + echo ''; + // Label echo ''; - + // Offset echo ''; - + // Total for one echo ''; - + // Action echo ''; - + echo ''; - $var=!$var; } } @@ -185,4 +181,4 @@ echo ''; dol_fiche_end(); llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/admin/expensereport_rules.php b/htdocs/admin/expensereport_rules.php index 26312f708d9..b1d65b8635b 100644 --- a/htdocs/admin/expensereport_rules.php +++ b/htdocs/admin/expensereport_rules.php @@ -30,11 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_rule.class.php'; -$langs->load('admin'); -$langs->load('other'); -$langs->load('trips'); -$langs->load('errors'); -$langs->load('dict'); +// Load translation files required by the page +$langs->loadLangs(array("admin","other","trips","errors","dict")); if (!$user->admin) accessforbidden(); @@ -57,17 +54,17 @@ $amount = GETPOST('amount'); $restrictive = GETPOST('restrictive'); $object = new ExpenseReportRule($db); -if (!empty($id)) +if (!empty($id)) { $result = $object->fetch($id); if ($result < 0) dol_print_error('', $object->error, $object->errors); } - + // TODO do action if ($action == 'save') { $error = 0; - + // check parameters if (empty($apply_to)) { $error++; @@ -93,11 +90,11 @@ if ($action == 'save') $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ExpenseReportLimitAmount")), null, 'errors'); } - + if (empty($error)) { $object->setValues($_POST); - + if($apply_to=='U'){ $object->fk_user=$fk_user; $object->fk_usergroup=0; @@ -114,13 +111,13 @@ if ($action == 'save') $object->dates = $dates; $object->datee = $datee; - + $object->entity = $conf->entity; $res = $object->create($user); if ($res > 0) setEventMessages($langs->trans('ExpenseReportRuleSave'), null); else dol_print_error($object->db); - + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -129,7 +126,7 @@ elseif ($action == 'delete') { // TODO add confirm $res = $object->delete($user); - + if ($res < 0) dol_print_error($object->db); header('Location: '.$_SERVER['PHP_SELF']); @@ -145,7 +142,7 @@ $tab_rules_type = array('EX_DAY' => $langs->trans('Day'), 'EX_MON' => $langs->tr * View */ -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); @@ -176,8 +173,7 @@ if ($action != 'edit') echo ''; echo ''; - $var=true; - echo ''; + echo ''; echo ''; echo '
".$langs->trans("LogEvents")."
'.$arr['id'].''; diff --git a/htdocs/admin/expedition.php b/htdocs/admin/expedition.php index 442a85c9c6a..eb18f904229 100644 --- a/htdocs/admin/expedition.php +++ b/htdocs/admin/expedition.php @@ -6,7 +6,7 @@ * Copyright (C) 2004 Eric Seigne * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2012 Juanjo Menent - * Copyright (C) 2011-2015 Philippe Grand + * Copyright (C) 2011-2018 Philippe Grand * * 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 @@ -34,10 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/expedition.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; -$langs->load("admin"); -$langs->load("sendings"); -$langs->load("deliveries"); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array("admin", "sendings", "deliveries", "other")); if (! $user->admin) accessforbidden(); diff --git a/htdocs/admin/expedition_extrafields.php b/htdocs/admin/expedition_extrafields.php index a12ed1f9b34..af49e5bf064 100644 --- a/htdocs/admin/expedition_extrafields.php +++ b/htdocs/admin/expedition_extrafields.php @@ -35,10 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("sendings"); -$langs->load("deliveries"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'sendings', 'deliveries')); $extrafields = new ExtraFields($db); diff --git a/htdocs/admin/expeditiondet_extrafields.php b/htdocs/admin/expeditiondet_extrafields.php index 073451eba6e..5567e9480e8 100644 --- a/htdocs/admin/expeditiondet_extrafields.php +++ b/htdocs/admin/expeditiondet_extrafields.php @@ -37,9 +37,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("sendings"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'sendings')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/admin/expensereport.php b/htdocs/admin/expensereport.php index 3806a17c99f..1002b146113 100644 --- a/htdocs/admin/expensereport.php +++ b/htdocs/admin/expensereport.php @@ -6,7 +6,7 @@ * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2008 Raphael Bertrand (Resultic) * Copyright (C) 2011-2013 Juanjo Menent - * Copyright (C) 2011-2015 Philippe Grand + * Copyright (C) 2011-2018 Philippe Grand * * 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 @@ -34,10 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; -$langs->load("admin"); -$langs->load("errors"); -$langs->load("trips"); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors', 'trips', 'other')); if (! $user->admin) accessforbidden(); @@ -195,7 +193,7 @@ else if ($action == 'setoptions') $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); @@ -233,8 +231,6 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - $var=true; - while (($file = readdir($handle))!==false) { if (substr($file, 0, 18) == 'mod_expensereport_' && substr($file, dol_strlen($file)-3, 3) == 'php') @@ -351,7 +347,6 @@ print "
'.$langs->trans("Parameter").'
'; print $form->textwithpicto($langs->trans("FreeLegalTextOnExpenseReports"), $langs->trans("AddCRIfTooLong").'

'.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
'; $variablename='EXPENSEREPORT_FREE_TEXT'; diff --git a/htdocs/admin/expensereport_extrafields.php b/htdocs/admin/expensereport_extrafields.php index db06f06d84a..8db81edb869 100644 --- a/htdocs/admin/expensereport_extrafields.php +++ b/htdocs/admin/expensereport_extrafields.php @@ -33,10 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("errors"); -$langs->load("trips"); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors', 'trips', 'other')); $extrafields = new ExtraFields($db); $form = new Form($db); @@ -67,7 +65,7 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; $textobject=$langs->transnoentitiesnoconv("expensereports"); -llxHeader('',$langs->trans("expensereportsSetup")); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $linkback=''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("ExpenseReportsSetup"),$linkback,'title_setup'); diff --git a/htdocs/admin/expensereport_ik.php b/htdocs/admin/expensereport_ik.php index a3bb7c4fc91..db7100d5928 100644 --- a/htdocs/admin/expensereport_ik.php +++ b/htdocs/admin/expensereport_ik.php @@ -30,11 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport_ik.class.php'; -$langs->load('admin'); -$langs->load('other'); -$langs->load('trips'); -$langs->load('errors'); -$langs->load('dict'); +// Load translation files required by the page +$langs->loadLangs(array("admin","trips","errors","other","dict")); if (!$user->admin) accessforbidden(); @@ -58,12 +55,12 @@ if ($action == 'updateik') $result = $expIk->fetch($id); if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); } - + $expIk->setValues($_POST); $result = $expIk->create($user); - + if ($result > 0) setEventMessages('SetupSaved', null, 'mesgs'); - + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -74,11 +71,11 @@ elseif ($action == 'delete') // TODO add confirm { $result = $expIk->fetch($id); if ($result < 0) dol_print_error('', $expIk->error, $expIk->errors); - + $expIk->delete($user); } - - + + header('Location: '.$_SERVER['PHP_SELF']); exit; } @@ -89,7 +86,7 @@ $rangesbycateg = ExpenseReportIk::getAllRanges(); * View */ -llxHeader(); +llxHeader('',$langs->trans("ExpenseReportsSetup")); $form=new Form($db); @@ -125,23 +122,23 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) echo '
'.$langs->trans('expenseReportTotalForFive').' 
['.$langs->trans('RangeNum', $tranche++).'] - '.$label.''; if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; @@ -152,10 +149,10 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) if ($action == 'edit' && $range->ik->id == $id && $range->rowid == $fk_range && $range->fk_c_exp_tax_cat == $fk_c_exp_tax_cat) echo ''; else echo ($range->ik->id > 0 ? $range->ik->coef : $langs->trans('expenseReportCoefUndefined')); echo ''.$langs->trans('expenseReportPrintExample', price($range->ik->offset + 5 * $range->ik->coef)).''; if ($range->range_active == 1) @@ -173,9 +170,8 @@ foreach ($rangesbycateg as $fk_c_exp_tax_cat => $Tab) } } echo '
 
'; echo '
'.$form->selectarray('apply_to', $tab_apply, '', 0).'
'; echo '
'.$form->select_dolusers('', 'fk_user').'
'; @@ -194,7 +190,7 @@ if ($action != 'edit') echo '
'; - echo ''; + echo ''; } @@ -220,11 +216,10 @@ echo '
'.$langs->trans('ExpenseReportRestrictive').' 
'; if ($action == 'edit' && $object->id == $rule->id) { @@ -240,8 +235,8 @@ foreach ($rules as $rule) elseif ($rule->fk_user > 0) echo $tab_apply['U'].' ('.$rule->getUserName().')'; } echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -250,7 +245,7 @@ foreach ($rules as $rule) else { if ($rule->fk_c_type_fees == -1) echo $langs->trans('AllExpenseReport'); - else + else { $key = getDictvalue(MAIN_DB_PREFIX.'c_type_fees', 'code', $rule->fk_c_type_fees, false, 'id'); if ($key != $langs->trans($key)) echo $langs->trans($key); @@ -258,9 +253,8 @@ foreach ($rules as $rule) } } echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -271,8 +265,8 @@ foreach ($rules as $rule) echo $tab_rules_type[$rule->code_expense_rules_type]; } echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -283,8 +277,8 @@ foreach ($rules as $rule) echo dol_print_date($rule->dates, 'day'); } echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -295,8 +289,8 @@ foreach ($rules as $rule) echo dol_print_date($rule->datee, 'day'); } echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -307,8 +301,8 @@ foreach ($rules as $rule) echo price($rule->amount, 0, $langs, 1, -1, -1, $conf->currency); } echo ''; if ($action == 'edit' && $object->id == $rule->id) { @@ -319,8 +313,8 @@ foreach ($rules as $rule) echo yn($rule->restrictive, 1, 1); } echo ''; if ($object->id != $rule->id) { @@ -333,9 +327,8 @@ foreach ($rules as $rule) echo ''.$langs->trans('Cancel').''; } echo '
'; +print ''; +print ''."\n"; +print ''; +print ''."\n"; + + +// Example with a yes / no select +$var=!$var; +print ''; +print ''; +print ''; +print ''; + + +print '
'.$langs->trans("ExportModel").' 
'.$langs->trans("set_EXPORTS_SHARE_MODELS").' '; +print '
'; +print ''; +print ''; +echo ajax_constantonoff('EXPORTS_SHARE_MODELS'); +print '
'; +print '
'; + +llxFooter(); + +$db->close(); diff --git a/htdocs/admin/external_rss.php b/htdocs/admin/external_rss.php index 4a184aa95a0..e8683dfc4ee 100644 --- a/htdocs/admin/external_rss.php +++ b/htdocs/admin/external_rss.php @@ -31,6 +31,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/rssparser.class.php'; +// Load translation files required by the page $langs->load("admin"); // Security check @@ -250,8 +251,6 @@ if ($resql) $rssparser=new RssParser($db); $result = $rssparser->parser($conf->global->$keyrssurl, 5, 300, $conf->externalrss->dir_temp); - $var=true; - print "
"; print "
"; diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index 9ffe45dec40..f00d125a4d5 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -33,10 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -$langs->load("admin"); -$langs->load("errors"); -$langs->load('other'); -$langs->load('bills'); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors', 'other', 'bills')); if (! $user->admin) accessforbidden(); @@ -284,8 +282,6 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - $var=true; - while (($file = readdir($handle))!==false) { if (! is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) @@ -316,7 +312,6 @@ foreach ($dirmodels as $reldir) if ($module->isEnabled()) { - $var = !$var; print '
'; echo preg_replace('/\-.*$/','',preg_replace('/mod_facture_/','',preg_replace('/\.php$/','',$file))); print "\n"; @@ -470,7 +465,6 @@ print "
'; print (empty($module->name)?$name:$module->name); print "\n"; @@ -598,7 +591,6 @@ print ''; print ''; print ''; -$var=True; print ''; print ''; print ''; print ''; print "\n"; -$var=true; // Force date validation -$var=! $var; print ''; print ''; print ''; @@ -717,7 +706,6 @@ $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; -$var=! $var; print ''; print ''; print ''; diff --git a/htdocs/admin/fckeditor.php b/htdocs/admin/fckeditor.php index 70b79acb931..19d4a4cc772 100644 --- a/htdocs/admin/fckeditor.php +++ b/htdocs/admin/fckeditor.php @@ -28,8 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/doleditor.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -$langs->load("admin"); -$langs->load("fckeditor"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'fckeditor')); $action = GETPOST('action','alpha'); // Possible modes are: @@ -139,8 +139,6 @@ $linkback=''; -$var=true; - if (empty($conf->use_javascript_ajax)) { setEventMessages(array($langs->trans("NotAvailable"), $langs->trans("JavascriptDisabled")), null, 'errors'); @@ -158,7 +156,6 @@ else { // Si condition non remplie, on ne propose pas l'option if (! $conditions[$const]) continue; - print ''; print ''; diff --git a/htdocs/admin/fichinter.php b/htdocs/admin/fichinter.php index 46c9d5fec9e..a216f2d4ab7 100644 --- a/htdocs/admin/fichinter.php +++ b/htdocs/admin/fichinter.php @@ -34,10 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php'; require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; -$langs->load("admin"); -$langs->load("errors"); -$langs->load("interventions"); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors', 'interventions', 'other')); if (! $user->admin) accessforbidden(); diff --git a/htdocs/admin/geoipmaxmind.php b/htdocs/admin/geoipmaxmind.php index bf588ca90ae..9c944324527 100644 --- a/htdocs/admin/geoipmaxmind.php +++ b/htdocs/admin/geoipmaxmind.php @@ -30,8 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array("admin","errors")); $action = GETPOST('action','aZ09'); @@ -94,7 +94,6 @@ else } // Mode -$var=true; print ''; print ''; print ''; @@ -105,7 +104,6 @@ print ''; print "\n"; - print ''; print ''; print "\n"; // Type - print ''; // Version - print ''; // Serveur primaire - print ''; // Serveur secondaire - print ''; // Port - print ''; // DNserver - print ''; // Utiliser TLS - print ''; print "\n"; // DNAdmin - print ''; // Pass - print ''; } + $tmparray=$object->getTotalWeightVolume(); + $totalWeight=$tmparray['weight']; + $totalVolume=$tmparray['volume']; + if ($totalWeight) { + print ''; + print ''; + } + if ($totalVolume) { + print ''; + print ''; + } + // Incoterms if (!empty($conf->incoterm->enabled)) { @@ -2135,7 +2171,7 @@ if ($action == 'create') print '
'; @@ -662,7 +654,7 @@ $sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; $sql.= " WHERE clos = 0"; $sql.= " AND courant = 1"; $sql.= " AND entity IN (".getEntity('bank_account').")"; -$var=True; + $resql=$db->query($sql); if ($resql) { @@ -670,7 +662,6 @@ if ($resql) $i = 0; while ($i < $num) { - $row = $db->fetch_row($resql); print ''.$langs->trans("Value").' 
'.img_object("",$picto[$const]).''.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("PathToGeoIPMaxmindCountryDataFile").''; diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index a9bf5313789..50edc32d55f 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -32,26 +32,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; -$langs->load("admin"); -$langs->load("languages"); -$langs->load("other"); - -$langs->load("companies"); -$langs->load("products"); -$langs->load("members"); -$langs->load("projects"); -$langs->load("hrm"); -$langs->load("agenda"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'languages', 'other', 'companies', 'products', 'members', 'projects', 'hrm', 'agenda')); if (! $user->admin) accessforbidden(); $action = GETPOST('action','aZ09'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'adminihm'; // To manage different context of search if (! defined("MAIN_MOTD")) define("MAIN_MOTD",""); -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$contextpage=array('adminihm','globaladmin'); -$hookmanager->initHooks($contextpage); /* @@ -110,10 +100,18 @@ if ($action == 'update') if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_VERMENU_BACK1', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_VERMENU_BACK1', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLENOTAB'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_BACKTITLE1'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKTITLE1', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_BACKTITLE1', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLE'),array())))); + if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLE', $conf->entity); + else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLE', $val,'chaine',0,'',$conf->entity); + $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR1', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR1', $val,'chaine',0,'',$conf->entity); @@ -128,17 +126,13 @@ if ($action == 'update') if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR2', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR2', $val,'chaine',0,'',$conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTTITLENOTAB'),array())))); - if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $conf->entity); - else dolibarr_set_const($db, 'THEME_ELDY_TEXTTITLENOTAB', $val,'chaine',0,'',$conf->entity); - - if (GETPOST('THEME_ELDY_USE_HOVER') == '') dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", '0', 'chaine', 0, '', $conf->entity); // If empty, we set to '0' ('000000' is for black) - else dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", $_POST["THEME_ELDY_USE_HOVER"], 'chaine', 0, '', $conf->entity); - $val=(implode(',',(colorStringToArray(GETPOST('THEME_ELDY_TEXTLINK'),array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TEXTLINK', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_TEXTLINK', $val,'chaine',0,'',$conf->entity); + if (GETPOST('THEME_ELDY_USE_HOVER') == '') dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", '0', 'chaine', 0, '', $conf->entity); // If empty, we set to '0' ('000000' is for black) + else dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", $_POST["THEME_ELDY_USE_HOVER"], '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_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); @@ -545,6 +539,8 @@ else // Show print '
'; // Login page + print '
'; + print ''; print ''; @@ -575,6 +571,7 @@ else // Show print ''; print '
'.$langs->trans("LoginPage").'
'."\n"; + print '
'; print '
'; print ''.$langs->trans("Modify").''; diff --git a/htdocs/admin/index.php b/htdocs/admin/index.php index 0aa8b14199d..6542cec1174 100644 --- a/htdocs/admin/index.php +++ b/htdocs/admin/index.php @@ -24,8 +24,8 @@ require '../main.inc.php'; -$langs->load("admin"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'companies')); if (!$user->admin) accessforbidden(); diff --git a/htdocs/admin/ldap.php b/htdocs/admin/ldap.php index 5655c0c2714..6776cfb1480 100644 --- a/htdocs/admin/ldap.php +++ b/htdocs/admin/ldap.php @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; +// Load translation files required by the page $langs->load("admin"); if (!$user->admin) @@ -102,7 +103,6 @@ if (! function_exists("ldap_connect")) } -$var=true; $form=new Form($db); @@ -180,7 +180,6 @@ print '
'.$langs->trans("Example").'
'.$langs->trans("Type").''; $arraylist=array(); $arraylist['activedirectory']='Active Directory'; @@ -190,7 +189,6 @@ print $form->selectarray('type',$arraylist,$conf->global->LDAP_SERVER_TYPE); print ' 
'.$langs->trans("Version").''; $arraylist=array(); $arraylist['3']='Version 3'; @@ -199,21 +197,18 @@ print $form->selectarray('LDAP_SERVER_PROTOCOLVERSION',$arraylist,$conf->global- print ''.$langs->trans("LDAPServerProtocolVersion").'
'; print $langs->trans("LDAPPrimaryServer").''; print ''; print ''.$langs->trans("LDAPServerExample").'
'; print $langs->trans("LDAPSecondaryServer").''; print ''; print ''.$langs->trans("LDAPServerExample").'
'.$langs->trans("LDAPServerPort").''; if (! empty($conf->global->LDAP_SERVER_PORT)) { @@ -226,13 +221,11 @@ else print ''.$langs->trans("LDAPServerPortExample").'
'.$langs->trans("LDAPServerDn").''; print ''; print ''.$langs->trans("LDAPServerDnExample").'
'.$langs->trans("LDAPServerUseTLS").''; $arraylist=array(); $arraylist['0']=$langs->trans("No"); @@ -245,13 +238,11 @@ print ''.$langs->trans("ForANonAnonymousAccess").'
'.$langs->trans("LDAPAdminDn").''; print ''; print ''.$langs->trans("LDAPAdminDnExample").'
'.$langs->trans("LDAPPassword").''; if (! empty($conf->global->LDAP_ADMIN_PASS)) { diff --git a/htdocs/admin/ldap_contacts.php b/htdocs/admin/ldap_contacts.php index 07910185956..3188bf6e58a 100644 --- a/htdocs/admin/ldap_contacts.php +++ b/htdocs/admin/ldap_contacts.php @@ -32,8 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; -$langs->load("admin"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array("admin","errors")); if (!$user->admin) accessforbidden(); @@ -117,15 +117,12 @@ print ''; print ''; print ''; -$var=true; print ''; print ''; print "\n"; - // DN Pour les contacts - print ''; @@ -133,7 +130,6 @@ print ''; print ''; // List of object class used to define attributes in structure - print ''; @@ -143,7 +139,6 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeContacts").'
'.$langs->trans("LDAPContactDn").''; print ''; print ''.$langs->trans("LDAPContactDnExample").' 
'.$langs->trans("LDAPContactObjectClassList").''; print ''; print ''.$langs->trans("LDAPContactObjectClassListExample").'
'; print '
'; print ''; -$var=true; print ''; print ''; @@ -152,7 +147,6 @@ print ''; print "\n"; // Common name - print ''; @@ -160,7 +154,6 @@ print ''; @@ -168,7 +161,6 @@ print ''; @@ -176,7 +168,6 @@ print ''; @@ -184,7 +175,6 @@ print ''; @@ -192,7 +182,6 @@ print ''; @@ -200,7 +189,6 @@ print ''; @@ -208,7 +196,6 @@ print ''; @@ -216,7 +203,6 @@ print ''; @@ -224,7 +210,6 @@ print ''; @@ -232,7 +217,6 @@ print ''; @@ -240,7 +224,6 @@ print ''; @@ -248,7 +231,6 @@ print ''; @@ -256,7 +238,6 @@ print ''; diff --git a/htdocs/admin/ldap_groups.php b/htdocs/admin/ldap_groups.php index 5a4e36b7792..4ae6ce9ad97 100644 --- a/htdocs/admin/ldap_groups.php +++ b/htdocs/admin/ldap_groups.php @@ -33,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; -$langs->load("admin"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array("admin","errors")); if (!$user->admin) accessforbidden(); @@ -109,14 +109,12 @@ print ''; $form=new Form($db); print '
'.$langs->trans("LDAPDolibarrMapping").''.$langs->trans("LDAPNamingAttribute").'
'.$langs->trans("LDAPFieldFullname").''; print ''; print ''.$langs->trans("LDAPFieldFullnameExample").''.$langs->trans("LDAPFieldName").''; print ''; print ''.$langs->trans("LDAPFieldNameExample").''.$langs->trans("LDAPFieldFirstName").''; print ''; print ''.$langs->trans("LDAPFieldFirstNameExample").''.$langs->trans("LDAPFieldCompany").''; print ''; print ''.$langs->trans("LDAPFieldCompanyExample").''.$langs->trans("LDAPFieldMail").''; print ''; print ''.$langs->trans("LDAPFieldMailExample").''.$langs->trans("LDAPFieldPhone").''; print ''; print ''.$langs->trans("LDAPFieldPhoneExample").''.$langs->trans("LDAPFieldHomePhone").''; print ''; print ''.$langs->trans("LDAPFieldHomePhoneExample").''.$langs->trans("LDAPFieldMobile").''; print ''; print ''.$langs->trans("LDAPFieldMobileExample").''.$langs->trans("LDAPFieldSkype").''; print ''; print ''.$langs->trans("LDAPFieldSkypeExample").''.$langs->trans("LDAPFieldFax").''; print ''; print ''.$langs->trans("LDAPFieldFaxExample").''.$langs->trans("LDAPFieldAddress").''; print ''; print ''.$langs->trans("LDAPFieldAddressExample").''.$langs->trans("LDAPFieldZip").''; print ''; print ''.$langs->trans("LDAPFieldZipExample").''.$langs->trans("LDAPFieldTown").''; print ''; print ''.$langs->trans("LDAPFieldTownExample").''.$langs->trans("LDAPFieldCountry").''; print ''; print ' 
'; -$var=true; print ''; print ''; print "\n"; // DN pour les groupes - print ''; @@ -124,7 +122,6 @@ print ''; print ''; // List of object class used to define attributes in structure - print ''; @@ -134,7 +131,6 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeGroups").'
'.$langs->trans("LDAPGroupDn").''; print ''; print ''.$langs->trans("LDAPGroupDnExample").' 
'.$langs->trans("LDAPGroupObjectClassList").''; print ''; print ''.$langs->trans("LDAPGroupObjectClassListExample").'
'; print '
'; print ''; -$var=true; print ''; print ''; @@ -145,7 +141,6 @@ print "\n"; // Filtre // Common name - print ''; @@ -162,7 +157,6 @@ print ''; */ // Description - print ''; @@ -170,7 +164,6 @@ print ''; diff --git a/htdocs/admin/ldap_members.php b/htdocs/admin/ldap_members.php index a6385c9690c..616eb99a8da 100644 --- a/htdocs/admin/ldap_members.php +++ b/htdocs/admin/ldap_members.php @@ -33,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; -$langs->load("admin"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors')); if (!$user->admin) accessforbidden(); @@ -133,17 +133,13 @@ dol_fiche_head($head, 'members', $langs->trans("LDAPSetup"), -1); print $langs->trans("LDAPDescMembers").'
'; print '
'; - print '
'.$langs->trans("LDAPDolibarrMapping").'
'.$langs->trans("LDAPFieldName").''; print ''; print ''.$langs->trans("LDAPFieldCommonNameExample").'
'.$langs->trans("LDAPFieldDescription").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").''.$langs->trans("LDAPFieldGroupMembers").''; print ''; print ''.$langs->trans("LDAPFieldGroupMembersExample").'
'; -$var=true; - print ''; print ''; print "\n"; // DN Pour les adherents - print ''; @@ -151,7 +147,6 @@ print ''; print ''; // List of object class used to define attributes in structure - print ''; @@ -159,7 +154,6 @@ print ''; print ''; // Filter, used to filter search - print ''; @@ -169,7 +163,6 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeMembers").'
'.$langs->trans("LDAPMemberDn").''; print ''; print ''.$langs->trans("LDAPMemberDnExample").' 
'.$langs->trans("LDAPMemberObjectClassList").''; print ''; print ''.$langs->trans("LDAPMemberObjectClassListExample").' 
'.$langs->trans("LDAPFilterConnection").''; print ''; print ''.$langs->trans("LDAPFilterConnectionExample").'
'; print '
'; print ''; -$var=true; print ''; print ''; @@ -180,7 +173,6 @@ print "\n"; // Filtre // Common name - print ''; @@ -188,7 +180,6 @@ print ''; @@ -196,7 +187,6 @@ print ''; @@ -204,7 +194,6 @@ print ''; print ''; // Login unix - print ''; @@ -212,7 +201,6 @@ print ''; @@ -220,7 +208,6 @@ print ''; @@ -228,7 +215,6 @@ print ''; print ''; // Password crypted - print ''; @@ -236,7 +222,6 @@ print ''; print ''; // Mail - print ''; @@ -244,7 +229,6 @@ print ''; @@ -260,7 +244,6 @@ print ''; print ''; // Mobile - print ''; @@ -268,7 +251,6 @@ print ''; print ''; // Skype - print ''; @@ -276,7 +258,6 @@ print ''; print ''; // Fax - print ''; @@ -284,7 +265,6 @@ print ''; print ''; // Company - print ''; @@ -292,7 +272,6 @@ print ''; print ''; // Address - print ''; @@ -300,7 +279,6 @@ print ''; print ''; // ZIP - print ''; @@ -308,7 +286,6 @@ print ''; print ''; // TOWN - print ''; @@ -316,7 +293,6 @@ print ''; print ''; // COUNTRY - print ''; @@ -324,7 +300,6 @@ print ''; print ''; // Description - print ''; @@ -332,7 +307,6 @@ print ''; print ''; // Public Note - print ''; @@ -348,7 +322,6 @@ print ''; print ''; // Status - print ''; @@ -364,7 +337,6 @@ print ''; print ''; // First subscription amount - print ''; @@ -372,7 +344,6 @@ print ''; print ''; // Last subscription date - print ''; @@ -380,7 +351,6 @@ print ''; print ''; // Last subscription amount - print ''; @@ -388,7 +358,6 @@ print ''; print ''; // End last subscriptions - print ''; diff --git a/htdocs/admin/ldap_members_types.php b/htdocs/admin/ldap_members_types.php index 2c08ec9fae8..e45857f2f38 100644 --- a/htdocs/admin/ldap_members_types.php +++ b/htdocs/admin/ldap_members_types.php @@ -33,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; -$langs->load("admin"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors')); if (!$user->admin) accessforbidden(); @@ -108,14 +108,12 @@ print ''; $form=new Form($db); print '
'.$langs->trans("LDAPDolibarrMapping").'
'.$langs->trans("LDAPFieldFullname").''; print ''; print ''.$langs->trans("LDAPFieldFullnameExample").''.$langs->trans("LDAPFieldName").''; print ''; print ''.$langs->trans("LDAPFieldNameExample").''.$langs->trans("LDAPFieldFirstName").''; print ''; print ''.$langs->trans("LDAPFieldFirstNameExample").' 
'.$langs->trans("LDAPFieldLoginUnix").''; print ''; print ''.$langs->trans("LDAPFieldLoginExample").''.$langs->trans("LDAPFieldLoginSamba").''; print ''; print ''.$langs->trans("LDAPFieldLoginSambaExample").''.$langs->trans("LDAPFieldPasswordNotCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").' 
'.$langs->trans("LDAPFieldPasswordCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").' 
'.$langs->trans("LDAPFieldMail").''; print ''; print ''.$langs->trans("LDAPFieldMailExample").''.$langs->trans("LDAPFieldPhone").''; print ''; print ''.$langs->trans("LDAPFieldPhoneExample").' 
'.$langs->trans("LDAPFieldMobile").''; print ''; print ''.$langs->trans("LDAPFieldMobileExample").' 
'.$langs->trans("LDAPFieldSkype").''; print ''; print ''.$langs->trans("LDAPFieldSkypeExample").' 
'.$langs->trans("LDAPFieldFax").''; print ''; print ''.$langs->trans("LDAPFieldFaxExample").' 
'.$langs->trans("LDAPFieldCompany").''; print ''; print ''.$langs->trans("LDAPFieldCompanyExample").' 
'.$langs->trans("LDAPFieldAddress").''; print ''; print ''.$langs->trans("LDAPFieldAddressExample").' 
'.$langs->trans("LDAPFieldZip").''; print ''; print ''.$langs->trans("LDAPFieldZipExample").' 
'.$langs->trans("LDAPFieldTown").''; print ''; print ''.$langs->trans("LDAPFieldTownExample").' 
'.$langs->trans("LDAPFieldCountry").''; print ''; print '  
'.$langs->trans("LDAPFieldDescription").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").' 
'.$langs->trans("LDAPFieldNotePublic").''; print ''; print ''.$langs->trans("LDAPFieldNotePublicExample").' 
'.$langs->trans("LDAPFieldStatus").''; print ''; print '  
'.$langs->trans("LDAPFieldFirstSubscriptionAmount").''; print ''; print '  
'.$langs->trans("LDAPFieldLastSubscriptionDate").''; print ''; print '  
'.$langs->trans("LDAPFieldLastSubscriptionAmount").''; print ''; print '  
'.$langs->trans("LDAPFieldEndLastSubscription").''; print ''; print ' 
'; -$var=true; print ''; print ''; print "\n"; // DN pour les types de membres - print ''; @@ -123,7 +121,6 @@ print ''; print ''; // List of object class used to define attributes in structure - print ''; @@ -133,7 +130,6 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeMembersTypes").'
'.$langs->trans("LDAPMemberTypeDn").''; print ''; print ''.$langs->trans("LDAPMemberTypepDnExample").' 
'.$langs->trans("LDAPMemberTypeObjectClassList").''; print ''; print ''.$langs->trans("LDAPMemberTypeObjectClassListExample").'
'; print '
'; print ''; -$var=true; print ''; print ''; @@ -144,7 +140,6 @@ print "\n"; // Filtre // Common name - print ''; @@ -152,7 +147,6 @@ print ''; @@ -160,7 +154,6 @@ print ''; diff --git a/htdocs/admin/ldap_users.php b/htdocs/admin/ldap_users.php index a2e40abfed2..8b11069fc61 100644 --- a/htdocs/admin/ldap_users.php +++ b/htdocs/admin/ldap_users.php @@ -33,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; -$langs->load("admin"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'errors')); if (!$user->admin) accessforbidden(); @@ -124,17 +124,13 @@ print $langs->trans("LDAPDescUsers").'
'; print '
'; - - print '
'.$langs->trans("LDAPDolibarrMapping").'
'.$langs->trans("LDAPFieldName").''; print ''; print ''.$langs->trans("LDAPFieldCommonNameExample").''.$langs->trans("LDAPFieldDescription").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").''.$langs->trans("LDAPFieldGroupMembers").''; print ''; print ''.$langs->trans("LDAPFieldGroupMembersExample").'
'; -$var=true; print ''; print ''; print "\n"; // DN Pour les utilisateurs - print ''; @@ -142,7 +138,6 @@ print ''; print ''; // List of object class used to define attributes in structure - print ''; @@ -150,7 +145,6 @@ print ''; print ''; // Filter, used to filter search - print ''; @@ -160,7 +154,6 @@ print ''; print '
'.$langs->trans("LDAPSynchronizeUsers").'
'.$langs->trans("LDAPUserDn").''; print ''; print ''.$langs->trans("LDAPUserDnExample").' 
'.$langs->trans("LDAPUserObjectClassList").''; print ''; print ''.$langs->trans("LDAPUserObjectClassListExample").' 
'.$langs->trans("LDAPFilterConnection").''; print ''; print ''.$langs->trans("LDAPFilterConnectionExample").'
'; print '
'; print ''; -$var=true; print ''; print ''; @@ -169,7 +162,6 @@ print ''; print "\n"; // Common name - print ''; @@ -177,7 +169,6 @@ print ''; @@ -185,7 +176,6 @@ print ''; @@ -193,7 +183,6 @@ print ''; @@ -201,7 +190,6 @@ print ''; @@ -209,7 +197,6 @@ print ''; @@ -217,7 +204,6 @@ print ''; print ''; // Password crypted - print ''; @@ -225,7 +211,6 @@ print ''; print ''; // Mail - print ''; @@ -233,7 +218,6 @@ print ''; @@ -241,7 +225,6 @@ print ''; @@ -249,7 +232,6 @@ print ''; @@ -257,7 +239,6 @@ print ''; @@ -265,7 +246,6 @@ print ''; @@ -273,7 +253,6 @@ print ''; print ''; // Address - print ''; @@ -281,7 +260,6 @@ print ''; print ''; // ZIP - print ''; @@ -289,7 +267,6 @@ print ''; print ''; // TOWN - print ''; @@ -297,7 +274,6 @@ print ''; print ''; // COUNTRY - print ''; @@ -305,7 +281,6 @@ print ''; print ''; // Title - print ''; @@ -313,7 +288,6 @@ print ''; print ''; // Note - print ''; @@ -321,7 +295,6 @@ print ''; print ''; // Sid - print ''; diff --git a/htdocs/admin/limits.php b/htdocs/admin/limits.php index 36b0d4d0df1..e9389b0271d 100644 --- a/htdocs/admin/limits.php +++ b/htdocs/admin/limits.php @@ -26,9 +26,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; -$langs->load("companies"); -$langs->load("products"); -$langs->load("admin"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'products', 'admin')); if (! $user->admin) accessforbidden(); @@ -38,8 +37,8 @@ if ($action == 'update') { $error=0; $MAXDEC=8; - if ($_POST["MAIN_MAX_DECIMALS_UNIT"] > $MAXDEC - || $_POST["MAIN_MAX_DECIMALS_TOT"] > $MAXDEC + if ($_POST["MAIN_MAX_DECIMALS_UNIT"] > $MAXDEC + || $_POST["MAIN_MAX_DECIMALS_TOT"] > $MAXDEC || $_POST["MAIN_MAX_DECIMALS_SHOWN"] > $MAXDEC) { $error++; diff --git a/htdocs/admin/livraison.php b/htdocs/admin/livraison.php index 4c18069b415..88ce717f005 100644 --- a/htdocs/admin/livraison.php +++ b/htdocs/admin/livraison.php @@ -6,8 +6,8 @@ * Copyright (C) 2004 Eric Seigne * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2011-2013 Juanjo Menent - * Copyright (C) 2011-2015 Philippe Grand - * Copyright (C) 2015 Claudio Aschieri + * Copyright (C) 2011-2018 Philippe Grand + * Copyright (C) 2015 Claudio Aschieri * * 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 @@ -34,10 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/expedition.lib.php'; require_once DOL_DOCUMENT_ROOT.'/livraison/class/livraison.class.php'; -$langs->load("admin"); -$langs->load("sendings"); -$langs->load("deliveries"); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array("admin", "sendings", "deliveries", "other")); if (!$user->admin) accessforbidden(); @@ -216,7 +214,6 @@ foreach ($dirmodels as $reldir) $handle = opendir($dir); if (is_resource($handle)) { - $var=true; while (($file = readdir($handle))!==false) { if (substr($file, 0, 14) == 'mod_livraison_' && substr($file, dol_strlen($file)-3, 3) == 'php') @@ -337,7 +334,6 @@ print "\n"; clearstatcache(); -$var=true; foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/livraison/doc/"); @@ -452,7 +448,6 @@ print ''; print ''; print ''; print "\n"; -$var=true; $substitutionarray=pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__']=$langs->trans("Translation"); @@ -460,7 +455,6 @@ $htmltext = ''.$langs->trans("AvailableVariables").':
'; foreach($substitutionarray as $key => $val) $htmltext.=$key.'
'; $htmltext.='
'; -$var=! $var; print ''; print ''; print ''; diff --git a/htdocs/admin/livraison_extrafields.php b/htdocs/admin/livraison_extrafields.php index 5e9a6824899..6ccf798bc93 100644 --- a/htdocs/admin/livraison_extrafields.php +++ b/htdocs/admin/livraison_extrafields.php @@ -35,10 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("sendings"); -$langs->load("deliveries"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'sendings', 'deliveries')); $extrafields = new ExtraFields($db); diff --git a/htdocs/admin/livraisondet_extrafields.php b/htdocs/admin/livraisondet_extrafields.php index f563100a326..431d5c3c170 100644 --- a/htdocs/admin/livraisondet_extrafields.php +++ b/htdocs/admin/livraisondet_extrafields.php @@ -37,9 +37,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("sendings"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'other', 'sendings')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/admin/loan.php b/htdocs/admin/loan.php index 1b5fdafcbb2..3349ac0056a 100644 --- a/htdocs/admin/loan.php +++ b/htdocs/admin/loan.php @@ -28,8 +28,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; -$langs->load("admin"); -$langs->load("loan"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'loan')); // Security check if (!$user->admin) @@ -123,4 +123,4 @@ print "
'.$langs->trans("LDAPDolibarrMapping").''.$langs->trans("LDAPNamingAttribute").'
'.$langs->trans("LDAPFieldFullname").''; print ''; print ''.$langs->trans("LDAPFieldFullnameExample").''.$langs->trans("LDAPFieldName").''; print ''; print ''.$langs->trans("LDAPFieldNameExample").''; // Firstname - print '
'.$langs->trans("LDAPFieldFirstName").''; print ''; print ''.$langs->trans("LDAPFieldFirstNameExample").''.$langs->trans("LDAPFieldLoginUnix").''; print ''; print ''.$langs->trans("LDAPFieldLoginExample").''; // Login samba - print '
'.$langs->trans("LDAPFieldLoginSamba").''; print ''; print ''.$langs->trans("LDAPFieldLoginSambaExample").''.$langs->trans("LDAPFieldPasswordNotCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").' 
'.$langs->trans("LDAPFieldPasswordCrypted").''; print ''; print ''.$langs->trans("LDAPFieldPasswordExample").' 
'.$langs->trans("LDAPFieldMail").''; print ''; print ''.$langs->trans("LDAPFieldMailExample").''; // Phone - print '
'.$langs->trans("LDAPFieldPhone").''; print ''; print ''.$langs->trans("LDAPFieldPhoneExample").''; // Mobile - print '
'.$langs->trans("LDAPFieldMobile").''; print ''; print ''.$langs->trans("LDAPFieldMobileExample").''.$langs->trans("LDAPFieldSkype").''; print ''; print ''.$langs->trans("LDAPFieldSkypeExample").''; // Fax - print '
'.$langs->trans("LDAPFieldFax").''; print ''; print ''.$langs->trans("LDAPFieldFaxExample").''; // Company - print '
'.$langs->trans("LDAPFieldCompany").''; print ''; print ''.$langs->trans("LDAPFieldCompanyExample").' 
'.$langs->trans("LDAPFieldAddress").''; print ''; print ''.$langs->trans("LDAPFieldAddressExample").' 
'.$langs->trans("LDAPFieldZip").''; print ''; print ''.$langs->trans("LDAPFieldZipExample").' 
'.$langs->trans("LDAPFieldTown").''; print ''; print ''.$langs->trans("LDAPFieldTownExample").' 
'.$langs->trans("LDAPFieldCountry").''; print ''; print '  
'.$langs->trans("LDAPFieldTitle").''; print ''; print ''.$langs->trans("LDAPFieldTitleExample").' 
'.$langs->trans("Note").''; print ''; print ''.$langs->trans("LDAPFieldDescriptionExample").' 
'.$langs->trans("LDAPFieldSid").''; print ''; print ''.$langs->trans("LDAPFieldSidExample").'
'.$langs->trans("Parameter").''.$langs->trans("Value").' 
\n"; print '
'; llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/admin/mailing.php b/htdocs/admin/mailing.php index 7abb16a0729..32fbdd4aeb6 100644 --- a/htdocs/admin/mailing.php +++ b/htdocs/admin/mailing.php @@ -27,8 +27,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; -$langs->load("admin"); -$langs->load("mails"); +// Load translation files required by the page +$langs->loadLangs(array("admin", "mails")); if (!$user->admin) accessforbidden(); @@ -60,7 +60,7 @@ if ($action == 'setvalue') // Create temporary encryption key if nedded $res=dolibarr_set_const($db, "MAILING_EMAIL_UNSUBSCRIBE_KEY",$checkread_key,'chaine',0,'',$conf->entity); if (! $res > 0) $error++; - + if (! $error) { $db->commit(); @@ -105,34 +105,30 @@ print ''; print ''; print ''; -$var=true; - print ''; print ''; print ''; print ''; print "\n"; - print ''; - print ''; - print ''; + // Constant to add salt into the unsubscribe and check read tag. // It is also used as a security key parameter. @@ -142,6 +138,13 @@ print ''; +if (!empty($conf->use_javascript_ajax) && $conf->global->MAIN_FEATURES_LEVEL >=1) { + print ''; +} + print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'; print $langs->trans("MailingEMailFrom").''; print ''; if (!empty($conf->global->MAILING_EMAIL_FROM) && ! isValidEmail($conf->global->MAILING_EMAIL_FROM)) print ' '.img_warning($langs->trans("BadEMail")); print '
'; print $langs->trans("MailingEMailError").''; print ''; if (!empty($conf->global->MAILING_EMAIL_ERRORSTO) && ! isValidEmail($conf->global->MAILING_EMAIL_ERRORSTO)) print ' '.img_warning($langs->trans("BadEMail")); print '
'; print $langs->trans("MailingDelay").''; print ''; print '
'; + print $langs->trans("MailAdvTargetRecipients").''; + print ajax_constantonoff('EMAILING_USE_ADVANCED_SELECTOR'); + print '
'; print '
'; diff --git a/htdocs/admin/mailman.php b/htdocs/admin/mailman.php index 89416a72e36..b831c13823f 100644 --- a/htdocs/admin/mailman.php +++ b/htdocs/admin/mailman.php @@ -32,9 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/mailmanspip.lib.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -$langs->load("admin"); -$langs->load("members"); -$langs->load("mailmanspip"); +// Load translation files required by the page +$langs->loadLangs(array("admin", "members", "mailmanspip")); if (! $user->admin) accessforbidden(); @@ -49,7 +48,7 @@ $testunsubscribeemail = GETPOST("testunsubscribeemail"); * Actions */ -// Action mise a jour ou ajout d'une constante +// Action updated or added a constant if ($action == 'update' || $action == 'add') { foreach($_POST['constname'] as $key => $val) @@ -156,9 +155,6 @@ print load_fiche_titre($langs->trans("MailmanSpipSetup"),$linkback,'title_setup' $head = mailmanspip_admin_prepare_head(); - -$var=true; - if (! empty($conf->global->ADHERENT_USE_MAILMAN)) { print ''; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index f6868eb7348..5b6a0841e76 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -27,12 +27,8 @@ 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("companies"); -$langs->load("products"); -$langs->load("admin"); -$langs->load("mails"); -$langs->load("other"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array("companies", "products", "admin", "mails", "other", "errors")); $action=GETPOST('action','alpha'); @@ -70,6 +66,8 @@ complete_substitutions_array($substitutionarrayfortest, $langs); if ($action == 'update' && empty($_POST["cancel"])) { dolibarr_set_const($db, "MAIN_DISABLE_ALL_MAILS", GETPOST("MAIN_DISABLE_ALL_MAILS"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_FORCE_SENDTO", GETPOST("MAIN_MAIL_FORCE_SENDTO"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_ENABLED_USER_DEST_SELECT", GETPOST("MAIN_MAIL_ENABLED_USER_DEST_SELECT"),'chaine',0,'',$conf->entity); // Send mode parameters dolibarr_set_const($db, "MAIN_MAIL_SENDMODE", GETPOST("MAIN_MAIL_SENDMODE"),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_SMTP_PORT", GETPOST("MAIN_MAIL_SMTP_PORT"),'chaine',0,'',$conf->entity); @@ -78,6 +76,11 @@ if ($action == 'update' && empty($_POST["cancel"])) dolibarr_set_const($db, "MAIN_MAIL_SMTPS_PW", GETPOST("MAIN_MAIL_SMTPS_PW"), 'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_TLS", GETPOST("MAIN_MAIL_EMAIL_TLS"),'chaine',0,'',$conf->entity); dolibarr_set_const($db, "MAIN_MAIL_EMAIL_STARTTLS", GETPOST("MAIN_MAIL_EMAIL_STARTTLS"),'chaine',0,'',$conf->entity); + + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_ENABLED", GETPOST("MAIN_MAIL_EMAIL_DKIM_ENABLED"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_DOMAIN", GETPOST("MAIN_MAIL_EMAIL_DKIM_DOMAIN"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_SELECTOR", GETPOST("MAIN_MAIL_EMAIL_DKIM_SELECTOR"),'chaine',0,'',$conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY", GETPOST("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY"),'chaine',0,'',$conf->entity); // Content parameters 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); @@ -146,75 +149,100 @@ if ($action == 'edit') { if (jQuery("#MAIN_MAIL_SENDMODE").val()==\'mail\') { + console.log("I choose php mail mode"); jQuery(".drag").hide(); jQuery("#MAIN_MAIL_EMAIL_TLS").val(0); jQuery("#MAIN_MAIL_EMAIL_TLS").prop("disabled", true); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val(0); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val(0); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").prop("disabled", true); + jQuery(".dkim").hide(); '; if ($linuxlike) { print ' - jQuery("#MAIN_MAIL_SMTP_SERVER").hide(); - jQuery("#MAIN_MAIL_SMTP_PORT").hide(); - jQuery("#smtp_server_mess").show(); - jQuery("#smtp_port_mess").show(); - '; + jQuery("#MAIN_MAIL_SMTP_SERVER").hide(); + jQuery("#MAIN_MAIL_SMTP_PORT").hide(); + jQuery("#smtp_server_mess").show(); + jQuery("#smtp_port_mess").show();'; } else { - print ' - jQuery("#MAIN_MAIL_SMTP_SERVER").prop("disabled", true); - jQuery("#MAIN_MAIL_SMTP_PORT").prop("disabled", true); - jQuery("#smtp_server_mess").hide(); - jQuery("#smtp_port_mess").hide(); - '; - } - print ' + print ' + jQuery("#MAIN_MAIL_SMTP_SERVER").prop("disabled", true); + jQuery("#MAIN_MAIL_SMTP_PORT").prop("disabled", true); + jQuery("#smtp_server_mess").hide(); + jQuery("#smtp_port_mess").hide();'; + } + print ' } if (jQuery("#MAIN_MAIL_SENDMODE").val()==\'smtps\') { + console.log("I choose smtps mode"); jQuery(".drag").show(); jQuery("#MAIN_MAIL_EMAIL_TLS").val('.$conf->global->MAIN_MAIL_EMAIL_TLS.'); jQuery("#MAIN_MAIL_EMAIL_TLS").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val(0); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").prop("disabled", true); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").hide(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").hide(); jQuery("#MAIN_MAIL_SMTP_SERVER").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER").show(); jQuery("#MAIN_MAIL_SMTP_PORT").show(); jQuery("#smtp_server_mess").hide(); jQuery("#smtp_port_mess").hide(); + jQuery(".dkim").hide(); } if (jQuery("#MAIN_MAIL_SENDMODE").val()==\'swiftmailer\') { + console.log("I choose swiftmailer mode"); jQuery(".drag").show(); jQuery("#MAIN_MAIL_EMAIL_TLS").val('.$conf->global->MAIN_MAIL_EMAIL_TLS.'); jQuery("#MAIN_MAIL_EMAIL_TLS").removeAttr("disabled"); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val('.$conf->global->MAIN_MAIL_EMAIL_STARTTLS.'); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").val('.$conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED.'); + jQuery("#MAIN_MAIL_EMAIL_DKIM_ENABLED").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").removeAttr("disabled"); + jQuery("#MAIN_MAIL_EMAIL_DKIM_DOMAIN").show(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_SELECTOR").show(); + jQuery("#MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").show(); jQuery("#MAIN_MAIL_SMTP_SERVER").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_PORT").removeAttr("disabled"); jQuery("#MAIN_MAIL_SMTP_SERVER").show(); jQuery("#MAIN_MAIL_SMTP_PORT").show(); jQuery("#smtp_server_mess").hide(); jQuery("#smtp_port_mess").hide(); + jQuery(".dkim").show(); } } initfields(); jQuery("#MAIN_MAIL_SENDMODE").change(function() { initfields(); }); - jQuery("#MAIN_MAIL_EMAIL_TLS").change(function() { + jQuery("#MAIN_MAIL_EMAIL_TLS").change(function() { if (jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val() == 1) jQuery("#MAIN_MAIL_EMAIL_STARTTLS").val(0); }); jQuery("#MAIN_MAIL_EMAIL_STARTTLS").change(function() { if (jQuery("#MAIN_MAIL_EMAIL_TLS").val() == 1) jQuery("#MAIN_MAIL_EMAIL_TLS").val(0); - }); + }); })'; - print ''."\n"; + print ''."\n"; } print ''; @@ -228,23 +256,30 @@ if ($action == 'edit') clearstatcache(); - $var=true; print ''; print ''; // Disable - print ''; - // Separator + // Force e-mail recipient + print ''; + + //Add user to select destinaries list + print ''; + + // Separator print ''; // Method - print ''; // Host server - print ''; // Port - print ''; } - // TLS - - print ''; // STARTTLS - print ''; - // Separator + // DKIM + print ''; + // DKIM Domain + print ''; + print ''; + + // DKIM Selector + print ''; + print ''; + + // DKIM PRIVATE KEY + print ''; + print ''; + + // Separator print ''; // From - print ''; print ''; @@ -429,22 +486,19 @@ if ($action == 'edit') } else dol_print_error($db);*/ - print ''; // Separator - print ''; // From - print ''; print ''; // Autocopy to - print ''; print ''; @@ -468,22 +522,24 @@ else print $langs->trans("EMailsDesc")."
\n"; print "
\n"; - - $var=true; - print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_DISABLE_ALL_MAILS").''; print $form->selectyesno('MAIN_DISABLE_ALL_MAILS',$conf->global->MAIN_DISABLE_ALL_MAILS,1); print '
'.$langs->trans("MAIN_MAIL_FORCE_SENDTO").''; + print ''; + print '
'.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''; + print $form->selectyesno('MAIN_MAIL_ENABLED_USER_DEST_SELECT',$conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT,1); + print '
 
'.$langs->trans("MAIN_MAIL_SENDMODE").''; // SuperAdministrator access only @@ -263,13 +298,12 @@ if ($action == 'edit') print '
'; if (! $conf->use_javascript_ajax && $linuxlike && $conf->global->MAIN_MAIL_SENDMODE == 'mail') { print $langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike"); print ''; - print $langs->trans("SeeLocalSendMailSetup"); + print ''.$langs->trans("SeeLocalSendMailSetup").''; } else { @@ -283,7 +317,7 @@ if ($action == 'edit') { print ''; print ''; - print ''.$langs->trans("SeeLocalSendMailSetup").''; + print ''.$langs->trans("SeeLocalSendMailSetup").''; } else { @@ -296,13 +330,12 @@ if ($action == 'edit') print '
'; if (! $conf->use_javascript_ajax && $linuxlike && $conf->global->MAIN_MAIL_SENDMODE == 'mail') { print $langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike"); print ''; - print $langs->trans("SeeLocalSendMailSetup"); + print ''.$langs->trans("SeeLocalSendMailSetup").''; } else { @@ -316,7 +349,7 @@ if ($action == 'edit') { print ''; print ''; - print ''.$langs->trans("SeeLocalSendMailSetup").''; + print ''.$langs->trans("SeeLocalSendMailSetup").''; } else { @@ -368,9 +401,8 @@ if ($action == 'edit') print '
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; + // TLS + print '
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer')))) { if (function_exists('openssl_open')) @@ -383,7 +415,6 @@ if ($action == 'edit') print '
'.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer')))) { @@ -396,12 +427,38 @@ if ($action == 'edit') else print yn(0).' ('.$langs->trans("NotSupported").')'; print '
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_ENABLED").''; + if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('swiftmailer')))) + { + if (function_exists('openssl_open')) + { + print $form->selectyesno('MAIN_MAIL_EMAIL_DKIM_ENABLED',(! empty($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED)?$conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED:0),1); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_DOMAIN").'
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_SELECTOR").'
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").''; + print '
 
'.$langs->trans("MAIN_MAIL_EMAIL_FROM",ini_get('sendmail_from')?ini_get('sendmail_from'):$langs->transnoentities("Undefined")).'
'.$langs->trans('MAIN_MAIL_DEFAULT_FROMTYPE').''; + print '
'.$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 ''; // Disable - print ''; - // Separator + // Force e-mail recipient + print ''; + //Add user to select destinaries list + print ''; + + // Separator print ''; // Method - print ''; // Host server - if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE) && $conf->global->MAIN_MAIL_SENDMODE == 'mail')) { - print ''; + print ''; } else { @@ -502,10 +557,9 @@ else } // Port - if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE) && $conf->global->MAIN_MAIL_SENDMODE == 'mail')) { - print ''; + print ''; } else { @@ -513,21 +567,18 @@ else } // SMTPS ID - if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer'))) { print ''; } // SMTPS PW - if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer'))) { print ''; } // TLS - print ''; // STARTTLS - print ''; - // Separator + if ($conf->global->MAIN_MAIL_SENDMODE == 'swiftmailer') + { + // DKIM + print ''; + + // Domain + print ''; + print ''; + + // Selector + print ''; + print ''; + + // PRIVATE KEY + print ''; + print ''; + } + + // Separator print ''; // From - print ''; print ''; // Separator - print ''; // Errors To - print ''; print ''; // Autocopy to - print ''; print ''; $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (empty($reshook) && ! empty($extrafields->attribute_label)) +if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index 149eb160a78..e57e51caf62 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +// Load translation files required by the page $langs->load("categories"); if (! $user->rights->categorie->lire) accessforbidden(); @@ -82,7 +83,7 @@ print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_DISABLE_ALL_MAILS").''.yn($conf->global->MAIN_DISABLE_ALL_MAILS).'
'.$langs->trans("MAIN_MAIL_FORCE_SENDTO").''.$conf->global->MAIN_MAIL_FORCE_SENDTO; + if (! empty($conf->global->MAIN_MAIL_FORCE_SENDTO) && ! isValidEmail($conf->global->MAIN_MAIL_FORCE_SENDTO)) print img_warning($langs->trans("ErrorBadEMail")); + print '
'.$langs->trans("MAIN_MAIL_ENABLED_USER_DEST_SELECT").''.yn($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT).'
 
'.$langs->trans("MAIN_MAIL_SENDMODE").''; $text=$listofmethods[$conf->global->MAIN_MAIL_SENDMODE]; if (empty($text)) $text=$langs->trans("Undefined").img_warning(); @@ -491,10 +547,9 @@ else print '
'.$langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTPS_ID").''.$conf->global->MAIN_MAIL_SMTPS_ID.'
'.$langs->trans("MAIN_MAIL_SMTPS_PW").''.preg_replace('/./','*',$conf->global->MAIN_MAIL_SMTPS_PW).'
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer'))) { @@ -537,11 +588,10 @@ else } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; } - else print yn(0).' ('.$langs->trans("NotSupported").')'; + else print ''.yn(0).' ('.$langs->trans("NotSupported").')'; print '
'.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('smtps', 'swiftmailer'))) { @@ -551,15 +601,45 @@ else } else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; } - else print yn(0).' ('.$langs->trans("NotSupported").')'; + else print ''.yn(0).' ('.$langs->trans("NotSupported").')'; print '
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_ENABLED").''; + if (isset($conf->global->MAIN_MAIL_SENDMODE) && in_array($conf->global->MAIN_MAIL_SENDMODE, array('swiftmailer'))) + { + if (function_exists('openssl_open')) + { + print yn($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED); + } + else print yn(0).' ('.$langs->trans("YourPHPDoesNotHaveSSLSupport").')'; + } + else print yn(0).' ('.$langs->trans("NotSupported").')'; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_DOMAIN").'' . $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_SELECTOR").'' . $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + print '
'.$langs->trans("MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY").'' . $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + print '
 
'.$langs->trans("MAIN_MAIL_EMAIL_FROM",ini_get('sendmail_from')?ini_get('sendmail_from'):$langs->transnoentities("Undefined")).''.$conf->global->MAIN_MAIL_EMAIL_FROM; if (! empty($conf->global->MAIN_MAIL_EMAIL_FROM) && ! isValidEmail($conf->global->MAIN_MAIL_EMAIL_FROM)) print img_warning($langs->trans("ErrorBadEMail")); @@ -614,18 +694,15 @@ else print '
 
'.$langs->trans("MAIN_MAIL_ERRORS_TO").''.$conf->global->MAIN_MAIL_ERRORS_TO; if (! empty($conf->global->MAIN_MAIL_ERRORS_TO) && ! isValidEmail($conf->global->MAIN_MAIL_ERRORS_TO)) print img_warning($langs->trans("ErrorBadEMail")); print '
'.$langs->trans("MAIN_MAIL_AUTOCOPY_TO").''; if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) @@ -644,25 +721,7 @@ else dol_fiche_end(); - if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) - { - print '
'; - /* - // Warning 1 - if ($linuxlike) - { - $sendmailoption=ini_get('mail.force_extra_parameters'); - if (empty($sendmailoption) || ! preg_match('/ba/',$sendmailoption)) - { - print info_admin($langs->trans("SendmailOptionNotComplete")); - } - }*/ - // Warning 2 - print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); - } - - - // Boutons actions + // Actions button print '
'; print ''.$langs->trans("Modify").''; @@ -671,7 +730,7 @@ else { if (function_exists('fsockopen') && $port && $server) { - print ''.$langs->trans("DoTestServerAvailability").''; + print ''.$langs->trans("DoTestServerAvailability").''; } } else @@ -679,16 +738,32 @@ else print ''.$langs->trans("DoTestServerAvailability").''; } - print ''.$langs->trans("DoTestSend").''; + print ''.$langs->trans("DoTestSend").''; if (! empty($conf->fckeditor->enabled)) { - print ''.$langs->trans("DoTestSendHTML").''; + print ''.$langs->trans("DoTestSendHTML").''; } print '
'; + if ($conf->global->MAIN_MAIL_SENDMODE == 'mail' && empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) + { + /* + // Warning 1 + if ($linuxlike) + { + $sendmailoption=ini_get('mail.force_extra_parameters'); + if (empty($sendmailoption) || ! preg_match('/ba/',$sendmailoption)) + { + print info_admin($langs->trans("SendmailOptionNotComplete")); + } + }*/ + // Warning 2 + print info_admin($langs->trans("SendmailOptionMayHurtBuggedMTA")); + } + if (! in_array($action, array('testconnect', 'test', 'testhtml'))) { $text = ''; @@ -744,7 +819,7 @@ else $formmail->fromalsorobot=1; $formmail->fromtype=(GETPOST('fromtype')?GETPOST('fromtype'):(!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE)?$conf->global->MAIN_MAIL_DEFAULT_FROMTYPE:'user')); $formmail->withfromreadonly=1; - $formmail->withsubstit=0; + $formmail->withsubstit=1; $formmail->withfrom=1; $formmail->witherrorsto=1; $formmail->withto=(! empty($_POST['sendto'])?$_POST['sendto']:($user->email?$user->email:1)); diff --git a/htdocs/admin/mails_emailing.php b/htdocs/admin/mails_emailing.php index 1202e9817d3..91826f2be1d 100644 --- a/htdocs/admin/mails_emailing.php +++ b/htdocs/admin/mails_emailing.php @@ -27,12 +27,8 @@ 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("companies"); -$langs->load("products"); -$langs->load("admin"); -$langs->load("mails"); -$langs->load("other"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'products', 'admin', 'mails', 'other', 'errors')); $action=GETPOST('action','alpha'); @@ -228,7 +224,6 @@ if ($action == 'edit') clearstatcache(); - $var=true; print ''; print ''; @@ -341,7 +336,6 @@ if ($action == 'edit') // PW if (! empty($conf->use_javascript_ajax) || (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer')))) { - $mainsmtppw=(! empty($conf->global->MAIN_MAIL_SMTPS_PW_EMAILING)?$conf->global->MAIN_MAIL_SMTPS_PW_EMAILING:''); print ''; } elseif ($value == 'fk_user') @@ -645,7 +648,7 @@ if ($resql) elseif ($value == 'topic') print ''; elseif ($value == 'type_template') { - print ''; + print ''; } elseif (! in_array($value, array('content', 'content_lines'))) print ''; } @@ -679,7 +682,7 @@ if ($resql) if ($fieldlist[$field]=='fk_user') { $valuetoshow=$langs->trans("Owner"); } if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); } + if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Code"); } if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } if ($fieldlist[$field]=='private') { $align='center'; } if ($fieldlist[$field]=='position') { $align='center'; } @@ -711,13 +714,13 @@ if ($resql) { $obj = $db->fetch_object($resql); - print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) { + 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 + $reshook=$hookmanager->executeHooks('editEmailTemplateFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error=$hookmanager->error; $errors=$hookmanager->errors; // Show fields @@ -761,6 +764,7 @@ if ($resql) } if ($tmpfieldlist == 'content') { + print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '
'; $okforextended = true; if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false; $doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%'); @@ -771,12 +775,25 @@ if ($resql) print ''; } } + + print "\n"; } else { - $tmpaction = 'view'; + $keyforobj='type_template'; + if (! in_array($obj->$keyforobj, array_keys($elementList))) + { + $i++; + continue; // It means this is a type of template not into elementList (may be because enabled condition of this type is false because module is not enabled) + } + // TODO Test on 'enabled' + + + print ''; + + $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 + $reshook=$hookmanager->executeHooks('viewEmailTemplateFieldlist',$parameters,$obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error=$hookmanager->error; $errors=$hookmanager->errors; @@ -851,7 +868,7 @@ if ($resql) print ""; // Modify link / Delete link - print ''; - /* $fieldsforcontent = array('content'); if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) @@ -888,8 +904,9 @@ if ($resql) } }*/ + + print "\n"; } - print "\n"; $i++; @@ -972,9 +989,9 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') print ''; } diff --git a/htdocs/admin/menus.php b/htdocs/admin/menus.php index 5e0b6fac6f6..083d78c03e5 100644 --- a/htdocs/admin/menus.php +++ b/htdocs/admin/menus.php @@ -30,11 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; $action=GETPOST('action','aZ09'); $cancel=GETPOST('cancel','alpha'); -$langs->load("companies"); -$langs->load("products"); -$langs->load("admin"); -$langs->load("users"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array("companies","products","admin","users","other")); // Security check if (! $user->admin) accessforbidden(); @@ -167,8 +164,6 @@ if ($action == 'edit') clearstatcache(); // Gestionnaires de menu - $var=true; - print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_MAIL_SMTPS_PW").''; // SuperAdministrator access only @@ -405,14 +399,10 @@ else print $langs->trans("EMailsDesc")."
\n"; print "
\n"; - - $var=true; - print ''; print ''; // Method - print ''; @@ -433,7 +422,6 @@ else } // Port - if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail')) { print ''; @@ -444,21 +432,18 @@ else } // SMTPS ID - if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) { print ''; } // SMTPS PW - if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) { print ''; } // TLS - print ''; // STARTTLS - print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("MAIN_MAIL_SENDMODE").''; $text=$listofmethods[$conf->global->MAIN_MAIL_SENDMODE_EMAILING]; if (empty($text)) $text=$langs->trans("Undefined").img_warning(); @@ -422,7 +412,6 @@ else if (! empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') { // Host server - if ($linuxlike && (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING == 'mail')) { print '
'.$langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTP_PORT_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").'
'.$langs->trans("MAIN_MAIL_SMTPS_ID").''.$conf->global->MAIN_MAIL_SMTPS_ID_EMAILING.'
'.$langs->trans("MAIN_MAIL_SMTPS_PW").''.preg_replace('/./','*',$conf->global->MAIN_MAIL_SMTPS_PW_EMAILING).'
'.$langs->trans("MAIN_MAIL_EMAIL_TLS").''; if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) { @@ -472,7 +457,6 @@ else print '
'.$langs->trans("MAIN_MAIL_EMAIL_STARTTLS").''; if (isset($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && in_array($conf->global->MAIN_MAIL_SENDMODE_EMAILING, array('smtps', 'swiftmailer'))) { diff --git a/htdocs/admin/mails_senderprofile_list.php b/htdocs/admin/mails_senderprofile_list.php index 763e648746d..b6268e7fc1e 100644 --- a/htdocs/admin/mails_senderprofile_list.php +++ b/htdocs/admin/mails_senderprofile_list.php @@ -1,5 +1,6 @@ + * Copyright (C) 2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -21,21 +22,6 @@ * \brief Page to adminsiter email sender profiles */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION','1'); // Do not check anti CSRF attack test -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test done when option MAIN_SECURITY_CSRF_WITH_TOKEN is on. -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test -//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) - - require '../main.inc.php'; require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; @@ -43,7 +29,7 @@ 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/emailsenderprofile.class.php'; -// Load traductions files requiredby by page +// Load translation files required by the page $langs->loadLangs(array("errors","admin","mails","languages")); $action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... @@ -244,6 +230,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); @@ -387,7 +378,7 @@ foreach($object->fields as $key => $val) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields -$parameters=array('arrayfields'=>$arrayfields); +$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); $reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; @@ -507,25 +498,21 @@ print ''."\n"; if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) - { - require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); - $formfile = new FormFile($db); + require_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); + $formfile = new FormFile($db); - // Show list of available documents - $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; - $urlsource.=str_replace('&','&',$param); + $hidegeneratedfilelistifempty=1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; - $filedir=$diroutputmassaction; - $genallowed=$user->rights->monmodule->read; - $delallowed=$user->rights->monmodule->create; + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - print $formfile->showdocuments('massfilesarea_monmodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
'.$langs->trans("ShowTempMassFilesArea").''; - } + $filedir=$diroutputmassaction; + $genallowed=$user->rights->monmodule->read; + $delallowed=$user->rights->monmodule->create; + + print $formfile->showdocuments('massfilesarea_monmodule','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty); } dol_fiche_end(); diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index 24bd6a7b8fe..394742c7d2a 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -1,10 +1,10 @@ - * Copyright (C) 2004-2015 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2004 Benoit Mortier * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2010-2016 Juanjo Menent - * Copyright (C) 2011-2017 Philippe Grand + * Copyright (C) 2011-2018 Philippe Grand * Copyright (C) 2011 Remy Younes * Copyright (C) 2012-2015 Marcos García * Copyright (C) 2012 Christophe Battarel @@ -41,7 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -// Load traductions files requiredby by page +// Load translation files required by the page $langs->loadLangs(array("errors","admin","mails","languages")); $action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; @@ -90,17 +90,17 @@ $tabsqlsort[25]="label ASC, lang ASC, position ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire $tabfield=array(); -$tabfield[25]= "label,type_template,lang,fk_user,private,position,topic,joinfiles,content"; +$tabfield[25]= "label,lang,type_template,fk_user,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfield[25].=',content_lines'; // Nom des champs d'edition pour modification d'un enregistrement $tabfieldvalue=array(); -$tabfieldvalue[25]= "label,type_template,fk_user,lang,private,position,topic,joinfiles,content"; +$tabfieldvalue[25]= "label,lang,type_template,fk_user,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldvalue[25].=',content_lines'; // Nom des champs dans la table pour insertion d'un enregistrement $tabfieldinsert=array(); -$tabfieldinsert[25]= "label,type_template,fk_user,lang,private,position,topic,joinfiles,content"; +$tabfieldinsert[25]= "label,lang,type_template,fk_user,private,position,topic,joinfiles,content"; if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldinsert[25].=',content_lines'; $tabfieldinsert[25].=',entity'; // Must be at end because not into other arrays @@ -167,10 +167,8 @@ if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send']=$la if ($conf->societe->enabled) $elementList['thirdparty']=$langs->trans('MailToThirdparty'); if ($conf->adherent->enabled) $elementList['member']=$langs->trans('MailToMember'); if ($conf->contrat->enabled) $elementList['contract']=$langs->trans('MailToSendContract'); +if ($conf->projet->enabled) $elementList['project']=$langs->trans('MailToProject'); $elementList['user']=$langs->trans('MailToUser'); -$elementList['all'] =$langs->trans('VisibleEverywhere'); -$elementList['none']=$langs->trans('VisibleNowhere'); - $parameters=array('elementList'=>$elementList); $reshook=$hookmanager->executeHooks('emailElementlist',$parameters); // Note that $action and $object may have been modified by some hooks @@ -180,6 +178,12 @@ if ($reshook == 0) { } } +// Add all and none after the sort +$elementList['all'] ='-- '.$langs->trans("All").' -- ('.$langs->trans('VisibleEverywhere').')'; +$elementList['none']='-- '.$langs->trans("None").' -- ('.$langs->trans('VisibleNowhere').')'; + +asort($elementList); + $id = 25; @@ -209,7 +213,7 @@ if (empty($reshook)) } // Actions add or modify an entry into a dictionary - if (GETPOST('actionadd') || GETPOST('actionmodify')) + if (GETPOST('actionadd','alpha') || GETPOST('actionmodify','alpha')) { $listfield=explode(',', str_replace(' ', '',$tabfield[$id])); $listfieldinsert=explode(',',$tabfieldinsert[$id]); @@ -225,15 +229,14 @@ if (empty($reshook)) if ($value == 'content') continue; if ($value == 'content_lines') continue; - if (GETPOST('actionmodify') && $value == 'topic') $_POST['topic']=$_POST['topic-'.$rowid]; + if (GETPOST('actionmodify','alpha') && $value == 'topic') $_POST['topic']=$_POST['topic-'.$rowid]; if ((! isset($_POST[$value]) || $_POST[$value]=='' || $_POST[$value]=='-1') && $value != 'lang' && $value != 'fk_user' && $value != 'position') { $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 == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Code'; if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; if ($fieldnamekey == 'type_template') $fieldnamekey = 'TypeOfTemplate'; @@ -268,8 +271,8 @@ if (empty($reshook)) if ($value == 'fk_user' && ! ($_POST[$keycode] > 0)) $_POST[$keycode]=''; if ($value == 'private' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='0'; if ($value == 'position' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='1'; - if ($_POST[$keycode] == '' && $keycode != 'langcode') $sql.="null"; // lang must be '' if not defined so the unique key that include lang will work - elseif ($_POST[$keycode] == '0' && $keycode == 'langcode') $sql.="null"; + if ($_POST[$keycode] == '' && $keycode != 'langcode') $sql.="null"; // lang must be '' if not defined so the unique key that include lang will work + elseif ($_POST[$keycode] == '0' && $keycode == 'langcode') $sql.="''"; // lang must be '' if not defined so the unique key that include lang will work else $sql.="'".$db->escape($_POST[$keycode])."'"; $i++; } @@ -315,12 +318,16 @@ if (empty($reshook)) if ($field == 'entity') $_POST[$keycode] = $conf->entity; if ($i) $sql.=","; $sql.= $field."="; - if ($_POST[$keycode] == '' || ($keycode == 'langcode' && empty($_POST[$keycode]))) $sql.="null"; // For vat, we want/accept code = '' + +// print $keycode.' - '.$_POST[$keycode].'
'; + if ($_POST[$keycode] == '' || ($keycode != 'langcode' && $keycode != 'private' && empty($_POST[$keycode]))) $sql.="null"; // lang must be '' if not defined so the unique key that include lang will work + elseif ($_POST[$keycode] == '0' && $keycode == 'langcode') $sql.="''"; // lang must be '' if not defined so the unique key that include lang will work + elseif ($keycode == 'private') $sql.=((int) $_POST[$keycode]); // private must be 0 or 1 else $sql.="'".$db->escape($_POST[$keycode])."'"; $i++; } $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; - +//print $sql;exit; dol_syslog("actionmodify", LOG_DEBUG); //print $sql; $resql = $db->query($sql); @@ -440,7 +447,6 @@ $fieldlist=explode(',',$tabfield[$id]); // Form to add a new line $alabelisused=0; -$var=false; print '
'; print ''; @@ -462,7 +468,7 @@ foreach ($fieldlist as $field => $value) if ($fieldlist[$field]=='lang') { $valuetoshow=(empty($conf->global->MAIN_MULTILANGS) ? ' ' : $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 ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Code"); } if ($fieldlist[$field]=='type_template') { $valuetoshow=$langs->trans("TypeOfTemplate"); } if ($fieldlist[$field]=='private') { $align='center'; } if ($fieldlist[$field]=='position') { $align='center'; } @@ -506,7 +512,7 @@ $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 +$reshook = $hookmanager->executeHooks('createEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = $hookmanager->errors; @@ -550,7 +556,7 @@ foreach ($fieldsforcontent as $tmpfieldlist) print ''; } else if ($tmpfieldlist == 'joinfiles') { - print ''; + print ''; } else { @@ -584,9 +590,7 @@ $colspan=count($fieldlist)+1; print '
'; print ''; - print ''; - print '
'; @@ -604,7 +608,6 @@ if ($resql) { $num = $db->num_rows($resql); $i = 0; - $var=true; $param = '&id='.$id; $paramwithsearch = $param; @@ -630,7 +633,7 @@ if ($resql) elseif ($value == 'lang') { print '
'; - print $formadmin->select_language($search_lang, 'search_lang', 0, null, 1); + print $formadmin->select_language($search_lang, 'search_lang', 0, null, 1, 0, 0, 'maxwidth150'); print ''.$form->selectarray('search_type_template', $elementList, $search_type_template, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100onsmartphone').''.$form->selectarray('search_type_template', $elementList, $search_type_template, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth200 maxwidth100onsmartphone').'
'; + print ''; if ($canbemodified) print ''.img_edit().''; if ($iserasable) { @@ -860,7 +877,6 @@ if ($resql) } print '
'; if (! empty($conf->global->MAIN_MULTILANGS)) { - $selectedlang = $langs->defaultlang; + $selectedlang = GETPOSTISSET('langcode','aZ09')?GETPOST('langcode','aZ09'):$langs->defaultlang; if ($context == 'edit') $selectedlang = $obj->{$fieldlist[$field]}; - print $formadmin->select_language($selectedlang, 'langcode', 0, null, 1); + print $formadmin->select_language($selectedlang, 'langcode', 0, null, 1, 0, 0, 'maxwidth150'); } else { @@ -1000,7 +1017,7 @@ function fieldList($fieldlist, $obj='', $tabname='', $context='') } else { - print $form->selectarray('type_template', $elementList, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1); + print $form->selectarray('type_template', $elementList, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1, 0, 0, '', 0, 0, 0, '', 'maxwidth200'); } print '
'; print ''; print ''; // Menu top - print ''; print ''; // Menu smartphone - print ''; print ''; // User print ''; @@ -372,6 +393,7 @@ print ''; // Ref print ''; +// Link to ref print ''; // Amount @@ -462,7 +484,6 @@ if (is_array($blocks)) // User print ''; @@ -474,7 +495,7 @@ if (is_array($blocks)) print ''; // Link to source object - print ''; + print ''.$object_link.''; // Amount print ''; @@ -483,8 +504,8 @@ if (is_array($blocks)) print ''; // Fingerprint - print ''; // Status diff --git a/htdocs/blockedlog/ajax/authority.php b/htdocs/blockedlog/ajax/authority.php index 929fd8401d5..7bde15aa879 100644 --- a/htdocs/blockedlog/ajax/authority.php +++ b/htdocs/blockedlog/ajax/authority.php @@ -27,10 +27,8 @@ // Directory to scan (full path) is inside POST['dir']. if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); $res=require '../../master.inc.php'; diff --git a/htdocs/blockedlog/ajax/block-add.php b/htdocs/blockedlog/ajax/block-add.php index 24fd71f0514..873b904e7a2 100644 --- a/htdocs/blockedlog/ajax/block-add.php +++ b/htdocs/blockedlog/ajax/block-add.php @@ -27,10 +27,8 @@ // Directory to scan (full path) is inside POST['dir']. if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); $res=require '../../main.inc.php'; diff --git a/htdocs/blockedlog/ajax/block-info.php b/htdocs/blockedlog/ajax/block-info.php index d4d4eef4e07..7a4ebebb2cf 100644 --- a/htdocs/blockedlog/ajax/block-info.php +++ b/htdocs/blockedlog/ajax/block-info.php @@ -27,10 +27,8 @@ // Directory to scan (full path) is inside POST['dir']. if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); require '../../main.inc.php'; diff --git a/htdocs/blockedlog/ajax/check_signature.php b/htdocs/blockedlog/ajax/check_signature.php index 4b50474b4a9..199f9051e07 100644 --- a/htdocs/blockedlog/ajax/check_signature.php +++ b/htdocs/blockedlog/ajax/check_signature.php @@ -27,10 +27,8 @@ // Directory to scan (full path) is inside POST['dir']. if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); require '../../main.inc.php'; diff --git a/htdocs/theme/common/octicons/index.html b/htdocs/blockedlog/ajax/index.html similarity index 100% rename from htdocs/theme/common/octicons/index.html rename to htdocs/blockedlog/ajax/index.html diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 20dda286dbd..0210491fba7 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -749,11 +749,12 @@ class BlockedLog return -2; } - if (empty($this->action) || empty($this->fk_user) || empty($this->user_fullname)) { + if (empty($this->action)) { $this->error=$langs->trans("BadParameterWhenCallingCreateOfBlockedLog"); dol_syslog($this->error, LOG_WARNING); return -3; } + if (empty($this->fk_user)) $this->user_fullname='(Anonymous)'; $this->date_creation = dol_now(); diff --git a/htdocs/blockedlog/class/index.html b/htdocs/blockedlog/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/blockedlog/index.html b/htdocs/blockedlog/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/bookmarks/admin/bookmark.php b/htdocs/bookmarks/admin/bookmark.php index 9b3bea82af1..25fa032902f 100644 --- a/htdocs/bookmarks/admin/bookmark.php +++ b/htdocs/bookmarks/admin/bookmark.php @@ -25,6 +25,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +// Load translation files required by the page $langs->load("admin"); if (!$user->admin) @@ -68,8 +69,6 @@ print ''; print ''; print ''; -$var=true; - print '
'.$langs->trans("Menu").''; @@ -180,7 +175,6 @@ if ($action == 'edit') print '
'.$langs->trans("DefaultMenuManager").''; $formadmin->select_menu(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?$conf->global->MAIN_MENU_STANDARD:$conf->global->MAIN_MENU_STANDARD_FORCED, 'MAIN_MENU_STANDARD', $dirstandard, empty($conf->global->MAIN_MENU_STANDARD_FORCED)?'':' disabled'); @@ -191,7 +185,6 @@ if ($action == 'edit') print '
'.$langs->trans("DefaultMenuSmartphoneManager").''; $formadmin->select_menu(empty($conf->global->MAIN_MENU_SMARTPHONE_FORCED)?$conf->global->MAIN_MENU_SMARTPHONE:$conf->global->MAIN_MENU_SMARTPHONE_FORCED, 'MAIN_MENU_SMARTPHONE', array_merge($dirstandard,$dirsmartphone), empty($conf->global->MAIN_MENU_SMARTPHONE_FORCED)?'':' disabled'); @@ -206,8 +199,6 @@ if ($action == 'edit') else { // Gestionnaires de menu - $var=true; - print ''; print ''; print ''; + + print '
'; + print_barre_liste('',$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); + + $moreforfilter = ''; + + print '
'; + print '
'.$langs->trans("Menu").''; @@ -271,7 +262,6 @@ if ($action == 'edit') print ''; - if ($action != 'edit') { print '
'; diff --git a/htdocs/admin/modulehelp.php b/htdocs/admin/modulehelp.php index bc48feb076f..6281376dc2e 100644 --- a/htdocs/admin/modulehelp.php +++ b/htdocs/admin/modulehelp.php @@ -17,29 +17,19 @@ */ /** - * \file htdocs/admin/modules.php + * \file htdocs/admin/modulehelp.php * \brief Page to activate/disable all modules */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -//if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test -//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1'); // Do not check style html tag into posted data -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -$langs->load("errors"); -$langs->load("admin"); +// Load translation files required by the page +$langs->loadLangs(array('errors', 'admin')); $mode=GETPOST('mode', 'alpha'); $action=GETPOST('action','alpha'); @@ -163,8 +153,6 @@ foreach ($modulesdir as $dir) $modules[$i] = $objMod; $filename[$i]= $modName; - $special = $objMod->special; - // Gives the possibility to the module, to provide his own family info and position of this family if (is_array($objMod->familyinfo) && !empty($objMod->familyinfo)) { if (!is_array($familyinfo)) $familyinfo=array(); @@ -180,13 +168,11 @@ foreach ($modulesdir as $dir) $moduleposition = 800; } - if ($special == 1) $familykey='interface'; - $orders[$i] = $familyinfo[$familykey]['position']."_".$familykey."_".$moduleposition."_".$j; // Sort by family, then by module position then number $dirmod[$i] = $dir; //print $i.'-'.$dirmod[$i].'
'; // Set categ[$i] - $specialstring = isset($specialtostring[$special])?$specialtostring[$special]:'unknown'; + $specialstring = 'unknown'; if ($objMod->version == 'development' || $objMod->version == 'experimental') $specialstring='expdev'; if (isset($categ[$specialstring])) $categ[$specialstring]++; // Array of all different modules categories else $categ[$specialstring]=1; @@ -240,7 +226,6 @@ foreach($orders as $tmpkey => $tmpvalue) $i++; } $value = $orders[$key]; -$special = $objMod->special; $tab=explode('_',$value); $familyposition=$tab[0]; $familykey=$tab[1]; $module_position=$tab[2]; $numero=$tab[3]; @@ -328,7 +313,9 @@ if ($mode == 'desc') { $textexternal.='
'.$langs->trans("Origin").': '.$langs->trans("ExternalModule",$dirofmodule); if ($objMod->editor_name != 'dolibarr') $textexternal.='
'.$langs->trans("Publisher").': '.(empty($objMod->editor_name)?$langs->trans("Unknown"):$objMod->editor_name); - if (! empty($objMod->editor_url) && ! preg_match('/dolibarr\.org/i',$objMod->editor_url)) $textexternal.='
'.$langs->trans("Url").': '.$objMod->editor_url.''; + $editor_url = $objMod->editor_url; + if (! preg_match('/^http/', $editor_url)) $editor_url = 'http://'.$editor_url; + if (! empty($objMod->editor_url) && ! preg_match('/dolibarr\.org/i',$objMod->editor_url)) $textexternal.='
'.$langs->trans("Url").': '.$objMod->editor_url.''; $text.=$textexternal; $text.='
'; } diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index 68764be5fc5..5ba261b619e 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -34,6 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/admin/dolistore/class/dolistore.class.php'; +// Load translation files required by the page $langs->loadLangs(array("errors","admin","modulebuilder")); $mode=GETPOST('mode', 'alpha'); @@ -54,7 +55,7 @@ $options['categorie'] = ((GETPOST('categorie', 'int')?GETPOST('categorie', 'int' $options['start'] = ((GETPOST('start', 'int')?GETPOST('start', 'int'):0) + 0); $options['end'] = ((GETPOST('end', 'int')?GETPOST('end', 'int'):0) + 0); $options['search'] = GETPOST('search_keyword', 'alpha'); -$dolistore = new Dolistore(); +$dolistore = new Dolistore(false); if (! $user->admin) @@ -78,10 +79,13 @@ $familyinfo=array( ); $param=''; -if ($search_keyword) $param.='&search_keyword='.urlencode($search_keyword); -if ($search_status && $search_status != '-1') $param.='&search_status='.urlencode($search_status); -if ($search_nature && $search_nature != '-1') $param.='&search_nature='.urlencode($search_nature); -if ($search_version && $search_version != '-1') $param.='&search_version='.urlencode($search_version); +if (! GETPOST('buttonreset','alpha')) +{ + if ($search_keyword) $param.='&search_keyword='.urlencode($search_keyword); + if ($search_status && $search_status != '-1') $param.='&search_status='.urlencode($search_status); + if ($search_nature && $search_nature != '-1') $param.='&search_nature='.urlencode($search_nature); + if ($search_version && $search_version != '-1') $param.='&search_version='.urlencode($search_version); +} $dirins=DOL_DOCUMENT_ROOT.'/custom'; $urldolibarrmodules='https://www.dolistore.com/'; @@ -358,8 +362,6 @@ foreach ($modulesdir as $dir) $filename[$i]= $modName; $modules[$modName] = $objMod; - $special = $objMod->special; - // Gives the possibility to the module, to provide his own family info and position of this family if (is_array($objMod->familyinfo) && !empty($objMod->familyinfo)) { $familyinfo = array_merge($familyinfo, $objMod->familyinfo); @@ -374,8 +376,6 @@ foreach ($modulesdir as $dir) $moduleposition = 800; } - if ($special == 1) $familykey='interface'; - // Add list of warnings to show into arrayofwarnings and arrayofwarningsext if (! empty($objMod->warnings_activation)) { @@ -390,7 +390,7 @@ foreach ($modulesdir as $dir) $dirmod[$i] = $dir; //print $i.'-'.$dirmod[$i].'
'; // Set categ[$i] - $specialstring = isset($specialtostring[$special])?$specialtostring[$special]:'unknown'; + $specialstring = 'unknown'; if ($objMod->version == 'development' || $objMod->version == 'experimental') $specialstring='expdev'; if (isset($categ[$specialstring])) $categ[$specialstring]++; // Array of all different modules categories else $categ[$specialstring]=1; @@ -531,12 +531,9 @@ if ($mode == 'common') $objMod = $modules[$modName]; $dirofmodule = $dirmod[$key]; - $special = $objMod->special; - - //print $objMod->name." - ".$key." - ".$objMod->special.' - '.$objMod->version."
"; + //print $objMod->name." - ".$key." - ".$objMod->version."
"; //if (($mode != (isset($specialtostring[$special])?$specialtostring[$special]:'unknown') && $mode != 'expdev') - if (($special >= 4 && $mode != 'expdev') - || ($mode == 'expdev' && $objMod->version != 'development' && $objMod->version != 'experimental')) continue; // Discard if not for current tab + if ($mode == 'expdev' && $objMod->version != 'development' && $objMod->version != 'experimental') continue; // Discard if not for current tab if (! $objMod->getName()) { diff --git a/htdocs/admin/multicurrency.php b/htdocs/admin/multicurrency.php index 467ffffeb41..b301a2c7a03 100644 --- a/htdocs/admin/multicurrency.php +++ b/htdocs/admin/multicurrency.php @@ -19,22 +19,18 @@ /** * \file admin/multicurrency.php * \ingroup multicurrency - * \brief This file is an example module setup page - * Put some comments here + * \brief Page to setup multicurrency module */ + // Dolibarr environment - require '../main.inc.php'; - -// Libraries require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/multicurrency.lib.php'; require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; -// Translations -$langs->load("admin"); -$langs->load("multicurrency"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'multicurrency')); // Access control if (! $user->admin) { @@ -43,6 +39,8 @@ if (! $user->admin) { // Parameters $action = GETPOST('action', 'alpha'); + + /* * Actions */ @@ -143,17 +141,7 @@ elseif ($action == 'update_currency') } elseif ($action == 'synchronize') { - $response = GETPOST('response'); - $response = json_decode($response); - - if ($response->success) - { - MultiCurrency::syncRates($response); - } - else - { - setEventMessages($langs->trans('multicurrency_syncronize_error', $response->error->info), null, 'errors'); - } + MultiCurrency::syncRates($conf->global->MULTICURRENCY_APP_ID); } @@ -175,6 +163,8 @@ if ($resql) * View */ +$form=new Form($db); + $page_name = "MultiCurrencySetup"; llxHeader('', $langs->trans($page_name)); @@ -187,21 +177,16 @@ print_fiche_titre($langs->trans($page_name), $linkback); $head = multicurrencyAdminPrepareHead(); dol_fiche_head($head, 'settings', $langs->trans("ModuleSetup"), -1, "multicurrency"); -// Setup page goes here -$form=new Form($db); -$var=false; print ''; print ''; print ''."\n"; -print ''; -print ''."\n"; - +print ''."\n"; +print ''; print ''; print ''; -print ''; -print ''; - print ''; print ''; -print ''; -print ''; print ''; print ''; -print ''; -print ''; print ''; print ''; -print ''; -print ''; */ print '
'.$langs->trans("Parameters").' '.$langs->trans("Value").''.$langs->trans("Value").'
'.$langs->transnoentitiesnoconv("MULTICURRENCY_USE_RATE_ON_DOCUMENT_DATE").' '; +print ''; print '
'; print ''; print ''; @@ -211,11 +196,9 @@ print '
'; print '
'.$langs->transnoentitiesnoconv("multicurrency_useOriginTx").' '; +print ''; print '
'; print ''; print ''; @@ -228,8 +211,7 @@ print '
'.$langs->transnoentitiesnoconv("multicurrency_buyPriceInCurrency").' '; +print ''; print ''; print ''; print ''; @@ -243,8 +225,7 @@ print '
'.$langs->transnoentitiesnoconv("multicurrency_modifyRateApplication").' '; +print ''; print ''; print ''; print ''; @@ -256,16 +237,17 @@ print '
'; + print '
'; if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) { - $var=false; + print '
'; print ''; + print ''; print ''."\n"; - print ''; - print ''; - print ''; print ''; - print ''; - print ''; print ''; - print ''; - print ''; print ''; - print ''; - print ''; print '
'.$form->textwithpicto($langs->trans("CurrencyLayerAccount"), $langs->trans("CurrencyLayerAccount_help_to_synchronize")).' '; + print ''; print ''; print ''; print ''; @@ -274,11 +256,9 @@ if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) print '
'.$langs->transnoentitiesnoconv("multicurrency_appId").' '; + print ''; print ''; print ''; print ''; @@ -290,8 +270,7 @@ if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) print '
'.$langs->transnoentitiesnoconv("multicurrency_appCurrencySource").' '; + print ''; print ''; print ''; print ''; @@ -302,8 +281,7 @@ if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) print '
'.$langs->transnoentitiesnoconv("multicurrency_alternateCurrencySource").' '; + print ''; print ''; print ''; print ''; @@ -313,35 +291,35 @@ if (!empty($conf->global->MAIN_MULTICURRENCY_ALLOW_SYNCHRONIZATION)) print '
'; + print '
'; print '
'; } +print '
'; print ''; print ''; print ''."\n"; -print ''; -print ''."\n"; +print ''."\n"; +print ''; - -print ''; print ''; +print ''; +print ''; +print ''; -print ''; -print ''; - +print ''; +print ''; +print ''; print ''; print ''; -print ''; -print ''; +print ''; +print ''; foreach ($TCurrency as &$currency) { @@ -349,8 +327,7 @@ foreach ($TCurrency as &$currency) print ''; print ''; - print ''; - print ''; } print '
'.$form->textwithpicto($langs->trans("CurrenciesUsed"), $langs->transnoentitiesnoconv("CurrenciesUsed_help_to_add")).' '.$langs->trans("Rate").''.$langs->trans("Rate").'
'.$form->selectCurrency('', 'code').''; print ''; print ''; -print ''.$form->selectCurrency('', 'code').' '; print ' '; print ''; -print '
'.$conf->currency.$form->textwithpicto(' ', $langs->trans("BaseCurrency")).' 1'; -print '
1
'.$currency->code.' - '.$currency->name.' '; + print ''; print '
'; print ''; print ''; @@ -360,13 +337,11 @@ foreach ($TCurrency as &$currency) print ' '; print ''; print '
'; - print '
'; - - +print '
'; print ' '; + + +// Part to create +if ($action == 'create') +{ + print load_fiche_titre($langs->trans("NewAsset")); + + print '
'; + print ''; + print ''; + print ''; + + dol_fiche_head(array(), ''); + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + + print '
'."\n"; + + dol_fiche_end(); + + print '
'; + print ''; + print '  '; + print ''; // Cancel for create does not post form if we don't know the backtopage + print '
'; + + print '
'; +} + +// Part to edit record +if (($id || $ref) && $action == 'edit') +{ + print load_fiche_titre($langs->trans("Assets")); + + print '
'; + print ''; + print ''; + print ''; + print ''; + + dol_fiche_head(); + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + + print '
'; + + dol_fiche_end(); + + print '
'; + print '   '; + print '
'; + + print '
'; +} + +// Part to show record +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) +{ + $res = $object->fetch_optionals($object->id, $extralabels); + + $head = AssetsPrepareHead($object); + dol_fiche_head($head, 'card', $langs->trans("Asset"), -1, 'generic'); + + $formconfirm = ''; + + // Confirmation to delete + if ($action == 'delete') + { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteAssets'), $langs->trans('ConfirmDeleteAssets'), 'confirm_delete', '', 0, 1); + } + + // Confirmation of action xxxx + if ($action == 'xxx') + { + $formquestion=array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + } + + if (! $formconfirm) { + $parameters = array('lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $formconfirm.=$hookmanager->resPrint; + elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + + // Object card + // ------------------------------------------------------------ + $linkback = '' . $langs->trans("BackToList") . ''; + + $morehtmlref='
'; + /* + // Ref bis + $morehtmlref.=$form->editfieldkey("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->asset->creer, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefBis", 'ref_client', $object->ref_client, $object, $user->rights->asset->creer, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $soc->getNomUrl(1); + */ + $morehtmlref.='
'; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
'; + print '
'; + print '
'; + print ''."\n"; + + // Common attributes + //$keyforbreak='fieldkeytoswithonsecondcolumn'; + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
'; + print '
'; + print '
'; + print '
'; + + print '

'; + + dol_fiche_end(); + + + // Buttons for actions + if ($action != 'presend' && $action != 'editline') { + print '
'."\n"; + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + if (empty($reshook)) + { + // Send + print '' . $langs->trans('SendMail') . ''."\n"; + + if ($user->rights->asset->write) + { + print ''.$langs->trans("Modify").''."\n"; + } + else + { + print ''.$langs->trans('Modify').''."\n"; + } + + if ($user->rights->asset->delete) + { + print ''.$langs->trans('Delete').''."\n"; + } + else + { + print ''.$langs->trans('Delete').''."\n"; + } + } + print '
'."\n"; + } + + + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + if ($action != 'presend') + { + print '
'; + print ''; // ancre + + // Documents + /*$objref = dol_sanitizeFileName($object->ref); + $relativepath = $comref . '/' . $comref . '.pdf'; + $filedir = $conf->asset->dir_output . '/' . $objref; + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->asset->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->asset->create; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('asset', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + */ + + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('asset')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + + + print '
'; + + $MAXEVENT = 10; + + $morehtmlright = ''; + $morehtmlright.= $langs->trans("SeeAll"); + $morehtmlright.= ''; + + // List of actions on element + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'asset', $socid, 1, '', $MAXEVENT, '', $morehtmlright); + + print '
'; + } + + //Select mail models is same action as presend + /* + if (GETPOST('modelselected')) $action = 'presend'; + + // Presend form + $modelmail='inventory'; + $defaulttopic='InformationMessage'; + $diroutput = $conf->product->dir_output.'/inventory'; + $trackid = 'stockinv'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; + */ +} + + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/asset/class/asset.class.php b/htdocs/asset/class/asset.class.php new file mode 100644 index 00000000000..4ab05ce675c --- /dev/null +++ b/htdocs/asset/class/asset.class.php @@ -0,0 +1,464 @@ + + * Copyright (C) 2018 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 asset/class/asset.class.php + * \ingroup asset + * \brief This file is a CRUD class file for asset (Create/Read/Update/Delete) + */ + +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; +//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + +/** + * Class for Asset + */ +class Asset extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'asset'; + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'asset'; + /** + * @var int Does module support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 0; + /** + * @var int Does asset support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 1; + /** + * @var string String with name of icon for asset. Must be the part after the 'object_' into object_asset.png + */ + public $picto = 'asset'; + + + /** + * 'type' if the field format. + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'position' is the sort order of field. + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'help' is a string visible as a tooltip on field + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * 'showoncombobox' if field must be shown into the label of combobox + */ + + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields=array( + 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",), + 'ref' => array('type'=>'varchar(10)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object",), + 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>-1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,), + 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'notnull'=>-1, 'searchall'=>1, 'help'=>"Help text",), + 'amount_ht' => array('type'=>'double(24,8)', 'label'=>'AmountHTShort', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1, 'isameasure'=>'1', 'help'=>"Help text",), + 'amount_vat' => array('type'=>'double(24,8)', 'label'=>'AmountVAT', 'visible'=>1, 'enabled'=>1, 'position'=>40, 'notnull'=>-1, 'isameasure'=>'1', 'help'=>"Help text",), + 'fk_asset_type' => array('type'=>'integer:AssetType:asset/class/asset.class.php', 'label'=>'AssetsType', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'searchall'=>1, 'help'=>"LinkToThirparty",), + 'description' => array('type'=>'text', 'label'=>'Description', 'visible'=>-1, 'enabled'=>1, 'position'=>90, 'notnull'=>-1,), + 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'visible'=>-1, 'enabled'=>1, 'position'=>91, 'notnull'=>-1,), + 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'visible'=>-1, 'enabled'=>1, 'position'=>92, 'notnull'=>-1,), + 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'visible'=>-2, 'enabled'=>1, 'position'=>500, 'notnull'=>1,), + 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'visible'=>-2, 'enabled'=>1, 'position'=>501, 'notnull'=>1,), + 'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'visible'=>-2, 'enabled'=>1, 'position'=>510, 'notnull'=>1,), + 'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'visible'=>-2, 'enabled'=>1, 'position'=>511, 'notnull'=>-1,), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'visible'=>-2, 'enabled'=>1, 'position'=>1000, 'notnull'=>-1,), + 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>1, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Draft', '1'=>'Active', '-1'=>'Cancel')), + ); + public $rowid; + public $ref; + public $entity; + public $label; + public $amount; + public $fk_soc; + public $description; + public $note_public; + public $note_private; + public $date_creation; + public $tms; + public $fk_user_creat; + public $fk_user_modif; + public $import_key; + public $status; + + // If this object has a subtable with lines + + /** + * @var int Name of subtable line + */ + //public $table_element_line = 'assetdet'; + /** + * @var int Field with ID of parent key if this field has a parent + */ + //public $fk_element = 'fk_asset'; + /** + * @var int Name of subtable class that manage subtable lines + */ + //public $class_element_line = 'Assetline'; + /** + * @var array Array of child tables (child tables to delete before deleting a record) + */ + //protected $childtables=array('assetdet'); + /** + * @var AssetLine[] Array of subtable lines + */ + //public $lines = array(); + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf; + + $this->db = $db; + + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) $this->fields['rowid']['visible']=0; + if (empty($conf->multicompany->enabled)) $this->fields['entity']['enabled']=0; + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = false) + { + return $this->createCommon($user, $notrigger); + } + + /** + * Clone and object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $hookmanager, $langs; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $object->fetchCommon($fromid); + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + unset($object->import_key); + + // Clear fields + $object->ref = "copy_of_".$object->ref; + $object->title = $langs->trans("CopyOf")." ".$object->title; + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + if ($result < 0) { + $error++; + $this->error = $object->error; + $this->errors = $object->errors; + } + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $ref Ref + * @return int <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $ref = null) + { + $result = $this->fetchCommon($id, $ref); + //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines(); + return $result; + } + + /** + * Load object lines in memory from the database + * + * @return int <0 if KO, 0 if not found, >0 if OK + */ + /*public function fetchLines() + { + $this->lines=array(); + + // Load lines with object AssetsLine + + return count($this->lines)?1:0; + }*/ + + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = false) + { + return $this->deleteCommon($user, $notrigger); + } + + /** + * Return a link to the object card (with optionaly the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1) + { + global $db, $conf, $langs; + global $dolibarr_main_authentication, $dolibarr_main_demo; + global $menumanager; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + + $result = ''; + $companylink = ''; + + $label = '' . $langs->trans("Asset") . ''; + $label.= '
'; + $label.= '' . $langs->trans('Ref') . ': ' . $this->ref; + + $url = dol_buildpath('/assets/card.php',1).'?id='.$this->id; + + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + $linkclose=''; + if (empty($notooltip)) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowAssets"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + } + else $linkclose = ($morecss?' class="'.$morecss.'"':''); + + $linkstart = ''; + $linkend=''; + + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= $this->ref; + $result .= $linkend; + //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); + + return $result; + } + + /** + * Retourne le libelle du status d'un user (actif, inactif) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Label of status + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + if ($mode == 0) + { + $prefix=''; + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 1) + { + if ($status == 1) return $langs->trans('Enabled'); + if ($status == 0) return $langs->trans('Disabled'); + } + if ($mode == 2) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 3) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5'); + } + if ($mode == 4) + { + if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled'); + if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled'); + } + if ($mode == 5) + { + 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'); + } + } + + /** + * Charge les informations d'ordre info dans l'objet commande + * + * @param int $id Id of order + * @return void + */ + function info($id) + { + $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; + $sql.= ' fk_user_creat, fk_user_modif'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql.= ' WHERE t.rowid = '.$id; + $result=$this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + + if ($obj->fk_user_valid) + { + $vuser = new User($this->db); + $vuser->fetch($obj->fk_user_valid); + $this->user_validation = $vuser; + } + + if ($obj->fk_user_cloture) + { + $cluser = new User($this->db); + $cluser->fetch($obj->fk_user_cloture); + $this->user_cloture = $cluser; + } + + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->datem); + $this->date_validation = $this->db->jdate($obj->datev); + } + + $this->db->free($result); + + } + else + { + dol_print_error($this->db); + } + } + + /** + * Initialise object with example values + * Id must be 0 if object instance is a specimen + * + * @return void + */ + public function initAsSpecimen() + { + $this->initAsSpecimenCommon(); + } + + + /** + * Action executed by scheduler + * CAN BE A CRON TASK + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + global $conf, $langs; + + $this->output = ''; + $this->error=''; + + dol_syslog(__METHOD__, LOG_DEBUG); + + return 0; + } +} \ No newline at end of file diff --git a/htdocs/asset/class/asset_type.class.php b/htdocs/asset/class/asset_type.class.php new file mode 100644 index 00000000000..51ea3a0c799 --- /dev/null +++ b/htdocs/asset/class/asset_type.class.php @@ -0,0 +1,433 @@ + + * + * 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/asset/class/asset_type.class.php + * \ingroup asset + * \brief File of class to manage asset types + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; + + +/** + * Class to manage asset type + */ +class AssetType extends CommonObject +{ + public $table_element = 'asset_type'; + public $element = 'asset_type'; + public $picto = 'group'; + public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + + /** @var string Label */ + public $label; + /** @var string Accountancy code asset */ + public $accountancy_code_asset; + /** @var string Accountancy code depreciation asset */ + public $accountancy_code_depreciation_asset; + /** @var string Accountancy code depreciation expense */ + public $accountancy_code_depreciation_expense; + /** @var string Public note */ + public $note; + /** @var array Array of asset */ + public $asset=array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; + } + + + /** + * Fonction qui permet de creer le type d'immobilisation + * + * @param User $user User making creation + * @param int $notrigger 1=do not execute triggers, 0 otherwise + * @return int >0 if OK, < 0 if KO + */ + function create($user,$notrigger=0) + { + global $conf; + + $error=0; + + $this->label=trim($this->label); + $this->accountancy_code_asset = trim($this->accountancy_code_asset); + $this->accountancy_code_depreciation_asset = trim($this->accountancy_code_depreciation_asset); + $this->accountancy_code_depreciation_expense = trim($this->accountancy_code_depreciation_expense); + + $this->db->begin(); + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."asset_type ("; + $sql.= "label"; + $sql.= ", accountancy_code_asset"; + $sql.= ", accountancy_code_depreciation_asset"; + $sql.= ", accountancy_code_depreciation_expense"; + $sql.= ", entity"; + $sql.= ") VALUES ("; + $sql.= "'".$this->db->escape($this->label)."'"; + $sql.= ", '".$this->db->escape($this->accountancy_code_asset)."'"; + $sql.= ", '".$this->db->escape($this->accountancy_code_depreciation_asset)."'"; + $sql.= ", '".$this->db->escape($this->accountancy_code_depreciation_expense)."'"; + $sql.= ", ".$conf->entity; + $sql.= ")"; + + dol_syslog("Asset_type::create", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."asset_type"); + + $result = $this->update($user,1); + if ($result < 0) + { + $this->db->rollback(); + return -3; + } + + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ASSET_TYPE_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return $this->id; + } + else + { + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); + $this->db->rollback(); + return -2; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + + /** + * Met a jour en base donnees du type + * + * @param User $user Object user making change + * @param int $notrigger 1=do not execute triggers, 0 otherwise + * @return int >0 if OK, < 0 if KO + */ + function update($user,$notrigger=0) + { + global $conf, $hookmanager; + + $error=0; + + $this->label=trim($this->label); + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."asset_type "; + $sql.= "SET "; + $sql.= "label = '".$this->db->escape($this->label) ."',"; + $sql.= "accountancy_code_asset = '".$this->db->escape($this->accountancy_code_asset)."',"; + $sql.= "accountancy_code_depreciation_asset = '".$this->db->escape($this->accountancy_code_depreciation_asset)."',"; + $sql.= "accountancy_code_depreciation_expense = '".$this->db->escape($this->accountancy_code_depreciation_expense)."'"; + $sql.= " WHERE rowid =".$this->id; + + $result = $this->db->query($sql); + if ($result) + { + $action='update'; + + // Actions on extra fields + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ASSET_TYPE_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + return -$error; + } + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + + /** + * Fonction qui permet de supprimer le status de l'adherent + * + * @return int >0 if OK, 0 if not found, < 0 if KO + */ + function delete() + { + global $user; + + $error = 0; + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."asset_type"; + $sql.= " WHERE rowid = ".$this->id; + + $resql=$this->db->query($sql); + if ($resql) + { + // Call trigger + $result=$this->call_trigger('ASSET_TYPE_DELETE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -2; } + // End call triggers + + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Fonction qui permet de recuperer le status de l'immobilisation + * + * @param int $rowid Id of member type to load + * @return int <0 if KO, >0 if OK + */ + function fetch($rowid) + { + $sql = "SELECT d.rowid, d.label as label, d.accountancy_code_asset, d.accountancy_code_depreciation_asset, d.accountancy_code_depreciation_expense, d.note"; + $sql .= " FROM ".MAIN_DB_PREFIX."asset_type as d"; + $sql .= " WHERE d.rowid = ".(int) $rowid; + + dol_syslog("Asset_type::fetch", LOG_DEBUG); + + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + $this->label = $obj->label; + $this->accountancy_code_asset = $obj->accountancy_code_asset; + $this->accountancy_code_depreciation_asset = $obj->accountancy_code_depreciation_asset; + $this->accountancy_code_depreciation_expense = $obj->accountancy_code_depreciation_expense; + $this->note = $obj->note; + } + + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Return list of asset's type + * + * @return array List of types of members + */ + function liste_array() + { + global $conf,$langs; + + $assettypes = array(); + + $sql = "SELECT rowid, label as label"; + $sql.= " FROM ".MAIN_DB_PREFIX."asset_type"; + $sql.= " WHERE entity IN (".getEntity('asset_type').")"; + + $resql=$this->db->query($sql); + if ($resql) + { + $nump = $this->db->num_rows($resql); + + if ($nump) + { + $i = 0; + while ($i < $nump) + { + $obj = $this->db->fetch_object($resql); + + $assettypes[$obj->rowid] = $langs->trans($obj->label); + $i++; + } + } + } + else + { + print $this->db->error(); + } + return $assettypes; + } + + /** + * Return array of Asset objects for asset type this->id (or all if this->id not defined) + * + * @param string $excludefilter Filter to exclude + * @param int $mode 0=Return array of asset instance + * 1=Return array of asset instance without extra data + * 2=Return array of asset id only + * @return mixed Array of asset or -1 on error + */ + function listAssetForAssetType($excludefilter='', $mode=0) + { + global $conf, $user; + + $ret=array(); + + $sql = "SELECT a.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."asset as a"; + $sql.= " WHERE a.entity IN (".getEntity('asset').")"; + $sql.= " AND a.fk_asset_type = ".$this->id; + if (! empty($excludefilter)) $sql.=' AND ('.$excludefilter.')'; + + dol_syslog(get_class($this)."::listAssetsForGroup", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + while ($obj = $this->db->fetch_object($resql)) + { + if (! array_key_exists($obj->rowid, $ret)) + { + if ($mode < 2) + { + $assetstatic=new Asset($this->db); + if ($mode == 1) { + $assetstatic->fetch($obj->rowid,'','','',false, false); + } else { + $assetstatic->fetch($obj->rowid); + } + $ret[$obj->rowid]=$assetstatic; + } + else $ret[$obj->rowid]=$obj->rowid; + } + } + + $this->db->free($resql); + + $this->asset=$ret; + + return $ret; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlen length max label + * @param int $notooltip 1=Disable tooltip + * @return string String with URL + */ + function getNomUrl($withpicto=0, $maxlen=0, $notooltip=0) + { + global $langs; + + $result=''; + $label=$langs->trans("ShowTypeCard",$this->label); + + $linkstart = ''; + $linkend=''; + + $result .= $linkstart; + if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1); + if ($withpicto != 2) $result.= ($maxlen?dol_trunc($this->label,$maxlen):$this->label); + $result .= $linkend; + + return $result; + } + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + function initAsSpecimen() + { + global $conf, $user, $langs; + + // Initialize parameters + $this->id = 0; + $this->ref = 'ATSPEC'; + $this->specimen=1; + + $this->label='ASSET TYPE SPECIMEN'; + $this->note='This is a note'; + + // Assets of this asset type is just me + $this->asset=array( + $user->id => $user + ); + } + + /** + * getLibStatut + * + * @return string Return status of a type of asset + */ + function getLibStatut() + { + return ''; + } + +} diff --git a/htdocs/asset/document.php b/htdocs/asset/document.php new file mode 100644 index 00000000000..66baaae196c --- /dev/null +++ b/htdocs/asset/document.php @@ -0,0 +1,153 @@ + + * Copyright (C) 2018 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 document.php + * \ingroup asset + * \brief Tab for documents linked to Assets + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("assets","companies")); + + +$action=GETPOST('action','aZ09'); +$confirm=GETPOST('confirm'); +$id=(GETPOST('socid','int') ? GETPOST('socid','int') : GETPOST('id','int')); +$ref = GETPOST('ref', 'alpha'); + +// Security check - Protection if external user +//if ($user->societe_id > 0) access_forbidden(); +//if ($user->societe_id > 0) $socid = $user->societe_id; +//$result = restrictedArea($user, 'asset', $id); + +// Get parameters +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortorder) $sortorder="ASC"; +if (! $sortfield) $sortfield="name"; + +// Initialize technical objects +$object=new Asset($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->assets->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('assetdocument')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('asset'); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals + +//if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->id); +if ($id > 0 || ! empty($ref)) $upload_dir = $conf->sellyoursaas->multidir_output[$object->entity] . "/packages/" . dol_sanitizeFileName($object->ref); + + + +/* + * Actions + */ + +include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; + + +/* + * View + */ + +$form = new Form($db); + +$title=$langs->trans("Assets").' - '.$langs->trans("Files"); +$help_url=''; +//$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +llxHeader('', $title, $help_url); + +if ($object->id) +{ + /* + * Show tabs + */ + if (! empty($conf->notification->enabled)) $langs->load("mails"); + $head = AssetsPrepareHead($object); + + dol_fiche_head($head, 'document', $langs->trans("Asset"), -1, 'generic'); + + + // Construit liste des fichiers + $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); + $totalsize=0; + foreach($filearray as $key => $file) + { + $totalsize+=$file['size']; + } + + // Object card + // ------------------------------------------------------------ + $linkback = '' . $langs->trans("BackToList") . ''; + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + print '
'; + + print '
'; + print ''; + + // Number of files + print ''; + + // Total size + print ''; + + print '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'; + + print '
'; + + dol_fiche_end(); + + $modulepart = 'asset'; + //$permission = $user->rights->asset->create; + $permission = 1; + //$permtoedit = $user->rights->asset->create; + $permtoedit = 1; + $param = '&id=' . $object->id; + + //$relativepathwithnofile='asset/' . dol_sanitizeFileName($object->id).'/'; + $relativepathwithnofile='asset/' . dol_sanitizeFileName($object->ref).'/'; + + include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; +} +else +{ + accessforbidden('',0,0); +} + + +llxFooter(); +$db->close(); diff --git a/htdocs/asset/info.php b/htdocs/asset/info.php new file mode 100644 index 00000000000..71460f31a2c --- /dev/null +++ b/htdocs/asset/info.php @@ -0,0 +1,83 @@ + + * + * 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 info.php + * \ingroup asset + * \brief Page to show an asset information + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("asset")); + +$id = GETPOST('id','int'); +$ref=GETPOST('ref','alpha'); +$action=GETPOST('action','alpha'); + +// Security check +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'asset', $id, ''); + +$object = new Asset($db); +$object->fetch($id); + +/* + * Actions + */ + +/* + * View + */ +$title = $langs->trans('Asset') . " - " . $langs->trans('Info'); +$helpurl = ""; +llxHeader('', $title, $helpurl); + +$form = new Form($db); + +$object->info($id); + +$head = AssetsPrepareHead($object); + +dol_fiche_head($head, 'info', $langs->trans("Asset"), -1, 'generic'); + +$linkback = ''.$langs->trans("BackToList").''; + +$morehtmlref='
'; +$morehtmlref.='
'; + +dol_banner_tab($object, 'rowid', $linkback, 1, 'rowid', 'ref', $morehtmlref); + +print '
'; +print '
'; + +print '
'; + +print '
'; +dol_print_object_info($object); +print '
'; + +print '
'; + +dol_fiche_end(); + +llxFooter(); +$db->close(); diff --git a/htdocs/asset/list.php b/htdocs/asset/list.php new file mode 100644 index 00000000000..bcc2329f870 --- /dev/null +++ b/htdocs/asset/list.php @@ -0,0 +1,531 @@ + + * Copyright (C) 2018 Alexandre Spangaro + * Copyright (C) 2018 Ferran Marcet + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (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 list.php + * \ingroup asset + * \brief List page for asset + */ + +// Load Dolibarr environment +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.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.'/asset/class/asset.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("assets")); + +$action = GETPOST('action','alpha')?GETPOST('action','alpha'):'view'; // The action 'add', 'create', 'edit', 'update', 'view', ... +$massaction = GETPOST('massaction','alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOST('show_files','int'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm','alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'assetslist'; // To manage different context of search +$backtopage = GETPOST('backtopage','alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss','aZ'); // Option for the css output (always '' except when 'print') + +$id = GETPOST('id','int'); + +// Load variable for pagination +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST('sortfield','alpha'); +$sortorder = GETPOST('sortorder','alpha'); +$page = GETPOST('page','int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object=new Asset($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->asset->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('assetlist')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('asset'); +$search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (! $sortfield) $sortfield="t.".key($object->fields); // Set here default search field. By default 1st field in definition. +if (! $sortorder) $sortorder="ASC"; + +// Protection if external user +$socid=0; +if ($user->societe_id > 0) +{ + //$socid = $user->societe_id; + accessforbidden(); +} +//$result = restrictedArea($user, 'asset', $id,''); + +// Initialize array of search criterias +$search_all=trim(GETPOST("search_all",'alpha')); +$search=array(); +foreach($object->fields as $key => $val) +{ + if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach($object->fields as $key => $val) +{ + if ($val['searchall']) $fieldstosearchall['t.'.$key]=$val['label']; +} + +// Definition of fields for list +$arrayfields=array(); +foreach($object->fields as $key => $val) +{ + // If $val['visible']==0, then we never show the field + if (! empty($val['visible'])) $arrayfields['t.'.$key]=array('label'=>$val['label'], 'checked'=>(($val['visible']<0)?0:1), 'enabled'=>$val['enabled'], 'position'=>$val['position']); +} +// Extra fields +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) +{ + foreach($extrafields->attribute_label as $key => $val) + { + if (! empty($extrafields->attribute_list[$key])) $arrayfields["ef.".$key]=array('label'=>$extrafields->attribute_label[$key], 'checked'=>(($extrafields->attribute_list[$key]<0)?0:1), 'position'=>$extrafields->attribute_pos[$key], 'enabled'=>(abs($extrafields->attribute_list[$key])!=3 && $extrafields->attribute_perms[$key])); + } +} +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + + + +/* + * Actions + * + * Put here all code to do according to value of "$action" parameter + */ + +if (GETPOST('cancel','alpha')) { $action='list'; $massaction=''; } +if (! GETPOST('confirmmassaction','alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } + +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) +{ + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') ||GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers + { + foreach($object->fields as $key => $val) + { + $search[$key]=''; + } + $toselect=''; + $search_array_options=array(); + } + if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') + || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) + { + $massaction=''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass='Asset'; + $objectlabel='Asset'; + $permtoread = $user->rights->asset->read; + $permtodelete = $user->rights->asset->delete; + $uploaddir = $conf->asset->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + + + +/* + * View + * + * Put here all code to render page + */ + +$form=new Form($db); + +$now=dol_now(); + +//$help_url="EN:Module_Asset|FR:Module_Asset_FR|ES:Módulo_Asset"; +$help_url=''; +$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("Assets")); + + +// Build and execute select +// -------------------------------------------------------------------- +$sql = 'SELECT '; +foreach($object->fields as $key => $val) +{ + $sql.='t.'.$key.', '; +} +// Add fields from extrafields +foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); +// Add fields from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +$sql=preg_replace('/, $/','', $sql); +$sql.= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; +if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."assets_extrafields as ef on (t.rowid = ef.fk_object)"; +if ($object->ismultientitymanaged == 1) $sql.= " WHERE t.entity IN (".getEntity('assets').")"; +else $sql.=" WHERE 1 = 1"; +foreach($search as $key => $val) +{ + $mode_search=(($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key]))?1:0); + if ($search[$key] != '') $sql.=natural_search($key, $search[$key], (($key == 'status')?2:$mode_search)); +} +if ($search_all) $sql.= natural_search(array_keys($fieldstosearchall), $search_all); +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; + +/* If a group by is required +$sql.= " GROUP BY " +foreach($object->fields as $key => $val) +{ + $sql.='t.'.$key.', '; +} +// Add fields from extrafields +foreach ($extrafields->attribute_label as $key => $val) $sql.=($extrafields->attribute_type[$key] != 'separate' ? ",ef.".$key : ''); +// Add where from hooks +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters); // Note that $action and $object may have been modified by hook +$sql.=$hookmanager->resPrint; +*/ + +$sql.=$db->order($sortfield,$sortorder); + +// Count total nb of records +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } +} + +$sql.= $db->plimit($limit+1, $offset); + +$resql=$db->query($sql); +if (! $resql) +{ + 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.'/assets/card.php?id='.$id); + exit; +} + + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $title, $help_url); + +// Example : Adding jquery code +print ''; + +$arrayofselected=is_array($toselect)?$toselect:array(); + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); +foreach($search as $key => $val) +{ + $param.= '&search_'.$key.'='.urlencode($search[$key]); +} +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + +// List of mass actions available +$arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->asset->delete) $arrayofmassactions['predelete']=$langs->trans("Delete"); +if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + +print '
'; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit); + +// Add code for pre mass action (confirmation or email presend form) +$topicmail="SendAssetsRef"; +$modelmail="asset"; +$objecttmp=new Asset($db); +$trackid='xxxx'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $all) . join(', ',$fieldstosearchall).'
'; +} + +$moreforfilter = ''; +/*$moreforfilter.='
'; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
';*/ + +$parameters=array(); +$reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // 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 +$selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table +print ''."\n"; + + +// Fields title search +// -------------------------------------------------------------------- +print ''; +foreach($object->fields as $key => $val) +{ + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print ''; +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters=array('arrayfields'=>$arrayfields); +$reshook=$hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +// Action column +print ''; +print ''."\n"; + + +// Fields title label +// -------------------------------------------------------------------- +print ''; +foreach($object->fields as $key => $val) +{ + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align?'class="'.$align.'"':''), $sortfield, $sortorder, $align.' ')."\n"; +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); +$reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"],'','','','align="center"',$sortfield,$sortorder,'maxwidthsearch ')."\n"; +print ''."\n"; + + +// Detect if we need a fetch on each output line +$needToFetchEachLine=0; +foreach ($extrafields->attribute_computed as $key => $val) +{ + if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object +} + + +// Loop on record +// -------------------------------------------------------------------- +$i=0; +$totalarray=array(); +while ($i < min($num, $limit)) +{ + $obj = $db->fetch_object($resql); + if (empty($obj)) break; // Should not happen + + // Store properties in $object + $object->id = $obj->rowid; + foreach($object->fields as $key => $val) + { + if (isset($obj->$key)) $object->$key = $obj->$key; + } + + // Show here line of result + print ''; + foreach($object->fields as $key => $val) + { + $align=''; + if (in_array($val['type'], array('date','datetime','timestamp'))) $align.=($align?' ':'').'center'; + if (in_array($val['type'], array('timestamp'))) $align.=($align?' ':'').'nowrap'; + if ($key == 'status') $align.=($align?' ':'').'center'; + if (! empty($arrayfields['t.'.$key]['checked'])) + { + print ''; + print $object->showOutputField($val, $key, $obj->$key, ''); + print ''; + if (! $i) $totalarray['nbfield']++; + if (! empty($val['isameasure'])) + { + if (! $i) $totalarray['pos'][$totalarray['nbfield']]='t.'.$key; + $totalarray['val']['t.'.$key] += $obj->$key; + } + } + } + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // Fields from hook + $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + + print ''; + + $i++; +} + +// Show total line +if (isset($totalarray['pos'])) +{ + print ''; + $i=0; + while ($i < $totalarray['nbfield']) + { + $i++; + if (! empty($totalarray['pos'][$i])) print ''; + else + { + if ($i == 1) + { + if ($num < $limit) print ''; + else print ''; + } + else print ''; + } + } + print ''; +} + +// If no record found +if ($num == 0) +{ + $colspan=1; + foreach($arrayfields as $key => $val) { if (! empty($val['checked'])) $colspan++; } + print ''; +} + + +$db->free($resql); + +$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
'; +$searchpicto=$form->showFilterButtons(); +print $searchpicto; +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 '
'.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
'.$langs->trans("NoRecordFound").'
'."\n"; +print '
'."\n"; + +print '
'."\n"; + +if (in_array('builddoc',$arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) +{ + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) + { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); + + $filedir=$diroutputmassaction; + $genallowed=$user->rights->asset->read; + $delallowed=$user->rights->asset->create; + + print $formfile->showdocuments('massfilesarea_asset','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); + } + else + { + print '
'.$langs->trans("ShowTempMassFilesArea").''; + } +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/asset/note.php b/htdocs/asset/note.php new file mode 100644 index 00000000000..cf0166df96f --- /dev/null +++ b/htdocs/asset/note.php @@ -0,0 +1,149 @@ + + * Copyright (C) 2018 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 note.php + * \ingroup asset + * \brief Card with notes on Asset + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("asset","companies")); + +// Get parameters +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object=new Asset($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction=$conf->asset->dir_output . '/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array('assetnote')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extralabels = $extrafields->fetch_name_optionals_label('asset'); + +// Security check - Protection if external user +//if ($user->societe_id > 0) access_forbidden(); +//if ($user->societe_id > 0) $socid = $user->societe_id; +//$result = restrictedArea($user, 'asset', $id); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || ! empty($ref)) $upload_dir = $conf->asset->multidir_output[$object->entity] . "/" . $object->id; + +$permissionnote=1; +//$permissionnote=$user->rights->asset->creer; // Used by the include of actions_setnotes.inc.php + + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once + + +/* + * View + */ + +$form = new Form($db); + +//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; +$help_url=''; +llxHeader('',$langs->trans('Assets'),$help_url); + +if ($id > 0 || ! empty($ref)) +{ + $object->fetch_thirdparty(); + + $head = AssetsPrepareHead($object); + + dol_fiche_head($head, 'note', $langs->trans("Asset"), -1, 'generic'); + + // Object 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->asset->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 '
'; + + + $cssclass="titlefield"; + include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; + + print '
'; + + dol_fiche_end(); +} + + +llxFooter(); +$db->close(); diff --git a/htdocs/asset/type.php b/htdocs/asset/type.php new file mode 100644 index 00000000000..f4409ee5417 --- /dev/null +++ b/htdocs/asset/type.php @@ -0,0 +1,857 @@ + + * + * 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/asset/type.php + * \ingroup asset + * \brief Asset's type setup + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/asset/class/asset.class.php'; +require_once DOL_DOCUMENT_ROOT.'/asset/class/asset_type.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; + +// Load translation files required by the page +$langs->load("assets"); + +$rowid = GETPOST('rowid','int'); +$action = GETPOST('action','alpha'); +$cancel = GETPOST('cancel','alpha'); +$backtopage = GETPOST('backtopage','alpha'); + +$type = GETPOST('type','alpha'); + +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page ; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortorder) { $sortorder="DESC"; } +if (! $sortfield) { $sortfield="d.lastname"; } + +$label=GETPOST("label","alpha"); +$comment=GETPOST("comment"); + +// Security check +$result=restrictedArea($user,'asset',$rowid,'asset_type'); + +$object = new AssetType($db); + +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label('asset_type'); + +if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers +{ + $type=""; + $sall=""; +} + + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('assettypecard','globalcard')); + + +/* + * Actions + */ + +if ($cancel) { + + $action=''; + + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } +} + +if ($action == 'add' && $user->rights->asset->write) +{ + $object->label = trim($label); + $object->accountancy_code_asset = trim($accountancy_code_asset); + $object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset); + $object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense); + $object->note = trim($comment); + + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; + + if (empty($object->label)) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentities("Label")), null, 'errors'); + } + else { + $sql = "SELECT label FROM ".MAIN_DB_PREFIX."asset_type WHERE label='".$db->escape($object->label)."'"; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + } + if ($num) { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorLabelAlreadyExists",$login), null, 'errors'); + } + } + + if (! $error) + { + $id=$object->create($user); + if ($id > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; + } + } + else + { + $action = 'create'; + } +} + +if ($action == 'update' && $user->rights->asset->write) +{ + $object->fetch($rowid); + + $object->oldcopy = clone $object; + + $object->label = trim($label); + $object->accountancy_code_asset = trim($accountancy_code_asset); + $object->accountancy_code_depreciation_asset = trim($accountancy_code_depreciation_asset); + $object->accountancy_code_depreciation_expense = trim($accountancy_code_depreciation_expense); + $object->note = trim($comment); + + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + if ($ret < 0) $error++; + + $ret=$object->update($user); + + if ($ret >= 0 && ! count($object->errors)) + { + setEventMessages($langs->trans("AssetsTypeModified"), null, 'mesgs'); + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } + + header("Location: ".$_SERVER["PHP_SELF"]."?rowid=".$object->id); + exit; +} + +if ($action == 'confirm_delete' && $user->rights->asset->write) +{ + $object->fetch($rowid); + $res=$object->delete(); + + if ($res > 0) + { + setEventMessages($langs->trans("AssetsTypeDeleted"), null, 'mesgs'); + header("Location: ".$_SERVER["PHP_SELF"]); + exit; + } + else + { + setEventMessages($langs->trans("AssetsTypeCanNotBeDeleted"), null, 'errors'); + $action=''; + } +} + + +/* + * View + */ + +$form=new Form($db); +$helpurl=''; +llxHeader('',$langs->trans("AssetsTypeSetup"),$helpurl); + + +// List of asset type +if (! $rowid && $action != 'create' && $action != 'edit') +{ + //dol_fiche_head(''); + + $sql = "SELECT d.rowid, d.label as label, d.accountancy_code_asset, d.accountancy_code_depreciation_asset, d.accountancy_code_depreciation_expense, d.note"; + $sql.= " FROM ".MAIN_DB_PREFIX."asset_type as d"; + $sql.= " WHERE d.entity IN (".getEntity('asset_type').")"; + + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $nbtotalofrecords = $num; + + $i = 0; + + $param = ''; + + print '
'; + if ($optioncss != '') print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print_barre_liste($langs->trans("AssetsTypes"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic.png', 0, '', '', $limit); + + $moreforfilter = ''; + + print '
'; + print ''."\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $assettype = new AssetType($db); + + while ($i < $num) + { + $objp = $db->fetch_object($result); + + $assettype->id = $objp->rowid; + $assettype->ref = $objp->rowid; + $assettype->label = $objp->rowid; + + print ''; + print ''; + print ''; + + print ''; + + print ''; + + print ''; + + if ($user->rights->asset->write) + print ''; + else + print ''; + print ""; + $i++; + } + print "
'.$langs->trans("Ref").''.$langs->trans("Label").''.$langs->trans("AccountancyCodeAsset").''.$langs->trans("AccountancyCodeDepreciationAsset").''.$langs->trans("AccountancyCodeDepreciationExpense").' 
'; + print $assettype->getNomUrl(1); + //'.img_object($langs->trans("ShowType"),'group').' '.$objp->rowid.' + print ''.dol_escape_htmltag($objp->label).''; + if (! empty($conf->accounting->enabled)) + { + $accountingaccount = new AccountingAccount($db); + $accountingaccount->fetch('',$object->accountancy_code_asset,1); + + print $accountingaccount->getNomUrl(0,1,1,'',1); + } else { + print $object->accountancy_code_asset; + } + print ''; + if (! empty($conf->accounting->enabled)) + { + $accountingaccount2 = new AccountingAccount($db); + $accountingaccount2->fetch('',$object->accountancy_code_depreciation_asset,1); + + print $accountingaccount2->getNomUrl(0,1,1,'',1); + } else { + print $object->accountancy_code_depreciation_asset; + } + print ''; + if (! empty($conf->accounting->enabled)) + { + $accountingaccount3 = new AccountingAccount($db); + $accountingaccount3->fetch('',$object->accountancy_code_depreciation_expense,1); + + print $accountingaccount3->getNomUrl(0,1,1,'',1); + } else { + print $object->accountancy_code_depreciation_expense; + } + print 'rowid.'">'.img_edit().' 
"; + print '
'; + + print '
'; + } + else + { + dol_print_error($db); + } +} + + +/* ************************************************************************** */ +/* */ +/* Creation mode */ +/* */ +/* ************************************************************************** */ +if ($action == 'create') +{ + $object = new AssetType($db); + if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + + print load_fiche_titre($langs->trans("NewAssetType")); + + print '
'; + print ''; + print ''; + + dol_fiche_head(''); + + print ''; + print ''; + + print ''; + + if (! empty($conf->accounting->enabled)) + { + // Accountancy_code_asset + print ''; + print ''; + + // Accountancy_code_depreciation_expense + print ''; + print ''; + + // Accountancy_code_depreciation_expense + print ''; + print ''; + + } + else // For external software + { + // Accountancy_code_asset + print ''; + print ''; + + // Accountancy_code_depreciation_asset + print ''; + print ''; + + // Accountancy_code_depreciation_expense + print ''; + print ''; + } + + print ''; + + // Other attributes + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$act,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook)) + { + print $object->showOptionals($extrafields,'edit'); + } + print ''; + print "
'.$langs->trans("Label").'
'.$langs->trans("AccountancyCodeAsset").''; + print $formaccounting->select_account($object->accountancy_code_asset, 'accountancy_code_asset', 1, '', 1, 1); + print '
'.$langs->trans("AccountancyCodeDepreciationAsset").''; + print $formaccounting->select_account($object->accountancy_code_depreciation_asset, 'accountancy_code_depreciation_asset', 1, '', 1, 1); + print '
'.$langs->trans("AccountancyCodeDepreciationExpense").''; + print $formaccounting->select_account($object->accountancy_code_depreciation_expense, 'accountancy_code_depreciation_expense', 1, '', 1, 1); + print '
'.$langs->trans("AccountancyCodeAsset").''; + print '
'.$langs->trans("AccountancyCodeDepreciationAsset").''; + print '
'.$langs->trans("AccountancyCodeDepreciationExpense").''; + print '
'.$langs->trans("Description").''; + print '
\n"; + + dol_fiche_end(); + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + + print "
\n"; +} + +/* ************************************************************************** */ +/* */ +/* View mode */ +/* */ +/* ************************************************************************** */ +if ($rowid > 0) +{ + if ($action != 'edit') + { + $object = new AssetType($db); + $object->fetch($rowid); + $object->fetch_optionals(); + + /* + * Confirmation suppression + */ + if ($action == 'delete') + { + print $form->formconfirm($_SERVER['PHP_SELF']."?rowid=".$object->id,$langs->trans("DeleteAMemberType"),$langs->trans("ConfirmDeleteMemberType",$object->label),"confirm_delete", '',0,1); + } + + $head = asset_type_prepare_head($object); + + dol_fiche_head($head, 'card', $langs->trans("AssetType"), -1, 'setup'); + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'rowid', $linkback); + + print '
'; + print '
'; + + print ''; + + print ''; + if (! empty($conf->accounting->enabled)) + { + $accountingaccount = new AccountingAccount($db); + $accountingaccount->fetch('',$object->accountancy_code_asset,1); + + print $accountingaccount->getNomUrl(0,1,1,'',1); + } else { + print $object->accountancy_code_asset; + } + print ''; + + print ''; + + print ''; + + print '"; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
'; + if (! empty($conf->accounting->enabled)) + { + $accountingaccount2 = new AccountingAccount($db); + $accountingaccount2->fetch('',$object->accountancy_code_depreciation_asset,1); + + print $accountingaccount2->getNomUrl(0,1,1,'',1); + } else { + print $object->accountancy_code_depreciation_asset; + } + print ''; + if (! empty($conf->accounting->enabled)) + { + $accountingaccount3 = new AccountingAccount($db); + $accountingaccount3->fetch('',$object->accountancy_code_depreciation_expense,1); + + print $accountingaccount3->getNomUrl(0,1,1,'',1); + } else { + print $object->accountancy_code_depreciation_expense; + } + print '
'.$langs->trans("Description").''; + print nl2br($object->note)."
'; + print '
'; + + dol_fiche_end(); + + /* + * Buttons + */ + + print '
'; + + // Edit + if ($user->rights->asset->write) + { + print ''; + } + + // Add + print ''; + + // Delete + if ($user->rights->asset->write) + { + print ''; + } + + print "
"; + + + // Show list of assets (nearly same code than in page list.php) + $assettypestatic=new AssetType($db); + + $now=dol_now(); + + $sql = "SELECT a.rowid, d.login, d.firstname, d.lastname, d.societe, "; + $sql.= " d.datefin,"; + $sql.= " a.fk_asset_type as type_id,"; + $sql.= " t.label as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."asset as a, ".MAIN_DB_PREFIX."asset_type as t"; + $sql.= " WHERE a.fk_asset_type = t.rowid"; + $sql.= " AND a.entity IN (".getEntity('asset').")"; + $sql.= " AND t.rowid = ".$object->id; + if ($sall) + { + $sql.=natural_search(array("f.firstname","d.lastname","d.societe","d.email","d.login","d.address","d.town","d.note_public","d.note_private"), $sall); + } + if ($status != '') + { + $sql.= natural_search('d.statut', $status, 2); + } + if ($action == 'search') + { + if (GETPOST('search','alpha')) + { + $sql.= natural_search(array("d.firstname","d.lastname"), GETPOST('search','alpha')); + } + } + if (! empty($search_lastname)) + { + $sql.= natural_search(array("d.firstname","d.lastname"), $search_lastname); + } + if (! empty($search_login)) + { + $sql.= natural_search("d.login", $search_login); + } + if (! empty($search_email)) + { + $sql.= natural_search("d.email", $search_email); + } + if ($filter == 'uptodate') + { + $sql.=" AND datefin >= '".$db->idate($now)."'"; + } + if ($filter == 'outofdate') + { + $sql.=" AND datefin < '".$db->idate($now)."'"; + } + + $sql.= " ".$db->order($sortfield,$sortorder); + + // Count total nb of records + $nbtotalofrecords = ''; + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + { + $resql = $db->query($sql); + if ($resql) $nbtotalofrecords = $db->num_rows($result); + else dol_print_error($db); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } + } + + $sql.= " ".$db->plimit($conf->liste_limit+1, $offset); + + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + + $titre=$langs->trans("AssetsList"); + if ($status != '') + { + if ($status == '-1,1') { $titre=$langs->trans("MembersListQualified"); } + else if ($status == '-1') { $titre=$langs->trans("MembersListToValid"); } + else if ($status == '1' && ! $filter) { $titre=$langs->trans("MembersListValid"); } + else if ($status == '1' && $filter=='uptodate') { $titre=$langs->trans("MembersListUpToDate"); } + else if ($status == '1' && $filter=='outofdate') { $titre=$langs->trans("MembersListNotUpToDate"); } + else if ($status == '0') { $titre=$langs->trans("MembersListResiliated"); } + } + elseif ($action == 'search') + { + $titre=$langs->trans("MembersListQualified"); + } + + if ($type > 0) + { + $assettype=new AssetType($db); + $result=$assettype->fetch($type); + $titre.=" (".$assettype->label.")"; + } + + $param="&rowid=".$object->id; + if (! empty($status)) $param.="&status=".$status; + if (! empty($search_lastname)) $param.="&search_lastname=".$search_lastname; + if (! empty($search_firstname)) $param.="&search_firstname=".$search_firstname; + if (! empty($search_login)) $param.="&search_login=".$search_login; + if (! empty($search_email)) $param.="&search_email=".$search_email; + if (! empty($filter)) $param.="&filter=".$filter; + + if ($sall) + { + print $langs->trans("Filter")." (".$langs->trans("Lastname").", ".$langs->trans("Firstname").", ".$langs->trans("EMail").", ".$langs->trans("Address")." ".$langs->trans("or")." ".$langs->trans("Town")."): ".$sall; + } + + print '
'; + print '
'."\n"; + + // Lignes des champs de filtre + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + print "\n"; + + print ''; + print_liste_field_titre( $langs->trans("Name")." / ".$langs->trans("Company"),$_SERVER["PHP_SELF"],"d.lastname",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("Login",$_SERVER["PHP_SELF"],"d.login",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("Nature",$_SERVER["PHP_SELF"],"d.morphy",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("EMail",$_SERVER["PHP_SELF"],"d.email",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"d.statut,d.datefin",$param,"","",$sortfield,$sortorder); + print_liste_field_titre("EndSubscription",$_SERVER["PHP_SELF"],"d.datefin",$param,"",'align="center"',$sortfield,$sortorder); + print_liste_field_titre("Action",$_SERVER["PHP_SELF"],"",$param,"",'width="60" align="center"',$sortfield,$sortorder); + print "\n"; + + while ($i < $num && $i < $conf->liste_limit) + { + $objp = $db->fetch_object($resql); + + $datefin=$db->jdate($objp->datefin); + + $adh=new Asset($db); + $adh->lastname=$objp->lastname; + $adh->firstname=$objp->firstname; + + // Lastname + print ''; + if ($objp->societe != '') + { + print ''."\n"; + } + else + { + print ''."\n"; + } + + // Login + print "\n"; + + // Type + /*print ''; + */ + + // Moral/Physique + print "\n"; + + // EMail + print "\n"; + + // Statut + print '"; + + // Actions + print '"; + + print "\n"; + $i++; + } + + print "
'; + print ''; + print ' '; + print ' '; + print ''; + print '  '; + print ''; + print '
'.img_object($langs->trans("ShowMember"),"user").' '.$adh->getFullName($langs,0,-1,20).' / '.dol_trunc($objp->societe,12).''.img_object($langs->trans("ShowMember"),"user").' '.$adh->getFullName($langs,0,-1,32).'".$objp->login."'; + $assettypestatic->id=$objp->type_id; + $assettypestatic->label=$objp->type; + print $assettypestatic->getNomUrl(1,12); + print '".$adh->getmorphylib($objp->morphy)."".dol_print_email($objp->email,0,0,1)."'; + print $adh->LibStatut($objp->statut,$objp->subscription,$datefin,2); + print "'; + if ($user->rights->asset->creer) + { + print ''.img_edit().''; + } + print ' '; + if ($user->rights->asset->supprimer) + { + print ''.img_picto($langs->trans("Resiliate"),'disable.png').''; + } + print "
\n"; + print ''; + print ''; + + if ($num > $conf->liste_limit) + { + print_barre_liste('',$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords,''); + } + } + else + { + dol_print_error($db); + } + + } + + /* ************************************************************************** */ + /* */ + /* Edition mode */ + /* */ + /* ************************************************************************** */ + + if ($action == 'edit') + { + $object = new AssetType($db); + $object->fetch($rowid); + $object->fetch_optionals(); + if (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db); + + $head = asset_type_prepare_head($object); + + print '
'; + print ''; + print ''; + print ''; + + dol_fiche_head($head, 'card', $langs->trans("AssetsType"), -1, 'setup'); + + print ''; + + print ''; + + print ''; + + if (! empty($conf->accounting->enabled)) + { + // Accountancy_code_asset + print ''; + print ''; + + // Accountancy_code_depreciation_expense + print ''; + print ''; + + // Accountancy_code_depreciation_expense + print ''; + print ''; + + } + else // For external software + { + // Accountancy_code_asset + print ''; + print ''; + + // Accountancy_code_depreciation_asset + print ''; + print ''; + + // Accountancy_code_depreciation_expense + print ''; + print ''; + } + + print ''; + + // Other attributes + $parameters=array(); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$act,$action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook)) + { + print $object->showOptionals($extrafields,'edit'); + } + + print '
'.$langs->trans("Ref").''.$object->id.'
'.$langs->trans("Label").'
'.$langs->trans("AccountancyCodeAsset").''; + print $formaccounting->select_account($object->accountancy_code_asset, 'accountancy_code_asset', 1, '', 1, 1); + print '
'.$langs->trans("AccountancyCodeDepreciationAsset").''; + print $formaccounting->select_account($object->accountancy_code_depreciation_asset, 'accountancy_code_depreciation_asset', 1, '', 1, 1); + print '
'.$langs->trans("AccountancyCodeDepreciationExpense").''; + print $formaccounting->select_account($object->accountancy_code_depreciation_expense, 'accountancy_code_depreciation_expense', 1, '', 1, 1); + print '
'.$langs->trans("AccountancyCodeAsset").''; + print '
'.$langs->trans("AccountancyCodeDepreciationAsset").''; + print '
'.$langs->trans("AccountancyCodeDepreciationExpense").''; + print '
'.$langs->trans("Description").''; + print '
'; + + // Extra field + if (empty($reshook)) + { + print '

'; + foreach($extrafields->attribute_label as $key=>$label) + { + if (isset($_POST["options_" . $key])) { + if (is_array($_POST["options_" . $key])) { + // $_POST["options"] is an array but following code expects a comma separated string + $value = implode(",", $_POST["options_" . $key]); + } else { + $value = $_POST["options_" . $key]; + } + } else { + $value = $adht->array_options["options_" . $key]; + } + print '\n"; + } + print '
'.$label.''; + print $extrafields->showInputField($key,$value); + print "


'; + } + + dol_fiche_end(); + + print '
'; + print ''; + print '     '; + print ''; + print '
'; + + print "
"; + } +} + + +llxFooter(); + +$db->close(); diff --git a/htdocs/asterisk/wrapper.php b/htdocs/asterisk/wrapper.php index 69a9a96f032..8cd5ff979a0 100644 --- a/htdocs/asterisk/wrapper.php +++ b/htdocs/asterisk/wrapper.php @@ -28,8 +28,6 @@ * write = system,call,log,verbose,command,agent,user */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); diff --git a/htdocs/barcode/codeinit.php b/htdocs/barcode/codeinit.php index 5e684b4091d..26386052480 100644 --- a/htdocs/barcode/codeinit.php +++ b/htdocs/barcode/codeinit.php @@ -25,10 +25,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -$langs->load("admin"); -$langs->load("members"); -$langs->load("errors"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'members', 'errors', 'other')); // Choice of print year or current year. $now = dol_now(); @@ -212,7 +210,8 @@ if ($conf->societe->enabled) { $nbno=$nbtotal=0; - print load_fiche_titre($langs->trans("BarcodeInitForThirdparties"),'','object_company'); + print load_fiche_titre($langs->trans("BarcodeInitForThirdparties"),'','title_companies'); + print '
'."\n"; $sql="SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."societe where barcode IS NULL or barcode = ''"; $resql=$db->query($sql); @@ -253,7 +252,7 @@ if ($conf->product->enabled || $conf->product->service) $nbno=$nbtotal=0; - print load_fiche_titre($langs->trans("BarcodeInitForProductsOrServices"),'','object_product'); + print load_fiche_titre($langs->trans("BarcodeInitForProductsOrServices"),'','title_products'); print '
'."\n"; $sql ="SELECT count(rowid) as nb, fk_product_type, datec"; diff --git a/htdocs/barcode/printsheet.php b/htdocs/barcode/printsheet.php index 04a181d3613..7dfec76b39e 100644 --- a/htdocs/barcode/printsheet.php +++ b/htdocs/barcode/printsheet.php @@ -28,9 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/printsheet/modules_labels.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php'; -$langs->load("admin"); -$langs->load("members"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array('admin', 'members', 'errors')); // Choice of print year or current year. $now = dol_now(); diff --git a/htdocs/blockedlog/admin/blockedlog.php b/htdocs/blockedlog/admin/blockedlog.php index e4b38a9568f..326fea79c5d 100644 --- a/htdocs/blockedlog/admin/blockedlog.php +++ b/htdocs/blockedlog/admin/blockedlog.php @@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php'; require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +// Load translation files required by the page $langs->loadLangs(array("admin","other","blockedlog")); if (! $user->admin || empty($conf->blockedlog->enabled)) accessforbidden(); diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index e8b2dc8b73b..b93856b7af5 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/authority.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +// Load translation files required by the page $langs->loadLangs(array("admin", "other", "blockedlog", "bills")); if ((! $user->admin && ! $user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) accessforbidden(); @@ -116,10 +117,10 @@ else if (GETPOST('downloadcsv','alpha')) $sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data"; $sql.= " FROM ".MAIN_DB_PREFIX."blockedlog"; $sql.= " WHERE entity = ".$conf->entity; - if (GETPOST('yeartoexport','int') > 0) + if (GETPOST('monthtoexport','int') > 0 || GETPOST('yeartoexport','int') > 0) { - $dates = dol_get_first_day(GETPOST('yeartoexport','int'), 1); - $datee = dol_get_last_day(GETPOST('yeartoexport','int'), 12); + $dates = dol_get_first_day(GETPOST('yeartoexport','int'), GETPOST('monthtoexport','int')?GETPOST('monthtoexport','int'):1); + $datee = dol_get_last_day(GETPOST('yeartoexport','int'), GETPOST('monthtoexport','int')?GETPOST('monthtoexport','int'):12); $sql.= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'"; } $sql.= " ORDER BY rowid ASC"; // Required so we get the first one @@ -130,9 +131,16 @@ else if (GETPOST('downloadcsv','alpha')) { // Make the first fetch to get first line $obj = $db->fetch_object($res); - - $previoushash = $block_static->getPreviousHash(0, $obj->rowid); - $firstid = $obj->rowid; + if ($obj) + { + $previoushash = $block_static->getPreviousHash(0, $obj->rowid); + $firstid = $obj->rowid; + } + else + { // If not data found for filter, we do not need previoushash neither firstid + $previoushash = 'nodata'; + $firstid = ''; + } } else { @@ -143,14 +151,14 @@ else if (GETPOST('downloadcsv','alpha')) if (! $error) { - // Now restart request with all data + // Now restart request with all data = no limit(1) in sql request $sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data"; $sql.= " FROM ".MAIN_DB_PREFIX."blockedlog"; $sql.= " WHERE entity = ".$conf->entity; - if (GETPOST('yeartoexport','int') > 0) + if (GETPOST('monthtoexport','int') > 0 || GETPOST('yeartoexport','int') > 0) { - $dates = dol_get_first_day(GETPOST('yeartoexport','int'), 1); - $datee = dol_get_last_day(GETPOST('yeartoexport','int'), 12); + $dates = dol_get_first_day(GETPOST('yeartoexport','int'), GETPOST('monthtoexport','int')?GETPOST('monthtoexport','int'):1); + $datee = dol_get_last_day(GETPOST('yeartoexport','int'), GETPOST('monthtoexport','int')?GETPOST('monthtoexport','int'):12); $sql.= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'"; } $sql.= " ORDER BY rowid ASC"; // Required so later we can use the parameter $previoushash of checkSignature() @@ -160,7 +168,7 @@ else if (GETPOST('downloadcsv','alpha')) { header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); - header("Content-disposition: attachment; filename=\"unalterable-log-archive-" .$dolibarr_main_db_name."-".(GETPOST('yeartoexport','int')>0?GETPOST('yeartoexport','int').'-':'').$previoushash. ".csv\""); + header("Content-disposition: attachment; filename=\"unalterable-log-archive-" .$dolibarr_main_db_name."-".(GETPOST('yeartoexport','int')>0 ? GETPOST('yeartoexport','int').(GETPOST('monthtoexport','int')>0?sprintf("%02d",GETPOST('monthtoexport','int')):'').'-':'').$previoushash. ".csv\""); print $langs->transnoentities('Id') .';'.$langs->transnoentities('Date') @@ -320,7 +328,20 @@ print '
'; print $langs->trans("RestrictYearToExport").': '; -print ''; +$smonth=GETPOST('monthtoexport','int'); +// Month +$retstring=''; +$retstring.='"; +print $retstring; +print ''; print ''; print ''; if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY)) print ' | '.$langs->trans('DownloadBlockChain').''; @@ -359,7 +380,7 @@ print '
'; -print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); +print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); print ''; - //print $block->getUser() print $block->user_fullname; print ''.$block->ref_object.''.$object_link.''.price($block->amounts).''.img_info($langs->trans('ShowDetails')).''; - print $form->textwithpicto(dol_trunc($block->signature, '12'), $block->signature, 1, 'help', '', 0, 2, 'fingerprint'); + print ''; + print $form->textwithpicto(dol_trunc($block->signature, '8'), $block->signature, 1, 'help', '', 0, 2, 'fingerprint'.$block->id); print '
'; print ''; print ''; diff --git a/htdocs/bookmarks/card.php b/htdocs/bookmarks/card.php index 54512a8049e..d450e476506 100644 --- a/htdocs/bookmarks/card.php +++ b/htdocs/bookmarks/card.php @@ -27,8 +27,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/bookmarks/class/bookmark.class.php'; -$langs->load("bookmarks"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array('bookmarks', 'other')); // Security check if (! $user->rights->bookmark->lire) { diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index 2aa3024920f..ac5a89c66f3 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -24,8 +24,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/bookmarks/class/bookmark.class.php'; -$langs->load("bookmarks"); -$langs->load("admin"); +// Load translation files required by the page +$langs->loadLangs(array('bookmarks', 'admin')); $action=GETPOST('action','alpha'); $massaction=GETPOST('massaction','alpha'); @@ -81,7 +81,15 @@ $userstatic=new User($db); llxHeader('', $langs->trans("ListOfBookmarks")); -print load_fiche_titre($langs->trans("ListOfBookmarks")); +$newcardbutton=''; +if ($user->rights->bookmark->creer) +{ + $newcardbutton=''.$langs->trans('NewBookmark').''; + $newcardbutton.= ''; + $newcardbutton.= ''; +} + +print_barre_liste($langs->trans("ListOfBookmarks"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', -1, '', 'title_generic.png', 0, $newcardbutton); $sql = "SELECT b.rowid, b.dateb, b.fk_user, b.url, b.target, b.title, b.favicon, b.position,"; $sql.= " u.login, u.lastname, u.firstname"; @@ -117,12 +125,10 @@ if ($resql) print_liste_field_titre(''); print "\n"; - $var=True; while ($i < $num) { $obj = $db->fetch_object($resql); - print ''; // Id @@ -204,16 +210,6 @@ else } - -print "
\n"; - -if ($user->rights->bookmark->creer) -{ - print ''.$langs->trans("NewBookmark").''; -} - -print '
'; - llxFooter(); $db->close(); diff --git a/htdocs/cashdesk/admin/cashdesk.php b/htdocs/cashdesk/admin/cashdesk.php index 5a68b37caac..f4af16b3739 100644 --- a/htdocs/cashdesk/admin/cashdesk.php +++ b/htdocs/cashdesk/admin/cashdesk.php @@ -38,8 +38,8 @@ if (! empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("cashdesk"); +// Load translation files required by the page +$langs->loadLangs(array("admin", "cashdesk")); /* @@ -91,7 +91,6 @@ print '
'; // Mode -$var=true; print ''; print ''; print ''; @@ -162,7 +161,6 @@ if (! empty($conf->stock->enabled)) if (! empty($conf->service->enabled)) { - $var=! $var; print ''; print ''."\n"; print ''; -$var=true; $form = new Form($db); // Mail required for members @@ -123,4 +123,4 @@ print ''; print '
'.$langs->trans("Name").'
'; print $langs->trans("CashdeskShowServices"); print ''; @@ -173,7 +171,6 @@ if (! empty($conf->service->enabled)) // Use Dolibarr Receipt Printer if (! empty($conf->receiptprinter->enabled)) { - $var=! $var; print '
'; print $langs->trans("DolibarrReceiptPrinter").' ('.$langs->trans("FeatureNotYetAvailable").')'; print ''; diff --git a/htdocs/cashdesk/class/Facturation.class.php b/htdocs/cashdesk/class/Facturation.class.php index 8bfd1d3082c..a0e992e9da9 100644 --- a/htdocs/cashdesk/class/Facturation.class.php +++ b/htdocs/cashdesk/class/Facturation.class.php @@ -233,7 +233,7 @@ class Facturation $this->prix_total_localtax2 = $total_localtax2; $this->montant_tva = $total_ttc - $total_ht; - //print $this->prix_total_ttc.'eeee'; exit; + //print 'total: '.$this->prix_total_ttc; exit; } /** @@ -292,7 +292,7 @@ class Facturation else if ( $aId == 'RESET' ) { - $this->id = NULL; + $this->id = null; } else @@ -318,7 +318,7 @@ class Facturation } else if ( $aRef == 'RESET' ) { - $this->ref = NULL; + $this->ref = null; } else { @@ -342,7 +342,7 @@ class Facturation else if ( $aQte == 'RESET' ) { - $this->qte = NULL; + $this->qte = null; } else { @@ -366,7 +366,7 @@ class Facturation } else if ( $aStock == 'RESET' ) { - $this->stock = NULL; + $this->stock = null; } else { @@ -390,7 +390,7 @@ class Facturation } else if ($aRemisePercent == 'RESET') { - $this->remise_percent = NULL; + $this->remise_percent = null; } else { @@ -414,7 +414,7 @@ class Facturation } else if ( $aMontantRemise == 'RESET' ) { - $this->montant_remise = NULL; + $this->montant_remise = null; } else { @@ -439,7 +439,7 @@ class Facturation } else if ( $aPrix == 'RESET' ) { - $this->prix = NULL; + $this->prix = null; } else { @@ -463,7 +463,7 @@ class Facturation } else if ( $aTva == 'RESET' ) { - $this->tva = NULL; + $this->tva = null; } else { @@ -487,7 +487,7 @@ class Facturation } else if ( $aNumFacture == 'RESET' ) { - $this->num_facture = NULL; + $this->num_facture = null; } else { @@ -511,7 +511,7 @@ class Facturation } else if ( $aModeReglement == 'RESET' ) { - $this->mode_reglement = NULL; + $this->mode_reglement = null; } else { @@ -536,7 +536,7 @@ class Facturation } else if ( $aMontantEncaisse == 'RESET' ) { - $this->montant_encaisse = NULL; + $this->montant_encaisse = null; } else { @@ -560,7 +560,7 @@ class Facturation return $this->montant_rendu; } else if ( $aMontantRendu == 'RESET' ) { - $this->montant_rendu = NULL; + $this->montant_rendu = null; } else { @@ -584,7 +584,7 @@ class Facturation } else if ( $aPaiementLe == 'RESET' ) { - $this->paiement_le = NULL; + $this->paiement_le = null; } else { @@ -607,7 +607,7 @@ class Facturation } else if ( $aTotalHt == 'RESET' ) { - $this->prix_total_ht = NULL; + $this->prix_total_ht = null; } else { @@ -630,7 +630,7 @@ class Facturation } else if ( $aMontantTva == 'RESET' ) { - $this->montant_tva = NULL; + $this->montant_tva = null; } else { @@ -654,7 +654,7 @@ class Facturation } else if ( $aTotalTtc == 'RESET' ) { - $this->prix_total_ttc = NULL; + $this->prix_total_ttc = null; } else { diff --git a/htdocs/cashdesk/facturation_dhtml.php b/htdocs/cashdesk/facturation_dhtml.php index 72fbd509535..e1a1dcc6bc8 100644 --- a/htdocs/cashdesk/facturation_dhtml.php +++ b/htdocs/cashdesk/facturation_dhtml.php @@ -24,16 +24,12 @@ */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // Change this following line to use the correct relative path (../, ../../, etc) require '../main.inc.php'; diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index 399e2984ea8..431f921a1fb 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -324,7 +324,7 @@ switch ($action) { // We set status to payed $result=$invoice->set_paid($user); - //print 'eeeee';exit; + //print 'set paid';exit; } } diff --git a/htdocs/categories/admin/categorie.php b/htdocs/categories/admin/categorie.php index 518d8903edd..92e23a2199a 100644 --- a/htdocs/categories/admin/categorie.php +++ b/htdocs/categories/admin/categorie.php @@ -30,6 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; if (!$user->admin) accessforbidden(); +// Load translation files required by the page $langs->load("categories"); $action=GETPOST('action','aZ09'); @@ -93,7 +94,6 @@ print ' '.$langs->trans("Value").'
'; llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/categories/admin/categorie_extrafields.php b/htdocs/categories/admin/categorie_extrafields.php index 3e5a252264f..3fd7d1c69b5 100644 --- a/htdocs/categories/admin/categorie_extrafields.php +++ b/htdocs/categories/admin/categorie_extrafields.php @@ -28,8 +28,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("categories"); -$langs->load("admin"); +// Load translation files required by the page +$langs->loadLangs(array('categories', 'admin')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/categories/card.php b/htdocs/categories/card.php index 9f49e42f060..db56902347b 100644 --- a/htdocs/categories/card.php +++ b/htdocs/categories/card.php @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +// Load translation files required by the page $langs->load("categories"); // Security check @@ -268,7 +269,7 @@ if ($user->rights->categorie->creer) $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index 46332f9f979..c559d760f0f 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -172,7 +172,7 @@ class Categories extends DolibarrApi * @param array $request_data Request data * @return int ID of category */ - function post($request_data = NULL) + function post($request_data = null) { if(! DolibarrApiAccess::$user->rights->categorie->creer) { throw new RestException(401); @@ -197,7 +197,7 @@ class Categories extends DolibarrApi * @param array $request_data Datas * @return int */ - function put($id, $request_data = NULL) + function put($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->categorie->creer) { throw new RestException(401); diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index a8018e2c104..70b2108dd4c 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -236,7 +236,9 @@ class Categorie extends CommonObject $this->type = $res['type']; $this->entity = $res['entity']; - $this->fetch_optionals($this->id,null); + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); $this->db->free($resql); @@ -336,28 +338,23 @@ class Categorie extends CommonObject $action='create'; - // Actions on extra fields (by external module or standard code) - // TODO the hook duplicates the trigger !! - $hookmanager->initHooks(array('HookModuleNamedao')); - $parameters=array('socid'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) + // Actions on extra fields + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + $result=$this->insertExtraFields(); + if ($result < 0) { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } + $error++; } } - else if ($reshook < 0) $error++; - // Call trigger - $result=$this->call_trigger('CATEGORY_CREATE',$user); - if ($result < 0) { $error++; } - // End call triggers + if (! $error) + { + // Call trigger + $result=$this->call_trigger('CATEGORY_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } if ( ! $error ) { @@ -430,28 +427,23 @@ class Categorie extends CommonObject { $action='update'; - // Actions on extra fields (by external module or standard code) - // TODO the hook duplicates the trigger !! - $hookmanager->initHooks(array('HookCategorydao')); - $parameters=array(); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) + // Actions on extra fields + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + $result=$this->insertExtraFields(); + if ($result < 0) { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } + $error++; } } - else if ($reshook < 0) $error++; - // Call trigger - $result=$this->call_trigger('CATEGORY_MODIFY',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers + if (! $error) + { + // Call trigger + $result=$this->call_trigger('CATEGORY_MODIFY',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers + } $this->db->commit(); @@ -651,18 +643,6 @@ class Categorie extends CommonObject if ($this->id == -1) return -2; - // For backward compatibility - if ($type == 'societe') - { - $type = 'customer'; - dol_syslog(get_class($this) . "::add_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING); - } - elseif ($type == 'fournisseur') - { - $type = 'supplier'; - dol_syslog(get_class($this) . "::add_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING); - } - $this->db->begin(); $sql = "INSERT INTO " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type]; @@ -713,11 +693,11 @@ class Categorie extends CommonObject } } - // Save object we want to link category to into category instance to provide information to trigger - $this->linkto=$obj; + // Call trigger - $result=$this->call_trigger('CATEGORY_LINK',$user); + $this->context=array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger + $result=$this->call_trigger('CATEGORY_LINK',$user); if ($result < 0) { $error++; } // End call triggers @@ -781,11 +761,9 @@ class Categorie extends CommonObject dol_syslog(get_class($this).'::del_type', LOG_DEBUG); if ($this->db->query($sql)) { - // Save object we want to unlink category off into category instance to provide information to trigger - $this->unlinkoff=$obj; - // Call trigger - $result=$this->call_trigger('CATEGORY_UNLINK',$user); + $this->context=array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger + $result=$this->call_trigger('CATEGORY_UNLINK',$user); if ($result < 0) { $error++; } // End call triggers @@ -915,24 +893,23 @@ class Categorie extends CommonObject $sql.= ' AND s.rowid = sub.fk_categorie'; $sql.= ' AND sub.'.$subcol_name.' = '.$id; + $sql.= $this->db->order($sortfield, $sortorder); + + $offset = 0; $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $this->db->query($sql); $nbtotalofrecords = $this->db->num_rows($result); - } - - $sql.= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 { $page = 0; + $offset = 0; } - $offset = $limit * $page; - - $sql.= $this->db->plimit($limit + 1, $offset); } + $sql.= $this->db->plimit($limit + 1, $offset); + $result = $this->db->query($sql); if ($result) { @@ -1229,30 +1206,6 @@ class Categorie extends CommonObject } } - /** - * Returns total number of categories - * - * @return int Number of categories - * @deprecated function not used ? - */ - function get_nb_categories() - { - $sql = "SELECT count(rowid)"; - $sql.= " FROM ".MAIN_DB_PREFIX."categorie"; - $sql.= " WHERE entity IN (".getEntity('category').")"; - $res = $this->db->query($sql); - if ($res) - { - $res = $this->db->fetch_array($res); - return $res[0]; - } - else - { - dol_print_error($this->db); - return -1; - } - } - /** * Check if no category with same label already exists for this cat's parent or root and for this cat's type * diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index 4ccd9116d74..b420847f6fd 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +// Load translation files required by the page $langs->load("categories"); $id=GETPOST('id','int'); @@ -176,7 +177,7 @@ print '
'; print ''; print ''; print ''; -print ''; /* // faire une rech dans une sous categorie uniquement @@ -111,7 +112,6 @@ if ($catname || $id > 0) print '
'.$langs->trans("Search").'
'; +print '
'; print $langs->trans("Name").':
'; print ''; - $var=true; foreach ($cats as $cat) { print "\t".''."\n"; diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index e6047ed2149..472a8eb9b95 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -32,8 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; -$langs->load("categories"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadlangs(array('categories', 'bills')); $id=GETPOST('id','int'); diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 40b40eab921..7d71b43a81b 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -32,8 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -$langs->load("categories"); -$langs->load("languages"); +// Load translation files required by the page +$langs->loadLangs(array('categories', 'languages')); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index c613190588a..24e70e7d587 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; - +// Load translation files required by the page $langs->load("categories"); $id = GETPOST('id','int'); @@ -53,11 +53,12 @@ $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); $result=$object->fetch($id, $label); -$object->fetch_optionals($id,$extralabels); -if ($result <= 0) -{ - dol_print_error($db,$object->error); - exit; +if ($result <= 0) { + dol_print_error($db,$object->error); exit; +} +$object->fetch_optionals(); +if ($result <= 0) { + dol_print_error($db,$object->error); exit; } $type=$object->type; @@ -67,13 +68,14 @@ $extrafields = new ExtraFields($db); $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('categorycard')); +$hookmanager->initHooks(array('categorycard','globalcard')); /* * Actions */ - +$parameters=array(); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks // Remove element from category if ($id > 0 && $removeelem > 0) { @@ -353,7 +355,7 @@ if ($type == Categorie::TYPE_PRODUCT) print "
"; print "
'.$langs->trans("FoundCats").'
\n"; - print '\n"; + print '\n"; if (count($prods) > 0) { @@ -366,13 +368,12 @@ if ($type == Categorie::TYPE_PRODUCT) print '\n"; // Link to delete from category print ''; print ''; @@ -1984,11 +2004,11 @@ if ($action == 'create') if (! empty($conf->commande->enabled)) print ' (' . $langs->trans('AfterOrder') . ')'; print ''; - if ($action != 'editavailability' && ! empty($object->brouillon)) + if ($action != 'editavailability' && ! empty($object->brouillon) && $usercancreate) print ''; print '
'.$langs->trans("ProductsAndServices")."
'.$langs->trans("ProductsAndServices")." (".count($prods).")
'.$prod->label."'; - $typeid=$object->type; $permission=0; - if ($typeid == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($typeid == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($typeid == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; if ($permission) { print ""; @@ -402,7 +403,7 @@ if ($type == Categorie::TYPE_SUPPLIER) { print "
"; print ''."\n"; - print '\n"; + print '\n"; if (count($socs) > 0) { @@ -414,13 +415,12 @@ if ($type == Categorie::TYPE_SUPPLIER) print "\n"; // Link to delete from category print ''; @@ -169,14 +165,12 @@ if ($result) $num = $db->num_rows($result); if ($num > 0) - { - $var = true; + { $i = 0; - while ($i < $num ) + while ($i < $num ) { $obj = $db->fetch_object($result); - print ''; print ''; diff --git a/htdocs/comm/mailing/info.php b/htdocs/comm/mailing/info.php index ddb0d4a8fc6..b4f2eaeb6f3 100644 --- a/htdocs/comm/mailing/info.php +++ b/htdocs/comm/mailing/info.php @@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php'; $id=GETPOST('id'); +// Load translation files required by the page $langs->load("mails"); // Security check diff --git a/htdocs/comm/mailing/list.php b/htdocs/comm/mailing/list.php index f2491b09336..87a390d4006 100644 --- a/htdocs/comm/mailing/list.php +++ b/htdocs/comm/mailing/list.php @@ -25,6 +25,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php'; +// Load translation files required by the page $langs->load("mails"); // Security check @@ -32,7 +33,7 @@ $result=restrictedArea($user,'mailing'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $page = GETPOST("page",'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; @@ -103,12 +104,19 @@ if ($result) $title=$langs->trans("ListOfEMailings"); if ($filteremail) $title.=' ('.$langs->trans("SentTo",$filteremail).')'; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"],"",$sortfield,$sortorder,"",$num); + + $newcardbutton=''; + if ($user->rights->mailing->creer) + { + $newcardbutton=''.$langs->trans('NewMailing').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } $i = 0; - $param = "&sall=".urlencode($sall); - if ($filteremail) $param.='&filteremail='.urlencode($filteremail); + $param = "&sall=".urlencode($sall); + if ($filteremail) $param.='&filteremail='.urlencode($filteremail); print ''; if ($optioncss != '') print ''; @@ -118,7 +126,9 @@ if ($result) print ''; print ''; - $moreforfilter = ''; + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '',$num, '', 'title_generic.png', 0, $newcardbutton); + + $moreforfilter = ''; print '
'; print '
'.$langs->trans("Suppliers")."
'.$langs->trans("Suppliers")." (".count($socs).")
'; - $typeid=$object->type; $permission=0; - if ($typeid == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($typeid == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($typeid == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; if ($permission) { print ""; @@ -451,7 +451,7 @@ if($type == Categorie::TYPE_CUSTOMER) { print "
"; print ''."\n"; - print '\n"; + print '\n"; if (count($socs) > 0) { @@ -468,13 +468,12 @@ if($type == Categorie::TYPE_CUSTOMER) print "\n"; // Link to delete from category print ''; print ''."\n"; - print ''; + if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + print ''; + } + else { + print ''; + } print ''."\n"; print ''."\n"; $i++; @@ -843,7 +851,12 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) print ''; print ''."\n"; - print ''; + if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + print ''; + } + else { + print ''; + } print ''."\n"; print ''."\n"; $i++; diff --git a/htdocs/comm/mailing/advtargetemailing.php b/htdocs/comm/mailing/advtargetemailing.php index cfafdaa725b..1c886e2ba2c 100644 --- a/htdocs/comm/mailing/advtargetemailing.php +++ b/htdocs/comm/mailing/advtargetemailing.php @@ -34,9 +34,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/modules/mailings/advthirdparties.modules require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; -// Translations -$langs->load("mails"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('mails', 'companies')); if (! empty($conf->categorie->enabled)) { $langs->load("categories"); } @@ -73,13 +72,13 @@ if (GETPOST('button_removefilter_x','alpha')) { $search_prenom = ''; $search_email = ''; } - $array_query = array (); - $object = new Mailing($db); $advTarget = new AdvanceTargetingMailing($db); + if (empty($template_id)) { - $advTarget->fk_mailing = $id; + $advTarget->fk_element = $id; + $advTarget->type_element = 'mailing'; $result = $advTarget->fetch_by_mailing(); } else { $result = $advTarget->fetch($template_id); @@ -223,7 +222,7 @@ if ($action == 'add') { } else { $advTarget->contact_lines = array (); } - + if ((count($advTarget->thirdparty_lines) > 0) || (count($advTarget->contact_lines) > 0)) { // Add targets into database $obj = new mailing_advthirdparties($db); @@ -237,6 +236,7 @@ if ($action == 'add') { if (! empty($template_id)) { $query_temlate_id = '&template_id=' . $template_id; } + setEventMessages($langs->trans("XTargetsAdded",$result), null, 'mesgs'); header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $id . $query_temlate_id); exit(); } @@ -356,6 +356,7 @@ if ($action == 'savefilter' || $action == 'createfilter') { setEventMessage($advTarget->error, 'errors'); } } elseif ($action == 'savefilter') { + $result = $advTarget->update($user); if ($result < 0) { setEventMessage($advTarget->error, 'errors'); @@ -409,36 +410,7 @@ if ($_POST["button_removefilter"]) { llxHeader('', $langs->trans("MailAdvTargetRecipients")); -print ''; $form = new Form($db); $formadvtargetemaling = new FormAdvTargetEmailing($db); @@ -490,489 +462,11 @@ if ($object->fetch($id) >= 0) { // Show email selectors if ($object->statut == 0 && $user->rights->mailing->creer) { - print_fiche_titre($langs->trans("AdvTgtTitle")); - - print '
' . "\n"; - print '
' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '
'.$langs->trans("Customers")."
'.$langs->trans("Customers")." (".count($socs).")
'; - $typeid=$object->type; $permission=0; - if ($typeid == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($typeid == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($typeid == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; if ($permission) { print ""; @@ -507,7 +506,7 @@ if ($type == Categorie::TYPE_MEMBER) { print "
"; print "\n"; - print '\n"; + print '\n"; if (count($prods) > 0) { @@ -522,13 +521,12 @@ if ($type == Categorie::TYPE_MEMBER) print '\n"; // Link to delete from category print ''; print ''; - $var = true; if ($num > 0) { $i = 0; @@ -349,7 +344,12 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) $companystatic->canvas=$obj->canvas; print $companystatic->getNomUrl(1,'customer',16); print ''; - print ''; + if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + print ''; + } + else { + print ''; + } $i++; $total += $obj->total_ttc; } @@ -406,7 +406,6 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande print ''; print ''; - $var = true; if ($num > 0) { $i = 0; @@ -432,7 +431,12 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande $companystatic->canvas=$obj->canvas; print $companystatic->getNomUrl(1,'supplier',16); print ''; - print ''; + if(! empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { + print ''; + } + else { + print ''; + } $i++; $total += $obj->total_ttc; } @@ -518,7 +522,6 @@ if (! empty($conf->societe->enabled) && $user->rights->societe->lire) print ''; $i++; - } $db->free($resql); @@ -676,8 +679,8 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) { $langs->load("propal"); - $sql = "SELECT s.nom as name, s.rowid, p.rowid as propalid, p.total as total_ttc, p.total_ht, p.tva as total_tva, p.ref, p.ref_client, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; - $sql.= ", s.code_client"; + $sql = "SELECT s.nom as name, s.rowid, s.code_client"; + $sql.= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.tva as total_tva, p.ref, p.ref_client, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."propal as p"; if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -726,7 +729,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) print ''; print '
'.$langs->trans("Member")."
'.$langs->trans("Member")." (".count($prods).")
'.$member->firstname."'; - $typeid=$object->type; $permission=0; - if ($typeid == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($typeid == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($typeid == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; if ($permission) { print ""; @@ -558,7 +556,7 @@ if ($type == Categorie::TYPE_CONTACT) { print "
"; print ''."\n"; - print '\n"; + print '\n"; if (count($contacts) > 0) { @@ -573,14 +571,12 @@ if ($type == Categorie::TYPE_CONTACT) print "\n"; // Link to delete from category print ''; print "\n"; - $var=True; $i = 0; while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); - - print ''; print ''; diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index 91004c86f67..e90a821b5e3 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -37,8 +37,8 @@ if (! empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn if (! $user->rights->societe->lire) accessforbidden(); -$langs->load("commercial"); -$langs->load("propal"); +// Load translation files required by the page +$langs->loadLangs(array("commercial", "propal")); $action=GETPOST('action', 'alpha'); $bid=GETPOST('bid', 'int'); @@ -161,7 +161,6 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) print ''; print ''; - $var=true; if ($num > 0) { $i = 0; @@ -228,7 +227,7 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos if (! $user->rights->societe->client->voir && ! $socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE p.fk_statut = 0"; $sql.= " AND p.fk_soc = s.rowid"; - $sql.= " AND p.entity IN (".getEntity('propal').")"; + $sql.= " AND p.entity IN (".getEntity('supplier_proposal').")"; if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid) $sql.= " AND s.rowid = ".$socid; @@ -243,7 +242,6 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos print ''; print ''; - $var=true; if ($num > 0) { $i = 0; @@ -266,7 +264,7 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas=$obj->canvas; - print $companystatic->getNomUrl(1,'customer',16); + print $companystatic->getNomUrl(1,'supplier',16); print ''; print ''; $i++; @@ -274,13 +272,11 @@ if (! empty($conf->supplier_proposal->enabled) && $user->rights->supplier_propos } if ($total>0) { - print '"; } } else { - print ''; } print "
'.$langs->trans("Contact")."
'.$langs->trans("Contact")." (".count($contacts).")
'; - $typeid=$object->type; $permission=0; - if ($typeid == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($typeid == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($typeid == Categorie::TYPE_CONTACT) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; if ($permission) { print ""; @@ -613,7 +609,7 @@ if ($type == Categorie::TYPE_ACCOUNT) { print "
"; print "\n"; - print '\n"; + print '\n"; if (count($accounts) > 0) { @@ -627,14 +623,12 @@ if ($type == Categorie::TYPE_ACCOUNT) print '\n"; // Link to delete from category print ''; print "\n"; - $var=true; while ($i < min($num,$limit)) { $obj=$db->fetch_object($resql); diff --git a/htdocs/comm/address.php b/htdocs/comm/address.php index 6547f453b21..9c8b275d198 100644 --- a/htdocs/comm/address.php +++ b/htdocs/comm/address.php @@ -28,8 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/address.class.php'; -$langs->load("companies"); -$langs->load("commercial"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'commercial')); $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); diff --git a/htdocs/comm/admin/propal_extrafields.php b/htdocs/comm/admin/propal_extrafields.php index 3c95c39c88d..6a6aa12862a 100644 --- a/htdocs/comm/admin/propal_extrafields.php +++ b/htdocs/comm/admin/propal_extrafields.php @@ -28,9 +28,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("admin"); -$langs->load('propal'); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'admin', 'propal')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/comm/admin/propaldet_extrafields.php b/htdocs/comm/admin/propaldet_extrafields.php index 9c85504d458..49784228fe6 100644 --- a/htdocs/comm/admin/propaldet_extrafields.php +++ b/htdocs/comm/admin/propaldet_extrafields.php @@ -35,9 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) accessforbidden(); -$langs->load("admin"); -$langs->load("other"); -$langs->load("propal"); +// Load translation files required by the page +$langs->loadlangs(array('admin', 'other', 'propal')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 2495d512c55..83db0e0f1d2 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -45,8 +45,8 @@ if (! empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/c if (! empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; if (! empty($conf->ficheinter->enabled)) require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; -$langs->load("companies"); -$langs->load('banks'); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'banks')); if (! empty($conf->contrat->enabled)) $langs->load("contracts"); if (! empty($conf->commande->enabled)) $langs->load("orders"); @@ -82,7 +82,7 @@ $extrafields = new ExtraFields($db); $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('commcard','globalcard')); +$hookmanager->initHooks(array('thirdpartycomm','globalcard')); /* @@ -177,16 +177,27 @@ if (empty($reshook)) if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); } + // update order min amount + if ($action == 'setorder_min_amount') + { + $object->fetch($id); + $object->order_min_amount=GETPOST('order_min_amount'); + $result=$object->update($object->id, $user); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + } + if ($action == 'update_extras') { $object->fetch($id); + $object->oldcopy = dol_clone($object); + // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none')); if ($ret < 0) $error++; if (! $error) { - $result = $object->insertExtraFields(); + $result = $object->insertExtraFields('COMPANY_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -211,7 +222,7 @@ if ($id > 0 && empty($object->id)) { // Load data of third party $res=$object->fetch($id); - if ($object->id <= 0) dol_print_error($db,$object->error,$object->errors); + if ($object->id < 0) dol_print_error($db, $object->error, $object->errors); } $title=$langs->trans("CustomerCard"); @@ -220,7 +231,7 @@ $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('',$title,$help_url); -if ($id > 0) +if ($object->id > 0) { $head = societe_prepare_head($object); @@ -267,29 +278,38 @@ if ($id > 0) print ''; } + // This fields are used to know VAT to include in an invoice when the thirdparty is making a sale, so when it is a supplier. + // We don't need them into customer profile. + // Except for spain and localtax where localtax depends on buyer and not seller + // VAT is used + /* print ''; - print ''; + print ''; print ''; print ''; + */ - // Local Taxes - // TODO Move this on same record than VATIsUsed - if ($mysoc->localtax1_assuj=="1") + if ($mysoc->country_code == 'ES') { - print ''; + // Local Taxes + if ($mysoc->localtax1_assuj=="1") + { + print ''; + } + if ($mysoc->localtax1_assuj=="1") + { + print ''; + } } - if ($mysoc->localtax1_assuj=="1") - { - print ''; - } - // TVA Intra print ''; + print ''; + + print ''; + print ''; print ''; } + // Multiprice level - if (! empty($conf->global->PRODUIT_MULTIPRICES)) + if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print '
'.$langs->trans("Account")."
'.$langs->trans("Account")." (".count($accounts).")
'.$account->number."'; - $typeid=$object->type; $permission=0; - if ($typeid == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($typeid == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($typeid == Categorie::TYPE_ACCOUNT) $permission=$user->rights->banque->configurer; - if ($typeid == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; if ($permission) { print ""; @@ -666,7 +660,7 @@ if ($type == Categorie::TYPE_PROJECT) { print "
"; print "\n"; - print '\n"; + print '\n"; if (count($projects) > 0) { @@ -680,14 +674,12 @@ if ($type == Categorie::TYPE_PROJECT) print '\n"; // Link to delete from category print 'global->AGENDA_USE_EVENT_TYPE)?' class="fieldrequired"':'').'>'.$langs->trans("Title").''; + print ''; // Full day event print ''; @@ -1266,7 +1271,7 @@ if ($id > 0) $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } @@ -1297,7 +1302,7 @@ if ($id > 0) } $linkback =img_picto($langs->trans("BackToList"),'object_list','class="hideonsmartphone pictoactionview"'); - $linkback.= ''.$langs->trans("BackToList").''; + $linkback.= ''.$langs->trans("BackToList").''; // Link to other agenda views $out=''; @@ -1609,7 +1614,6 @@ if ($id > 0) $genallowed=$user->rights->agenda->myactions->read; $delallowed=$user->rights->agenda->myactions->create; - $var=true; print $formfile->showdocuments('agenda',$object->id,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,0,0,'','','',$object->default_lang); diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 1adcf7376c5..be8ad550b39 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -213,7 +213,7 @@ class ActionComm extends CommonObject $now=dol_now(); // Check parameters - if (empty($this->userownerid)) + if (! isset($this->userownerid) || $this->userownerid === '') // $this->userownerid may be 0 (anonymous event) of > 0 { dol_syslog("You tried to create an event but mandatory property ownerid was not defined", LOG_WARNING); $this->errors[]='ErrorPropertyUserowneridNotDefined'; @@ -281,6 +281,7 @@ class ActionComm extends CommonObject return -1; } } + $code = empty($this->code)?$this->type_code:$this->code; // Check parameters if (! $this->type_id) @@ -309,14 +310,15 @@ class ActionComm extends CommonObject $sql.= "transparency,"; $sql.= "fk_element,"; $sql.= "elementtype,"; - $sql.= "entity"; + $sql.= "entity,"; + $sql.= "extraparams"; $sql.= ") VALUES ("; $sql.= "'".$this->db->idate($now)."', "; $sql.= (strval($this->datep)!=''?"'".$this->db->idate($this->datep)."'":"null").", "; $sql.= (strval($this->datef)!=''?"'".$this->db->idate($this->datef)."'":"null").", "; $sql.= ((isset($this->durationp) && $this->durationp >= 0 && $this->durationp != '')?"'".$this->db->escape($this->durationp)."'":"null").", "; // deprecated $sql.= (isset($this->type_id)?$this->type_id:"null").","; - $sql.= (isset($this->type_code)?" '".$this->db->escape($this->type_code)."'":"null").", "; + $sql.= ($code?("'".$code."'"):"null").", "; $sql.= ((isset($this->socid) && $this->socid > 0) ? $this->socid:"null").", "; $sql.= ((isset($this->fk_project) && $this->fk_project > 0) ? $this->fk_project:"null").", "; $sql.= " '".$this->db->escape($this->note)."', "; @@ -328,7 +330,8 @@ class ActionComm extends CommonObject $sql.= "'".$this->db->escape($this->transparency)."', "; $sql.= (! empty($this->fk_element)?$this->fk_element:"null").", "; $sql.= (! empty($this->elementtype)?"'".$this->db->escape($this->elementtype)."'":"null").", "; - $sql.= $conf->entity; + $sql.= $conf->entity.","; + $sql.= (! empty($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null"); $sql.= ")"; dol_syslog(get_class($this)."::add", LOG_DEBUG); @@ -384,23 +387,15 @@ class ActionComm extends CommonObject { $action='create'; - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('actioncommdao')); - $parameters=array('actcomm'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + // Actions on extra fields + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } } - else if ($reshook < 0) $error++; } if (! $error && ! $notrigger) @@ -466,7 +461,10 @@ class ActionComm extends CommonObject // Load source object $objFrom = clone $this; + // Retreive all extrafield + // fetch optionals attributes and labels $this->fetch_optionals(); + // $this->fetch_userassigned(); $this->fetchResources(); @@ -589,7 +587,6 @@ class ActionComm extends CommonObject $this->label = $obj->label; $this->datep = $this->db->jdate($obj->datep); $this->datef = $this->db->jdate($obj->datep2); -// $this->durationp = $this->durationp; // deprecated $this->datec = $this->db->jdate($obj->datec); $this->datem = $this->db->jdate($obj->datem); @@ -623,7 +620,7 @@ class ActionComm extends CommonObject $this->contact->id = $obj->fk_contact; // deprecated $this->fk_element = $obj->elementid; - $this->elementid = $obj->elementid; + $this->elementid = $obj->elementid; $this->elementtype = $obj->elementtype; $this->fetchResources(); @@ -863,23 +860,15 @@ class ActionComm extends CommonObject { $action='update'; - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('actioncommdao')); - $parameters=array('actcomm'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) - { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + // Actions on extra fields + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } } - else if ($reshook < 0) $error++; // Now insert assignedusers if (! $error) @@ -1216,15 +1205,16 @@ class ActionComm extends CommonObject * Return URL of event * Use $this->id, $this->type_code, $this->label and $this->type_label * - * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto - * @param int $maxlength Max number of charaters into label. If negative, use the ref as label. - * @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 + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlength Max number of charaters into label. If negative, use the ref as label. + * @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 + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$maxlength=0,$classname='',$option='',$overwritepicto=0, $notooltip=0) + function getNomUrl($withpicto=0, $maxlength=0, $classname='', $option='', $overwritepicto=0, $notooltip=0, $save_lastsearch_value=-1) { global $conf, $langs, $user, $hookmanager, $action; @@ -1235,8 +1225,12 @@ class ActionComm extends CommonObject $result=''; - // Set label of typ - $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code)?$langs->transnoentities("Action".$this->type_code):$this->type_label; + // Set label of type + $labeltype = ''; + if ($this->type_code) + { + $labeltype = ($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code)?$langs->transnoentities("Action".$this->type_code):$this->type_label; + } if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { if ($this->type_code != 'AC_OTH_AUTO') $labeltype = $langs->trans('ActionAC_MANUAL'); @@ -1266,15 +1260,12 @@ class ActionComm extends CommonObject $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); + */ } else $linkclose.=' class="'.$classname.'"'; @@ -1283,12 +1274,19 @@ class ActionComm extends CommonObject $url = DOL_URL_ROOT.'/contact/perso.php?id='.$this->id; else $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$this->id; + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } $linkstart = ''; $linkend=''; - //print 'rrr'.$this->libelle.'-'.$withpicto; + //print 'rrr'.$this->libelle.'rrr'.$this->label.'rrr'.$withpicto; if ($withpicto == 2) { @@ -1308,7 +1306,10 @@ class ActionComm extends CommonObject { if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into () { - $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).')':''); + if ($labeltype) + { + $libelle.=(preg_match('/'.preg_quote($labeltype,'/').'/', $libelle)?'':' ('.$langs->transnoentities("Action".$this->type_code).')'); + } } } @@ -1317,6 +1318,13 @@ class ActionComm extends CommonObject $result.=$libelleshort; $result.=$linkend; + global $action; + $hookmanager->initHooks(array('actiondao')); + $parameters=array('id'=>$this->id, 'getnomurl'=>$result); + $reshook=$hookmanager->executeHooks('getNomUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $result = $hookmanager->resPrint; + else $result .= $hookmanager->resPrint; + return $result; } @@ -1328,7 +1336,7 @@ class ActionComm extends CommonObject * @param string $type 'event' or 'journal' * @param int $cachedelay Do not rebuild file if date older than cachedelay seconds * @param string $filename Force filename - * @param array $filters Array of filters + * @param array $filters Array of filters. Exemple array('notolderthan'=>99, 'year'=>..., 'idfrom'=>..., 'notactiontype'=>'systemauto', 'project'=>123, ...) * @return int <0 if error, nb of events in new file if ok */ function build_exportfile($format,$type,$cachedelay,$filename,$filters) @@ -1409,7 +1417,9 @@ class ActionComm extends CommonObject if ($key == 'idfrom') $sql.=" AND a.id >= ".(is_numeric($value)?$value:0); if ($key == 'idto') $sql.=" AND a.id <= ".(is_numeric($value)?$value:0); if ($key == 'project') $sql.=" AND a.fk_project=".(is_numeric($value)?$value:0); - // We must filter on assignement table + if ($key == 'actiontype') $sql.=" AND c.type = '".$this->db->escape($value)."'"; + if ($key == 'notactiontype') $sql.=" AND c.type <> '".$this->db->escape($value)."'"; + // We must filter on assignement table if ($key == 'logint') $sql.= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; if ($key == 'logina') { @@ -1630,7 +1640,8 @@ class ActionComm extends CommonObject { global $conf, $langs; - $this->output = ''; + $error = 0; + $this->output = ''; $this->error=''; if (empty($conf->global->AGENDA_REMINDER_EMAIL)) @@ -1644,6 +1655,8 @@ class ActionComm extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); + $this->db->begin(); + // TODO Scan events of type 'email' into table llx_actioncomm_reminder with status todo, send email, then set status to done @@ -1652,7 +1665,9 @@ class ActionComm extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder WHERE dateremind < '".$this->db->jdate($now - (3600 * 24 * 32))."'"; $this->db->query($sql); - return 0; + $this->db->commit(); + + return $error; } } diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php index b507d9c72b9..f5d9c7db762 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -187,7 +187,7 @@ class AgendaEvents extends DolibarrApi * @param array $request_data Request data * @return int ID of Agenda Event */ - function post($request_data = NULL) + function post($request_data = null) { if (! DolibarrApiAccess::$user->rights->agenda->myactions->create) { throw new RestException(401, "Insuffisant rights to create your Agenda Event"); @@ -226,7 +226,7 @@ class AgendaEvents extends DolibarrApi * @return int */ /* - function put($id, $request_data = NULL) { + function put($id, $request_data = null) { if (! DolibarrApiAccess::$user->rights->agenda->myactions->create) { throw new RestException(401, "Insuffisant rights to create your Agenda Event"); } diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 46efeb95a54..43e5b89f115 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -36,10 +36,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -$langs->load("companies"); -$langs->load("commercial"); -$langs->load("other"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'commercial', 'other', 'bills')); $id = GETPOST('id', 'int'); $action=GETPOST('action', 'alpha'); @@ -100,7 +98,7 @@ if ($object->id > 0) $result2=$object->fetch_thirdparty(); $result3=$object->fetch_contact(); $result4=$object->fetch_userassigned(); - $result5=$object->fetch_optionals($id,$extralabels); + $result5=$object->fetch_optionals(); if ($result1 < 0 || $result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) { diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 4a909f1adeb..c361d275882 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -1,7 +1,7 @@ * Copyright (C) 2003 Eric Seigne - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011 Juanjo Menent * Copyright (C) 2014 Cedric GROSS @@ -44,7 +44,7 @@ if (! isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MA if (empty($conf->global->AGENDA_EXT_NB)) $conf->global->AGENDA_EXT_NB=5; $MAXAGENDA=$conf->global->AGENDA_EXT_NB; -$filter = GETPOST("filter",'',3); +$filter = GETPOST("filter",'alpha',3); $filtert = GETPOST("filtert","int",3); $usergroup = GETPOST("usergroup","int",3); $showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; @@ -59,7 +59,7 @@ $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page","int"); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $offset = $limit * $page; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="a.datec"; @@ -85,8 +85,8 @@ $month=GETPOST("month","int")?GETPOST("month","int"):date("m"); $week=GETPOST("week","int")?GETPOST("week","int"):date("W"); $day=GETPOST("day","int")?GETPOST("day","int"):0; $pid=GETPOST("projectid","int",3); -$status=GETPOST("status"); -$type=GETPOST("type"); +$status=GETPOST("status",'aZ09'); // status may be 0, 50, 100, 'todo' +$type=GETPOST("type",'az09'); $maxprint=(isset($_GET["maxprint"])?GETPOST("maxprint"):$conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) if (GETPOST('actioncode','array')) @@ -102,7 +102,10 @@ if ($actioncode == '' && empty($actioncodearray)) $actioncode=(empty($conf->glob if ($status == '' && ! isset($_GET['status']) && ! isset($_POST['status'])) $status=(empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS)?'':$conf->global->AGENDA_DEFAULT_FILTER_STATUS); if (empty($action) && ! isset($_GET['action']) && ! isset($_POST['action'])) $action=(empty($conf->global->AGENDA_DEFAULT_VIEW)?'show_month':$conf->global->AGENDA_DEFAULT_VIEW); - +if ($action == 'default') +{ + $action = ((! empty($conf->global->AGENDA_DEFAULT_VIEW) && $conf->global->AGENDA_DEFAULT_VIEW!='show_list') ? $conf->global->AGENDA_DEFAULT_VIEW : 'show_month'); +} if (GETPOST('viewcal') && $action != 'show_day' && $action != 'show_week') { $action='show_month'; $day=''; } // View by month @@ -113,10 +116,8 @@ if (GETPOST('viewday') || $action == 'show_day') { $action='show_day'; $day=($day?$day:date("d")); } // View by day - -$langs->load("agenda"); -$langs->load("other"); -$langs->load("commercial"); +// Load translation files required by the page +$langs->loadLangs(array('agenda', 'other', 'commercial')); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('agenda')); @@ -126,7 +127,7 @@ $hookmanager->initHooks(array('agenda')); * Actions */ -if (GETPOST("viewlist") || $action == 'show_list') +if (GETPOST("viewlist",'alpha') || $action == 'show_list') { $param=''; if (is_array($_POST)) @@ -142,7 +143,7 @@ if (GETPOST("viewlist") || $action == 'show_list') exit; } -if (GETPOST("viewperuser") || $action == 'show_peruser') +if (GETPOST("viewperuser",'alpha') || $action == 'show_peruser') { $param=''; if (is_array($_POST)) @@ -589,6 +590,7 @@ if ($resql) $event->type_color=$obj->type_color; $event->libelle=$obj->label; + $event->label=$obj->label; $event->percentage=$obj->percent; $event->authorid=$obj->fk_user_author; // user id of creator $event->userownerid=$obj->fk_user_action; // user id of owner @@ -601,7 +603,9 @@ if ($resql) $event->elementtype=$obj->elementtype; $event->societe->id=$obj->fk_soc; + $event->thirdparty_id=$obj->fk_soc; $event->contact->id=$obj->fk_contact; + $event->contact_id=$obj->fk_contact; // Defined date_start_in_calendar and date_end_in_calendar property // They are date start and end of action but modified to not be outside calendar view. @@ -674,7 +678,7 @@ if ($showbirthday) $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday'; $sql.= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; $sql.= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; - $sql.= " AND sp.entity IN (".getEntity('societe').")"; + $sql.= " AND sp.entity IN (".getEntity('socpeople').")"; if ($action == 'show_day') { $sql.= ' AND MONTH(birthday) = '.$month; @@ -1176,19 +1180,72 @@ else // View by day $timestamp=dol_mktime(12,0,0,$month,$day,$year); $arraytimestamp=dol_getdate($timestamp); - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table - echo '
'.$langs->trans("Project")."
'.$langs->trans("Project")." (".count($projects).")
'.$project->title."'; - $typeid=$object->type; $permission=0; - if ($typeid == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); - if ($typeid == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; - if ($typeid == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; - if ($typeid == Categorie::TYPE_ACCOUNT) $permission=$user->rights->banque->configurer; - if ($typeid == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; + if ($type == Categorie::TYPE_PRODUCT) $permission=($user->rights->produit->creer || $user->rights->service->creer); + if ($type == Categorie::TYPE_SUPPLIER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_CUSTOMER) $permission=$user->rights->societe->creer; + if ($type == Categorie::TYPE_MEMBER) $permission=$user->rights->adherent->creer; + if ($type == Categorie::TYPE_PROJECT) $permission=$user->rights->projet->creer; if ($permission) { print ""; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 890996bddce..10ed739ab94 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005 Simon TOSSER * Copyright (C) 2005-2017 Regis Houssin * Copyright (C) 2010-2013 Juanjo Menent @@ -42,12 +42,8 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("commercial"); -$langs->load("other"); -$langs->load("bills"); -$langs->load("orders"); -$langs->load("agenda"); +// Load translation files required by the page +$langs->loadLangs(array("companies", "other", "commercial", "bills", "orders", "agenda")); $action=GETPOST('action','alpha'); $cancel=GETPOST('cancel','alpha'); @@ -909,7 +905,7 @@ if ($action == 'create') $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } @@ -931,11 +927,20 @@ if ($action == 'create') if ($id > 0) { $result1=$object->fetch($id); + if ($result1 <= 0) + { + $langs->load("errors"); + print $langs->trans("ErrorRecordNotFound"); + + llxFooter(); + exit; + } + $result2=$object->fetch_thirdparty(); $result2=$object->fetch_projet(); $result3=$object->fetch_contact(); $result4=$object->fetch_userassigned(); - $result5=$object->fetch_optionals($id,$extralabels); + $result5=$object->fetch_optionals(); if ($listUserAssignedUpdated || $donotclearsession) { @@ -961,7 +966,7 @@ if ($id > 0) $object->note = GETPOST("note",'none'); } - if ($result1 < 0 || $result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) + if ($result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) { dol_print_error($db,$object->error); exit; @@ -1045,7 +1050,7 @@ if ($id > 0) } // Title - print '
'.$langs->trans("Title").'
'.$langs->trans("EventOnFullDay").'fulldayevent?' checked':'').'>
'; - echo ' '; - echo ' \n"; - echo " \n"; - echo " \n"; - echo ' \n"; - echo " \n"; + //echo '
'.$langs->trans("Day".$arraytimestamp['wday'])."
'; - $maxnbofchar=80; - show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); - echo "
'; + echo '
'; + + echo ' '; + echo ' '; + echo ' \n"; + echo " \n"; + + /* + echo '
'; + echo '
'; + echo '
'; + echo show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, -1); + echo '
'."\n"; + echo "
\n"; + */ + echo '
'.$langs->trans("Day".$arraytimestamp['wday'])."
'; - print ''; + + /* WIP View per hour */ + $useviewhour = 0; + if ($useviewhour) + { + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + + $maxheightwin=(isset($_SESSION["dol_screenheight"]) && $_SESSION["dol_screenheight"] > 500)?($_SESSION["dol_screenheight"]-200):660; // Also into index.php file + + echo '
'; + echo '
'; + + $maxnbofchar=80; + + $tmp = explode('-', $conf->global->MAIN_DEFAULT_WORKING_HOURS); + $minhour = round($tmp[0],0); + $maxhour = round($tmp[1],0); + if ($minhour > 23) $minhour = 23; + if ($maxhour < 1) $maxhour = 1; + if ($maxhour <= $minhour) { $maxhour = $minhour + 1; } + + $i = 0; + $j = 0; + while ($i < 24) + { + echo '
'."\n"; + echo '
'.dol_print_date($i*3600, 'hour', 'gmt').'
'; + echo '
'; + echo "
\n"; + echo "
\n"; + $i++; + $j++; + } + + echo '
'; + + show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, 1); + + print '
'; + } + else + { + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + + show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, 0); + + print '
'; + } } print "\n".''; @@ -1213,9 +1270,10 @@ $db->close(); * @param string $newparam Parameters on current URL * @param int $showinfo Add extended information (used by day and week view) * @param int $minheight Minimum height for each event. 60px by default. + * @param string $nonew 0=Add "new entry button", 1=No "new entry button", -1=Only "new entry button" * @return void */ -function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint=0, $maxnbofchar=16, $newparam='', $showinfo=0, $minheight=60) +function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint=0, $maxnbofchar=16, $newparam='', $showinfo=0, $minheight=60, $nonew=0) { global $user, $conf, $langs; global $action, $filter, $filtert, $status, $actioncode; // Filters used into search form @@ -1230,26 +1288,35 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $curtime = dol_mktime(0, 0, 0, $month, $day, $year); print '
'."\n"; - print '
'; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) + if ($nonew <= 0) { - $newparam.='&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; + print '
'; + if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) + { + $newparam.='&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; - //$param='month='.$monthshown.'&year='.$year; - $hourminsec='100000'; - print ''; - print img_picto($langs->trans("NewAction"),'edit_add.png'); - print ''; + //$param='month='.$monthshown.'&year='.$year; + $hourminsec='100000'; + print ''; + print img_picto($langs->trans("NewAction"),'edit_add.png'); + print ''; + } + print '
'."\n"; + } + + if ($nonew < 0) + { + print '
'; + return; } - print '
'."\n"; // Line with td contains all div of each events print '
'; @@ -1390,6 +1457,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa //print ' position: absolute; top: 40px; width: 50%;'; //print '"'; print '>'; + //var_dump($event->userassigned); //var_dump($event->transparency); print 'load("users"); -$langs->load("companies"); -$langs->load("agenda"); -$langs->load("commercial"); +// Load translation files required by the page +$langs->loadLangs(array("users","companies","agenda","commercial")); $action=GETPOST('action','alpha'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'actioncommlist'; // To manage different context of search $resourceid=GETPOST("resourceid","int"); $year=GETPOST("year",'int'); $month=GETPOST("month",'int'); @@ -57,6 +59,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_id=GETPOST('search_id','alpha'); $search_title=GETPOST('search_title','alpha'); $dateselect=dol_mktime(0, 0, 0, GETPOST('dateselectmonth','int'), GETPOST('dateselectday','int'), GETPOST('dateselectyear','int')); @@ -65,13 +68,11 @@ $dateend=dol_mktime(0, 0, 0, GETPOST('dateendmonth','int'), GETPOST('dateendday' if ($status == '' && ! isset($_GET['status']) && ! isset($_POST['status'])) $status=(empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS)?'':$conf->global->AGENDA_DEFAULT_FILTER_STATUS); if (empty($action) && ! isset($_GET['action']) && ! isset($_POST['action'])) $action=(empty($conf->global->AGENDA_DEFAULT_VIEW)?'show_month':$conf->global->AGENDA_DEFAULT_VIEW); -$filter = GETPOST("filter",'',3); +$filter = GETPOST("filter",'alpha',3); $filtert = GETPOST("filtert","int",3); $usergroup = GETPOST("usergroup","int",3); $showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; -$contextpage='actioncommlist'; - $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extralabels = $extrafields->fetch_name_optionals_label('actioncomm'); @@ -116,6 +117,7 @@ if (! $user->rights->agenda->allactions->read || $filter=='mine') // If no permi } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$object = new ActionComm($db); $hookmanager->initHooks(array('agendalist')); $arrayfields=array( @@ -170,7 +172,8 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { //$actioncode=''; - $search_title=''; + $search_id=''; + $search_title=''; $datestart=''; $dateend=''; $status=''; @@ -199,24 +202,25 @@ llxHeader('',$langs->trans("Agenda"),$help_url); $listofextcals=array(); $param=''; -if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); if ($actioncode != '') { if(is_array($actioncode)) { - foreach($actioncode as $str_action) $param.="&actioncode[]=".$str_action; - } else $param.="&actioncode=".$actioncode; + foreach($actioncode as $str_action) $param.="&actioncode[]=".urlencode($str_action); + } else $param.="&actioncode=".urlencode($actioncode); } -if ($resourceid > 0) $param.="&resourceid=".$resourceid; -if ($status != '' && $status > -1) $param.="&status=".$status; -if ($filter) $param.="&filter=".$filter; -if ($filtert) $param.="&filtert=".$filtert; -if ($socid) $param.="&socid=".$socid; +if ($resourceid > 0) $param.="&resourceid=".urlencode($resourceid); +if ($status != '' && $status > -1) $param.="&status=".urlencode($status); +if ($filter) $param.="&filter=".urlencode($filter); +if ($filtert) $param.="&filtert=".urlencode($filtert); +if ($socid) $param.="&socid=".urlencode($socid); if ($showbirthday) $param.="&showbirthday=1"; -if ($pid) $param.="&projectid=".$pid; -if ($type) $param.="&type=".$type; -if ($usergroup) $param.="&usergroup=".$usergroup; -if ($optioncss != '') $param.='&optioncss='.$optioncss; -if ($search_title != '') $param.='&search_title='.$search_title; +if ($pid) $param.="&projectid=".urlencode($pid); +if ($type) $param.="&type=".urlencode($type); +if ($usergroup) $param.="&usergroup=".urlencode($usergroup); +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +if ($search_id != '') $param.='&search_title='.urlencode($search_id); +if ($search_title != '') $param.='&search_title='.urlencode($search_title); if (GETPOST('datestartday','int')) $param.='&datestartday='.GETPOST('datestartday','int'); if (GETPOST('datestartmonth','int')) $param.='&datestartmonth='.GETPOST('datestartmonth','int'); if (GETPOST('datestartyear','int')) $param.='&datestartyear='.GETPOST('datestartyear','int'); @@ -291,8 +295,9 @@ if ($status == '0') { $sql.= " AND a.percent = 0"; } 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 == '100') { $sql.= " AND a.percent = 100"; } -if ($status == 'done' || $status == '100') { $sql.= " AND (a.percent = 100)"; } +if ($status == 'done') { $sql.= " AND (a.percent = 100)"; } if ($status == 'todo') { $sql.= " AND (a.percent >= 0 AND a.percent < 100)"; } +if ($search_id) $sql.=natural_search("a.id", $search_id, 1); if ($search_title) $sql.=natural_search("a.label", $search_title); // We must filter on assignement table if ($filtert > 0 || $usergroup > 0) @@ -317,6 +322,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1, $offset); @@ -331,13 +341,9 @@ if ($resql) $num = $db->num_rows($resql); - /*$title=$langs->trans("DoneAndToDoActions"); - if ($status == 'done') $title=$langs->trans("DoneActions"); - if ($status == 'todo') $title=$langs->trans("ToDoActions"); - */ - $title=$langs->trans("ListOfEvents"); - - $newtitle=$langs->trans($title); + // Local calendar + $newtitle ='
' . $langs->trans("LocalAgenda").'  
'; + //$newtitle=$langs->trans($title); $tabactive='cardlist'; @@ -400,6 +406,7 @@ if ($resql) $s = $hookmanager->resPrint; } + $newcardbutton=''; if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) { $tmpforcreatebutton=dol_getdate(dol_now(), true); @@ -408,12 +415,12 @@ if ($resql) //$param='month='.$monthshown.'&year='.$year; $hourminsec='100000'; - $link = ''; - $link.= $langs->trans("AddAction"); - $link.= ''; + $newcardbutton = ''.$langs->trans("AddAction").''; + $newcardbutton.= ''; + $newcardbutton.= ''; } - print_barre_liste($s, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, $nav.$link, '', $limit); + print_barre_liste($s, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, $nav.$newcardbutton, '', $limit); $moreforfilter=''; @@ -425,7 +432,7 @@ if ($resql) print '
'."\n"; print ''; - if (! empty($arrayfields['a.id']['checked'])) print ''; + if (! empty($arrayfields['a.id']['checked'])) print ''; if (! empty($arrayfields['owner']['checked'])) print ''; if (! empty($arrayfields['c.libelle']['checked'])) print ''; if (! empty($arrayfields['a.label']['checked'])) print ''; @@ -496,7 +503,6 @@ if ($resql) $caction=new CActionComm($db); $arraylist=$caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:0), '', 1); - $var=true; while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); @@ -626,6 +632,7 @@ if ($resql) // Linked object if (! empty($arrayfields['a.fk_element']['checked'])) { print '
'; + //var_dump($obj->fkelement.' '.$obj->elementtype); if ($obj->fk_element > 0 && ! empty($obj->elementtype)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; print dolGetElementUrl($obj->fk_element,$obj->elementtype,1); diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php index 982389552a5..2fdfa180319 100644 --- a/htdocs/comm/action/pertype.php +++ b/htdocs/comm/action/pertype.php @@ -136,11 +136,8 @@ if (GETPOST('viewyear','alpha') || $action == 'show_year') { $action='show_year'; } // View by year - -$langs->load("users"); -$langs->load("agenda"); -$langs->load("other"); -$langs->load("commercial"); +// Load translation files required by the page +$langs->loadLangs(array('users', 'agenda', 'other', 'commercial')); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('agenda')); @@ -468,10 +465,8 @@ if ($resql) $event->datef=$datep2; $event->type_code=$obj->code; $event->type_color=$obj->color; - //$event->libelle=$obj->label; // deprecated $event->label=$obj->label; $event->percentage=$obj->percent; - //$event->author->id=$obj->fk_user_author; // user id of creator $event->authorid=$obj->fk_user_author; // user id of creator $event->userownerid=$obj->fk_user_action; // user id of owner $event->priority=$obj->priority; @@ -483,8 +478,6 @@ if ($resql) $event->socid=$obj->fk_soc; $event->contactid=$obj->fk_contact; - //$event->societe->id=$obj->fk_soc; // deprecated - //$event->contact->id=$obj->fk_contact; // deprecated $event->fk_element=$obj->fk_element; $event->elementtype=$obj->elementtype; diff --git a/htdocs/comm/action/peruser.php b/htdocs/comm/action/peruser.php index dcb227799c4..0cf056ef3a9 100644 --- a/htdocs/comm/action/peruser.php +++ b/htdocs/comm/action/peruser.php @@ -136,11 +136,8 @@ if (GETPOST('viewday','alpha') || $action == 'show_day') { $action='show_day'; $day=($day?$day:date("d")); } // View by day - -$langs->load("users"); -$langs->load("agenda"); -$langs->load("other"); -$langs->load("commercial"); +// Load translation files required by the page +$langs->loadLangs(array('users', 'agenda', 'other', 'commercial')); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('agenda')); @@ -205,24 +202,24 @@ if ($status == 'todo') $title=$langs->trans("ToDoActions"); $param=''; if ($actioncode || isset($_GET['actioncode']) || isset($_POST['actioncode'])) { if(is_array($actioncode)) { - foreach($actioncode as $str_action) $param.="&actioncode[]=".$str_action; - } else $param.="&actioncode=".$actioncode; + foreach($actioncode as $str_action) $param.="&actioncode[]=".urlencode($str_action); + } else $param.="&actioncode=".urlencode($actioncode); } -if ($resourceid > 0) $param.="&resourceid=".$resourceid; -if ($status || isset($_GET['status']) || isset($_POST['status'])) $param.="&status=".$status; -if ($filter) $param.="&filter=".$filter; -if ($filtert) $param.="&filtert=".$filtert; -if ($usergroup) $param.="&usergroup=".$usergroup; -if ($socid) $param.="&socid=".$socid; +if ($resourceid > 0) $param.="&resourceid=".urlencode($resourceid); +if ($status || isset($_GET['status']) || isset($_POST['status'])) $param.="&status=".urlencode($status); +if ($filter) $param.="&filter=".urlencode($filter); +if ($filtert) $param.="&filtert=".urlencode($filtert); +if ($usergroup) $param.="&usergroup=".urlencode($usergroup); +if ($socid) $param.="&socid=".urlencode($socid); if ($showbirthday) $param.="&showbirthday=1"; -if ($pid) $param.="&projectid=".$pid; -if ($type) $param.="&type=".$type; -if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param.='&action='.$action; -if ($begin_h != '') $param.='&begin_h='.$begin_h; -if ($end_h != '') $param.='&end_h='.$end_h; -if ($begin_d != '') $param.='&begin_d='.$begin_d; -if ($end_d != '') $param.='&end_d='.$end_d; -$param.="&maxprint=".$maxprint; +if ($pid) $param.="&projectid=".urlencode($pid); +if ($type) $param.="&type=".urlencode($type); +if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param.='&action='.urlencode($action); +if ($begin_h != '') $param.='&begin_h='.urlencode($begin_h); +if ($end_h != '') $param.='&end_h='.urlencode($end_h); +if ($begin_d != '') $param.='&begin_d='.urlencode($begin_d); +if ($end_d != '') $param.='&end_d='.urlencode($end_d); +$param.="&maxprint=".urlencode($maxprint); $prev = dol_get_first_day_week($day, $month, $year); @@ -245,7 +242,9 @@ $next_day = $next['day']; // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) $firstdaytoshow=dol_mktime(0,0,0,$first_month,$first_day,$first_year); -$lastdaytoshow=dol_time_plus_duree($firstdaytoshow, 7, 'd'); + +$nb_weeks_to_show = (! empty($conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER)) ? ((int) $conf->global->AGENDA_NB_WEEKS_IN_VIEW_PER_USER * 7) : 7; +$lastdaytoshow=dol_time_plus_duree($firstdaytoshow, $nb_weeks_to_show, 'd'); //print $firstday.'-'.$first_month.'-'.$first_year; //print dol_print_date($firstdaytoshow,'dayhour'); //print dol_print_date($lastdaytoshow,'dayhour'); @@ -282,12 +281,11 @@ $nav.=' query($sql); @@ -495,10 +493,8 @@ if ($resql) $event->datef=$datep2; $event->type_code=$obj->code; $event->type_color=$obj->color; - //$event->libelle=$obj->label; // deprecated $event->label=$obj->label; $event->percentage=$obj->percent; - //$event->author->id=$obj->fk_user_author; // user id of creator $event->authorid=$obj->fk_user_author; // user id of creator $event->userownerid=$obj->fk_user_action; // user id of owner $event->priority=$obj->priority; @@ -510,8 +506,6 @@ if ($resql) $event->socid=$obj->fk_soc; $event->contactid=$obj->fk_contact; - //$event->societe->id=$obj->fk_soc; // deprecated - //$event->contact->id=$obj->fk_contact; // deprecated $event->fk_element=$obj->fk_element; $event->elementtype=$obj->elementtype; @@ -619,183 +613,193 @@ echo '' ; //print "begin_d=".$begin_d." end_d=".$end_d; - +$currentdaytoshow = $firstdaytoshow; echo '
'; -echo ''; -echo ''; -echo ''; -$i=0; // 0 = sunday, -while ($i < 7) -{ - if (($i + 1) < $begin_d || ($i + 1) > $end_d) - { - $i++; - continue; - } - echo '\n"; - $i++; -} -echo "\n"; +while($currentdaytoshow<$lastdaytoshow) { -echo ''; -echo ''; -$i=0; -while ($i < 7) -{ - if (($i + 1) < $begin_d || ($i + 1) > $end_d) - { - $i++; - continue; - } - for ($h = $begin_h; $h < $end_h; $h++) - { - echo '"; - } - echo "\n"; - $i++; -} -echo "\n"; + echo '
'; - echo $langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7)); - print "
"; - if ($i) print dol_print_date(dol_time_plus_duree($firstdaytoshow, $i, 'd'),'day'); - else print dol_print_date($firstdaytoshow,'day'); - echo "
'; - print ''.sprintf("%02d",$h).''; - print "
'; - -// Define $usernames -$usernames = array(); //init -$usernamesid = array(); -/* Use this to have list of users only if users have events */ -if (! empty($conf->global->AGENDA_SHOWOWNERONLY_ONPERUSERVIEW)) -{ - foreach ($eventarray as $daykey => $notused) - { - // Get all assigned users for each event - foreach ($eventarray[$daykey] as $index => $event) - { - $event->fetch_userassigned(); - $listofuserid=$event->userassigned; - foreach($listofuserid as $userid => $tmp) - { - if (! in_array($userid, $usernamesid)) $usernamesid[$userid] = $userid; - } - } - } -} -/* Use this list to have for all users */ -else -{ - $sql = "SELECT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; - if ($usergroup > 0) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user"; - $sql.= " WHERE u.statut = 1 AND u.entity IN (".getEntity('user').")"; - if ($usergroup > 0) $sql.= " AND ug.fk_usergroup = ".$usergroup; - //print $sql; - $resql=$db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $db->fetch_object($resql); - $usernamesid[$obj->rowid]=$obj->rowid; - $i++; - } - } - } - else dol_print_error($db); -} -//var_dump($usernamesid); -foreach($usernamesid as $id) -{ - $tmpuser=new User($db); - $result=$tmpuser->fetch($id); - $usernames[]=$tmpuser; -} - -/* -if ($filtert > 0) -{ - $tmpuser = new User($db); - $tmpuser->fetch($filtert); - $usernames[] = $tmpuser; -} -else if ($usergroup) -{ - $tmpgroup = new UserGroup($db); - $tmpgroup->fetch($usergroup); - $usernames = $tmpgroup->listUsersForGroup(); -} -else -{ - $tmpgroup = new UserGroup($db); - //$tmpgroup->fetch($usergroup); No fetch, we want all users for all groups - $usernames = $tmpgroup->listUsersForGroup(); -}*/ - -// Load array of colors by type -$colorsbytype=array(); -$labelbytype=array(); -$sql="SELECT code, color, libelle FROM ".MAIN_DB_PREFIX."c_actioncomm ORDER BY position"; -$resql=$db->query($sql); -while ($obj = $db->fetch_object($resql)) -{ - $colorsbytype[$obj->code]=$obj->color; - $labelbytype[$obj->code]=$obj->libelle; -} - -// Loop on each user to show calendar -$todayarray=dol_getdate($now,'fast'); -$sav = $tmpday; -$showheader = true; -$var = false; -foreach ($usernames as $username) -{ - $var = ! $var; - echo ""; - echo ''; - $tmpday = $sav; - - // Lopp on each day of week - $i = 0; - for ($iter_day = 0; $iter_day < 8; $iter_day++) + echo ''; + echo ''; + $i=0; // 0 = sunday, + while ($i < 7) { if (($i + 1) < $begin_d || ($i + 1) > $end_d) { $i++; continue; } - - // Show days of the current week - $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); - $tmparray = dol_getdate($curtime,'fast'); - $tmpday = $tmparray['mday']; - $tmpmonth = $tmparray['mon']; - $tmpyear = $tmparray['year']; - - $style='cal_current_month'; - if ($iter_day == 6) $style.=' cal_other_month'; - $today=0; - if ($todayarray['mday']==$tmpday && $todayarray['mon']==$tmpmonth && $todayarray['year']==$tmpyear) $today=1; - if ($today) $style='cal_today_peruser'; - - show_day_events2($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); - + echo '\n"; $i++; } echo "\n"; - $showheader = false; + + echo ''; + echo ''; + $i=0; + while ($i < 7) + { + if (($i + 1) < $begin_d || ($i + 1) > $end_d) + { + $i++; + continue; + } + for ($h = $begin_h; $h < $end_h; $h++) + { + echo '"; + } + echo "\n"; + $i++; + } + echo "\n"; + + + // Define $usernames + $usernames = array(); //init + $usernamesid = array(); + /* Use this to have list of users only if users have events */ + if (! empty($conf->global->AGENDA_SHOWOWNERONLY_ONPERUSERVIEW)) + { + foreach ($eventarray as $daykey => $notused) + { + // Get all assigned users for each event + foreach ($eventarray[$daykey] as $index => $event) + { + $event->fetch_userassigned(); + $listofuserid=$event->userassigned; + foreach($listofuserid as $userid => $tmp) + { + if (! in_array($userid, $usernamesid)) $usernamesid[$userid] = $userid; + } + } + } + } + /* Use this list to have for all users */ + else + { + $sql = "SELECT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; + if ($usergroup > 0) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user"; + $sql.= " WHERE u.statut = 1 AND u.entity IN (".getEntity('user').")"; + if ($usergroup > 0) $sql.= " AND ug.fk_usergroup = ".$usergroup; + //print $sql; + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $usernamesid[$obj->rowid]=$obj->rowid; + $i++; + } + } + } + else dol_print_error($db); + } + //var_dump($usernamesid); + foreach($usernamesid as $id) + { + $tmpuser=new User($db); + $result=$tmpuser->fetch($id); + $usernames[]=$tmpuser; + } + + /* + if ($filtert > 0) + { + $tmpuser = new User($db); + $tmpuser->fetch($filtert); + $usernames[] = $tmpuser; + } + else if ($usergroup) + { + $tmpgroup = new UserGroup($db); + $tmpgroup->fetch($usergroup); + $usernames = $tmpgroup->listUsersForGroup(); + } + else + { + $tmpgroup = new UserGroup($db); + //$tmpgroup->fetch($usergroup); No fetch, we want all users for all groups + $usernames = $tmpgroup->listUsersForGroup(); + }*/ + + // Load array of colors by type + $colorsbytype=array(); + $labelbytype=array(); + $sql="SELECT code, color, libelle FROM ".MAIN_DB_PREFIX."c_actioncomm ORDER BY position"; + $resql=$db->query($sql); + while ($obj = $db->fetch_object($resql)) + { + $colorsbytype[$obj->code]=$obj->color; + $labelbytype[$obj->code]=$obj->libelle; + } + + // Loop on each user to show calendar + $todayarray=dol_getdate($now,'fast'); + $sav = $tmpday; + $showheader = true; + $var = false; + foreach ($usernames as $username) + { + $var = ! $var; + echo ""; + echo ''; + $tmpday = $sav; + + // Lopp on each day of week + $i = 0; + for ($iter_day = 0; $iter_day < 8; $iter_day++) + { + + if (($i + 1) < $begin_d || ($i + 1) > $end_d) + { + $i++; + continue; + } + + // Show days of the current week + $curtime = dol_time_plus_duree($currentdaytoshow, $iter_day, 'd'); + $tmparray = dol_getdate($curtime,'fast'); + $tmpday = $tmparray['mday']; + $tmpmonth = $tmparray['mon']; + $tmpyear = $tmparray['year']; + + $style='cal_current_month'; + if ($iter_day == 6) $style.=' cal_other_month'; + $today=0; + if ($todayarray['mday']==$tmpday && $todayarray['mon']==$tmpmonth && $todayarray['year']==$tmpyear) $today=1; + if ($today) $style='cal_today_peruser'; + + show_day_events2($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); + + $i++; + } + echo "\n"; + $showheader = false; + } + + echo "
'; - print $username->getNomUrl(-1,'',0,0,20,1,''); - print '
'; + echo $langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7)); + print "
"; + if ($i) print dol_print_date(dol_time_plus_duree($currentdaytoshow, $i, 'd'),'day'); + else print dol_print_date($currentdaytoshow,'day'); + echo "
'; + print ''.sprintf("%02d",$h).''; + print "
'; + print $username->getNomUrl(-1,'',0,0,20,1,''); + print '
\n"; + echo "
"; + + $currentdaytoshow = dol_time_plus_duree($currentdaytoshow, 7, 'd'); + } -echo "
\n"; echo '
'; if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && ! empty($conf->global->AGENDA_USE_COLOR_PER_EVENT_TYPE)) diff --git a/htdocs/comm/action/rapport/index.php b/htdocs/comm/action/rapport/index.php index 2d72fa4c3f8..7e4108b470b 100644 --- a/htdocs/comm/action/rapport/index.php +++ b/htdocs/comm/action/rapport/index.php @@ -31,14 +31,14 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/action/rapport.pdf.php'; -$langs->load("agenda"); -$langs->load("commercial"); +// Load translation files required by the page +$langs->loadLangs(array("agenda", "commercial")); $action=GETPOST('action','alpha'); $month=GETPOST('month'); $year=GETPOST('year'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -93,6 +93,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1,$offset); @@ -133,7 +138,6 @@ if ($resql) print '
'.$langs->trans("Size").'
'.$langs->trans('VATIsUsed').''; + print $form->textwithpicto($langs->trans('VATIsUsed'),$langs->trans('VATIsUsedWhenSelling')); + print ''; print yn($object->tva_assuj); print '
'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; - print yn($object->localtax1_assuj); - print '
'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; + print yn($object->localtax1_assuj); + print '
'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; + print yn($object->localtax2_assuj); + print '
'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; - print yn($object->localtax2_assuj); - print '
'.$langs->trans('VATIntra').''; @@ -401,12 +421,22 @@ if ($id > 0) 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 $form->editfieldkey("OrderMinAmount",'order_min_amount',$object->order_min_amount,$object,$user->rights->societe->creer); + print ''; + print $form->editfieldval("OrderMinAmount",'order_min_amount',$object->order_min_amount,$object,$user->rights->societe->creer,$limit_field_type,($object->order_min_amount != '' ? price($object->order_min_amount) : '')); + print '
'; print '
'; @@ -529,7 +559,7 @@ if ($id > 0) } print '
'; - + print '
'; $boxstat = ''; @@ -538,7 +568,7 @@ if ($id > 0) // Lien recap $boxstat.='
'; - $boxstat.=''; + $boxstat.='
'; $boxstat.='
'; if (! empty($conf->propal->enabled)) @@ -630,8 +660,6 @@ if ($id > 0) */ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) { - $propal_static = new Propal($db); - $sql = "SELECT s.nom, s.rowid, p.rowid as propalid, p.fk_statut, p.total_ht"; $sql.= ", p.tva as total_tva"; $sql.= ", p.total as total_ttc"; @@ -646,12 +674,13 @@ if ($id > 0) $resql=$db->query($sql); if ($resql) { - $var=true; - $num = $db->num_rows($resql); + $propal_static = new Propal($db); + $num = $db->num_rows($resql); if ($num > 0) { - print ''; + print '
'; + print '
'; print ''; print '
'; @@ -684,7 +713,11 @@ if ($id > 0) } $db->free($resql); - if ($num > 0) print "
'.$langs->trans("LastPropals",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllPropals").' '.$num.'
"; + if ($num > 0) + { + print "
"; + print ''; + } } else { @@ -697,8 +730,6 @@ if ($id > 0) */ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) { - $commande_static=new Commande($db); - $sql = "SELECT s.nom, s.rowid"; $sql.= ", c.rowid as cid, c.total_ht"; $sql.= ", c.tva as total_tva"; @@ -714,14 +745,14 @@ if ($id > 0) $resql=$db->query($sql); if ($resql) { - $var=true; - $num = $db->num_rows($resql); + $commande_static=new Commande($db); + $num = $db->num_rows($resql); if ($num > 0) { // Check if there are orders billable $sql2 = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_client,'; - $sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as facturee'; + $sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut, c.facture as billed'; $sql2.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql2.= ', '.MAIN_DB_PREFIX.'commande as c'; $sql2.= ' WHERE c.fk_soc = s.rowid'; @@ -733,6 +764,7 @@ if ($id > 0) $orders2invoice = $db->num_rows($resql2); $db->free($resql2); + print '
'; print ''; print ''; @@ -749,14 +781,16 @@ if ($id > 0) { $objp = $db->fetch_object($resql); + $commande_static->id = $objp->cid; + $commande_static->ref = $objp->ref; + $commande_static->ref_client=$objp->ref_client; + $commande_static->total_ht = $objp->total_ht; + $commande_static->total_tva = $objp->total_tva; + $commande_static->total_ttc = $objp->total_ttc; + $commande_static->billed = $objp->billed; + print ''; print '\n"; print ''; @@ -765,7 +799,11 @@ if ($id > 0) } $db->free($resql); - if ($num >0) print "
'; - $commande_static->id = $objp->cid; - $commande_static->ref = $objp->ref; - $commande_static->ref_client=$objp->ref_client; - $commande_static->total_ht = $objp->total_ht; - $commande_static->total_tva = $objp->total_tva; - $commande_static->total_ttc = $objp->total_ttc; print $commande_static->getNomUrl(1); print ''.dol_print_date($db->jdate($objp->dc),'day')."'.price($objp->total_ht).'
"; + if ($num >0) + { + print "
"; + print '
'; + } } else { @@ -776,9 +814,8 @@ if ($id > 0) /* * Last shipments */ - if (! empty($conf->expedition->enabled) && $user->rights->expedition->lire) { - $sendingstatic = new Expedition($db); - + if (! empty($conf->expedition->enabled) && $user->rights->expedition->lire) + { $sql = 'SELECT e.rowid as id'; $sql.= ', e.ref'; $sql.= ', e.date_creation'; @@ -797,12 +834,14 @@ if ($id > 0) $sql.= " ORDER BY e.date_creation DESC"; $resql = $db->query($sql); - if ($resql) { - $var = true; - $num = $db->num_rows($resql); - $i = 0; + if ($resql) + { + $sendingstatic = new Expedition($db); + + $num = $db->num_rows($resql); if ($num > 0) { - print ''; + print '
'; + print '
'; print ''; print '
'; @@ -811,12 +850,16 @@ if ($id > 0) print ''; } - while ($i < $num && $i < $MAXLIST) { + $i = 0; + while ($i < $num && $i < $MAXLIST) + { $objp = $db->fetch_object($resql); - print ''; - print ''; + print ''; if ($objp->date_creation > 0) { @@ -832,7 +875,10 @@ if ($id > 0) $db->free($resql); if ($num > 0) + { print "
'.$langs->trans("LastSendings",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllSendings").' '.$num.'
'; + $sendingstatic->id = $objp->id; $sendingstatic->ref = $objp->ref; + + print '
'; print $sendingstatic->getNomUrl(1); print '
"; + print ''; + } } else { dol_print_error($db); } @@ -843,9 +889,7 @@ if ($id > 0) */ if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) { - $contratstatic=new Contrat($db); - - $sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut, c.datec as dc, c.date_contrat as dcon, c.ref_supplier as refsup"; + $sql = "SELECT s.nom, s.rowid, c.rowid as id, c.ref as ref, c.statut, c.datec as dc, c.date_contrat as dcon, c.ref_customer as refcus, c.ref_supplier as refsup"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c"; $sql.= " WHERE c.fk_soc = s.rowid "; $sql.= " AND s.rowid = ".$object->id; @@ -855,11 +899,13 @@ if ($id > 0) $resql=$db->query($sql); if ($resql) { - $var=true; + $contrat=new Contrat($db); + $num = $db->num_rows($resql); - if ($num >0 ) + if ($num >0) { - print ''; + print '
'; + print '
'; print ''; print ''; print ''; } + $i = 0; while ($i < $num && $i < $MAXLIST) { - $contrat=new Contrat($db); - $objp = $db->fetch_object($resql); + $contrat->id=$objp->id; + $contrat->ref=$objp->ref?$objp->ref:$objp->id; + $contrat->ref_customer=$objp->refcus; + $contrat->ref_supplier=$objp->refsup; + $contrat->fetch_lines(); + print ''; print '\n"; print '\n"; print '\n"; print '\n"; print ''; - print '\n"; print ''; @@ -894,7 +942,11 @@ if ($id > 0) } $db->free($resql); - if ($num > 0) print "
'; @@ -868,25 +914,27 @@ if ($id > 0) print '
'.$langs->trans("LastContracts",($num<=$MAXLIST?"":$MAXLIST)).'
'; - $contrat->id=$objp->id; - $contrat->ref=$objp->ref?$objp->ref:$objp->id; print $contrat->getNomUrl(1,12); print "'.dol_trunc($objp->refsup,12)."'.dol_print_date($db->jdate($objp->dc),'day')."'.dol_print_date($db->jdate($objp->dcon),'day')." '; - $contrat->fetch_lines(); + print ''; print $contrat->getLibStatut(4); print "
"; + if ($num > 0) + { + print "
"; + print '
'; + } } else { @@ -914,24 +966,24 @@ if ($id > 0) $sql.= " AND f.entity = ".$conf->entity; $sql.= " ORDER BY f.tms DESC"; - $fichinter_static=new Fichinter($db); - $resql=$db->query($sql); if ($resql) { - $var=true; + $fichinter_static=new Fichinter($db); + $num = $db->num_rows($resql); if ($num > 0) { - print ''; + print '
'; + print '
'; print ''; print ''; print ''; - } + $i = 0; while ($i < $num && $i < $MAXLIST) { @@ -951,7 +1003,11 @@ if ($id > 0) } $db->free($resql); - if ($num > 0) print "
'; print ''; print '
'.$langs->trans("LastInterventions",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllInterventions").' '.$num.''.img_picto($langs->trans("Statistics"),'stats').'
"; + if ($num > 0) + { + print "
"; + print ''; + } } else { @@ -964,14 +1020,12 @@ if ($id > 0) */ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { - $invoicetemplate = new FactureRec($db); - $sql = 'SELECT f.rowid as id, f.titre as ref, f.amount'; $sql.= ', f.total as total_ht'; $sql.= ', f.tva as total_tva'; $sql.= ', f.total_ttc'; $sql.= ', f.datec as dc'; - $sql.= ', f.date_last_gen'; + $sql.= ', f.date_last_gen, f.date_when'; $sql.= ', f.frequency'; $sql.= ', f.unit_frequency'; $sql.= ', f.suspended as suspended'; @@ -988,11 +1042,12 @@ if ($id > 0) $resql=$db->query($sql); if ($resql) { - $var=true; + $invoicetemplate = new FactureRec($db); + $num = $db->num_rows($resql); - $i = 0; if ($num > 0) { + print '
'; print ''; print ''; @@ -1001,12 +1056,11 @@ if ($id > 0) print ''; } + $i = 0; while ($i < $num && $i < $MAXLIST) { $objp = $db->fetch_object($resql); - print ''; - print ''; + print ''; if ($objp->frequency && $objp->date_last_gen > 0) @@ -1052,7 +1111,11 @@ if ($id > 0) } $db->free($resql); - if ($num > 0) print "
'; $invoicetemplate->id = $objp->id; $invoicetemplate->ref = $objp->ref; $invoicetemplate->suspended = $objp->suspended; @@ -1015,6 +1069,11 @@ if ($id > 0) $invoicetemplate->total_ht = $objp->total_ht; $invoicetemplate->total_tva = $objp->total_tva; $invoicetemplate->total_ttc = $objp->total_ttc; + $invoicetemplate->date_last_gen = $objp->date_last_gen; + $invoicetemplate->date_when = $objp->date_when; + + print '
'; print $invoicetemplate->getNomUrl(1); print '
"; + if ($num > 0) + { + print "
"; + print ''; + } } else { @@ -1065,8 +1128,6 @@ if ($id > 0) */ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { - $facturestatic = new Facture($db); - $sql = 'SELECT f.rowid as facid, f.facnumber, f.type, f.amount'; $sql.= ', f.total as total_ht'; $sql.= ', f.tva as total_tva'; @@ -1086,12 +1147,13 @@ if ($id > 0) $resql=$db->query($sql); if ($resql) { - $var=true; + $facturestatic = new Facture($db); + $num = $db->num_rows($resql); - $i = 0; if ($num > 0) { - print ''; + print '
'; + print '
'; print ''; print '
'; @@ -1100,18 +1162,20 @@ if ($id > 0) print ''; } + $i = 0; while ($i < $num && $i < $MAXLIST) { $objp = $db->fetch_object($resql); - print ''; - print ''; + print ''; if ($objp->df > 0) @@ -1139,7 +1203,11 @@ if ($id > 0) } $db->free($resql); - if ($num > 0) print "
'.$langs->trans("LastCustomersBills",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllBills").' '.$num.'
'; $facturestatic->id = $objp->facid; $facturestatic->ref = $objp->facnumber; $facturestatic->type = $objp->type; - $facturestatic->total_ht = $objp->total_ht; - $facturestatic->total_tva = $objp->total_tva; - $facturestatic->total_ttc = $objp->total_ttc; + $facturestatic->total_ht = $objp->total_ht; + $facturestatic->total_tva = $objp->total_tva; + $facturestatic->total_ttc = $objp->total_ttc; + + print '
'; print $facturestatic->getNomUrl(1); print '
"; + if ($num > 0) + { + print "
"; + print ''; + } } else { @@ -1272,7 +1340,8 @@ if ($id > 0) } else { - dol_print_error($db,'Bad value for socid parameter'); + $langs->load("errors"); + print $langs->trans('ErrorRecordNotFound'); } // End of page diff --git a/htdocs/comm/contact.php b/htdocs/comm/contact.php index 5c160bfab16..aa8dae43140 100644 --- a/htdocs/comm/contact.php +++ b/htdocs/comm/contact.php @@ -26,6 +26,7 @@ require '../main.inc.php'; +// Load translation files required by the page $langs->load("companies"); $sortfield=GETPOST('sortfield', 'alpha'); @@ -34,7 +35,7 @@ $page=GETPOST('page', 'int'); if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="p.name"; if ($page < 0) { $page = 0; } -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $offset = $limit * $page ; $type=GETPOST('type', 'alpha'); @@ -78,7 +79,7 @@ if (! $user->rights->societe->client->voir && ! $socid) $sql .= " ".MAIN_DB_PREF $sql.= " ".MAIN_DB_PREFIX."socpeople as p"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc"; $sql.= " WHERE s.fk_stcomm = st.id"; -$sql.= " AND p.entity IN (".getEntity('societe').")"; +$sql.= " AND p.entity IN (".getEntity('socpeople').")"; if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($type == "c") $sql.= " AND s.client IN (1, 3)"; if ($type == "p") $sql.= " AND s.client IN (2, 3)"; @@ -144,14 +145,11 @@ if ($resql) print '
'.img_object($langs->trans("ShowContact"),"contact"); print ' '.$obj->name.'
'.$langs->trans("ProposalsDraft").($num?' '.$num.'':'').'
'.$langs->trans("SupplierProposalsDraft").($num?' '.$num.'':'').'
'.price($obj->total_ht).'
'.$langs->trans("Total").''.price($total)."
'.$langs->trans("NoProposal").'

"; @@ -323,7 +319,6 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) print '
'.$langs->trans("DraftOrders").($num?' '.$num.'':'').'
'.price($obj->total_ttc).'
'.price($obj->total_ht).'
'.price($obj->total_ttc).'
'.$langs->trans("DraftSuppliersOrders").($num?' '.$num.'':'').'
'.price($obj->total_ttc).'
'.price($obj->total_ht).'
'.price($obj->total_ttc).'
'; $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->propalid; print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir); print '
'; @@ -744,7 +747,12 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) print '
'; print dol_print_date($db->jdate($obj->dp),'day').''.price($obj->total_ttc).''.price($obj->total_ht).''.price($obj->total_ttc).''.$propalstatic->LibStatut($obj->fk_statut,3).'
'; print dol_print_date($db->jdate($obj->dp),'day').''.price($obj->total_ttc).''.price($obj->total_ht).''.price($obj->total_ttc).''.$orderstatic->LibStatut($obj->fk_statut,$obj->billed,3).'
' . "\n"; - - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - - print '' . "\n"; - - print '' . "\n"; - - // Customer name - print '' . "\n"; - - // Code Client - print '' . "\n"; - - // Address Client - print '' . "\n"; - - // Zip Client - print '' . "\n"; - - // City Client - print '' . "\n"; - - // Customer Country - print '' . "\n"; - - // State Customer - print '' . "\n"; - - // Mother Company - print '' . "\n"; - - // Prospect/Customer - $selected = $array_query['cust_typecust']; - print '' . "\n"; - - // Prospection status - print '' . "\n"; - - // Prospection comm status - print '' . "\n"; - - // Customer Type - print '' . "\n"; - - // Staff number - print '' . "\n"; - - // Sales manager - print '' . "\n"; - - // Customer Default Langauge - if (! empty($conf->global->MAIN_MULTILANGS)) { - - print '' . "\n"; - } - - if (! empty($conf->categorie->enabled) && $user->rights->categorie->lire) { - // Customer Categories - print '' . "\n"; - } - - // Standard Extrafield feature - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { - // fetch optionals attributes and labels - dol_include_once('/core/class/extrafields.class.php'); - $extrafields = new ExtraFields($db); - $extralabels = $extrafields->fetch_name_optionals_label('societe'); - foreach ( $extralabels as $key => $val ) { - if ($key != 'ts_nameextra' && $key != 'ts_payeur') { - print '' . "\n"; - } - } - } else { - $std_soc = new Societe($db); - $action_search = 'query'; - - // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context - include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($db); - $hookmanager->initHooks(array ('thirdpartycard')); - - $parameters=array(); - if (! empty($advTarget->id)) { - $parameters = array('array_query' => $advTarget->filtervalue); - } - // Other attributes - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $std_soc, $action_search); - print $hookmanager->resPrint; - } - - // State Contact - print '' . "\n"; - - // Civility - print ''; - - // contact name - print '' . "\n"; - print '' . "\n"; - - // Contact Country - print '' . "\n"; - - // Never send mass mailing - print '' . "\n"; - - // Contact Date Create - print '' . "\n"; - - // Contact update Create - print '' . "\n"; - - if (! empty($conf->categorie->enabled) && $user->rights->categorie->lire) { - // Customer Categories - print '' . "\n"; - } - - // Standard Extrafield feature - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { - // fetch optionals attributes and labels - dol_include_once('/core/class/extrafields.class.php'); - $extrafields = new ExtraFields($db); - $extralabels = $extrafields->fetch_name_optionals_label('socpeople'); - foreach($extrafields->attribute_type as $key=>&$value) { - if($value == 'radio')$value = 'select'; - } - - - foreach ( $extralabels as $key => $val ) { - - print '' . "\n"; - } - } - - print '' . "\n"; - print '' . "\n"; - print '' . "\n"; - print '
' . "\n"; - - print '' . "\n"; - - print '
' . $langs->trans('AdvTgtNameTemplate') . ''; - if (! empty($template_id)) { - $default_template = $template_id; - } else { - $default_template = $advTarget->id; - } - print $formadvtargetemaling->selectAdvtargetemailingTemplate('template_id', $default_template); - print ''; - print ''; - print ''; - print $langs->trans('AdvTgtOrCreateNewFilter'); - print ''; - print ''; - print '' . "\n"; - print '
' . $langs->trans('AdvTgtTypeOfIncude') . ''; - print $form->selectarray('type_of_target', $advTarget->select_target_type, $array_query['type_of_target']); - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtTypeOfIncudeHelp"), 1, 'help'); - print '
' . $langs->trans('ThirdPartyName'); - if (! empty($array_query['cust_name'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans('CustomerCode'); - if (! empty($array_query['cust_code'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans('Address'); - if (! empty($array_query['cust_adress'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans('Zip'); - if (! empty($array_query['cust_zip'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans('Town'); - if (! empty($array_query['cust_city'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans("Country"); - if (count($array_query['cust_country']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $formadvtargetemaling->multiselectCountry('cust_country', $array_query['cust_country']); - print '' . "\n"; - print '
' . $langs->trans('Status') . ' ' . $langs->trans('ThirdParty'); - if (count($array_query['cust_status']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - print $formadvtargetemaling->advMultiselectarray('cust_status', array ( - '0' => $langs->trans('ActivityCeased'), - '1' => $langs->trans('InActivity') - ), $array_query['cust_status']); - print '' . "\n"; - print '
' . $langs->trans("Maison mère"); - if (! empty($array_query['cust_mothercompany'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print ''; - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans('ProspectCustomer') . ' ' . $langs->trans('ThirdParty'); - if (count($array_query['cust_typecust']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - $options_array = array ( - 2 => $langs->trans('Prospect'), - 3 => $langs->trans('ProspectCustomer'), - 1 => $langs->trans('Customer'), - 0 => $langs->trans('NorProspectNorCustomer') - ); - print $formadvtargetemaling->advMultiselectarray('cust_typecust', $options_array, $array_query['cust_typecust']); - print '' . "\n"; - print '
' . $langs->trans('ProspectLevel'); - if (count($array_query['cust_prospect_status']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - print $formadvtargetemaling->multiselectProspectionStatus($array_query['cust_prospect_status'], 'cust_prospect_status', 1); - print '' . "\n"; - print '
' . $langs->trans('StatusProsp'); - if (count($array_query['cust_comm_status']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - print $formadvtargetemaling->advMultiselectarray('cust_comm_status', $advTarget->type_statuscommprospect, $array_query['cust_comm_status']); - print '' . "\n"; - print '
' . $langs->trans("ThirdPartyType"); - if (count($array_query['cust_typeent']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $formadvtargetemaling->advMultiselectarray('cust_typeent', $formcompany->typent_array(0, " AND id <> 0"), $array_query['cust_typeent']); - print '' . "\n"; - print '
' . $langs->trans("Staff"); - if (count($array_query['cust_effectif_id']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - print $formadvtargetemaling->advMultiselectarray("cust_effectif_id", $formcompany->effectif_array(0, " AND id <> 0"), $array_query['cust_effectif_id']); - print '' . "\n"; - print '
' . $langs->trans("SalesRepresentatives"); - if (count($array_query['cust_saleman']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $formadvtargetemaling->multiselectselectSalesRepresentatives('cust_saleman', $array_query['cust_saleman'], $user); - print '' . "\n"; - print '
' . $langs->trans("DefaultLang"); - if (count($array_query['cust_language']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $formadvtargetemaling->multiselectselectLanguage('cust_language', $array_query['cust_language']); - print '' . "\n"; - print '
' . $langs->trans("CustomersCategoryShort"); - if (count($array_query['cust_categ']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $formadvtargetemaling->multiselectCustomerCategories('cust_categ', $array_query['cust_categ']); - print '' . "\n"; - print '
' . $extrafields->attribute_label[$key]; - if (! empty($array_query['options_' . $key]) || (is_array($array_query['options_' . $key]) && count($array_query['options_' . $key]) > 0)) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - if (($extrafields->attribute_type[$key] == 'varchar') || ($extrafields->attribute_type[$key] == 'text')) { - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - } elseif (($extrafields->attribute_type[$key] == 'int') || ($extrafields->attribute_type[$key] == 'double')) { - print $langs->trans("AdvTgtMinVal") . ''; - print $langs->trans("AdvTgtMaxVal") . ''; - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchIntHelp"), 1, 'help'); - } elseif (($extrafields->attribute_type[$key] == 'date') || ($extrafields->attribute_type[$key] == 'datetime')) { - - print ''; - print '
' . $langs->trans("AdvTgtStartDt") . ''; - print $form->select_date('', 'options_' . $key . '_st_dt'); - print '' . $langs->trans("AdvTgtEndDt") . ''; - print $form->select_date('', 'options_' . $key . '_end_dt'); - print '
'; - - print '
' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchDtHelp"), 1, 'help'); - } elseif (($extrafields->attribute_type[$key] == 'boolean')) { - print $form->selectarray('options_' . $key, array ( - '' => '', - '1' => $langs->trans('Yes'), - '0' => $langs->trans('No') - ), $array_query['options_' . $key]); - print '' . "\n"; - } elseif (($extrafields->attribute_type[$key] == 'select')) { - print $formadvtargetemaling->advMultiselectarray('options_' . $key, $extrafields->attribute_param[$key]['options'], $array_query['options_' . $key]); - print '' . "\n"; - } elseif (($extrafields->attribute_type[$key] == 'sellist')) { - print $formadvtargetemaling->advMultiselectarraySelllist('options_' . $key, $extrafields->attribute_param[$key]['options'], $array_query['options_' . $key]); - print '' . "\n"; - } else { - - print ''; - print '
'; - if (is_array($array_query['options_' . $key])) { - print $extrafields->showInputField($key, implode(',', $array_query['options_' . $key])); - } else { - print $extrafields->showInputField($key, $array_query['options_' . $key]); - } - print '
'; - - print '
' . "\n"; - } - print '
' . $langs->trans('Status') . ' ' . $langs->trans('Contact'); - if (count($array_query['contact_status']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - print $formadvtargetemaling->advMultiselectarray('contact_status', array ( - '0' => $langs->trans('ActivityCeased'), - '1' => $langs->trans('InActivity') - ), $array_query['contact_status']); - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtContactHelp"), 1, 'help'); - print '
' . $langs->trans("UserTitle"); - if (count($array_query['contact_civility']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - print $formadvtargetemaling->multiselectCivility('contact_civility', $array_query['contact_civility']); - print '
' . $langs->trans('Contact') . ' ' . $langs->trans('Lastname'); - if (! empty($array_query['contact_lastname'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans('Contact') . ' ' . $langs->trans('Firstname'); - if (! empty($array_query['contact_firstname'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - print '
' . $langs->trans('Contact') . ' ' . $langs->trans("Country"); - if (count($array_query['contact_country']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $formadvtargetemaling->multiselectCountry('contact_country', $array_query['contact_country']); - print '' . "\n"; - print '
' . $langs->trans('Contact') . ' ' . $langs->trans("No_Email"); - if (! empty($array_query['contact_no_email'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $form->selectarray('contact_no_email', array ( - '' => '', - '1' => $langs->trans('Yes'), - '0' => $langs->trans('No') - ), $array_query['contact_no_email']); - print '' . "\n"; - print '
' . $langs->trans('Contact') . ' ' . $langs->trans("DateCreation"); - if (! empty($array_query['contact_create_st_dt'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print ''; - print '
' . $langs->trans("AdvTgtStartDt") . ''; - print $form->select_date($array_query['contact_create_st_dt'], 'contact_create_st_dt', 0, 0, 1, 'find_customer', 1, 1); - print '' . $langs->trans("AdvTgtEndDt") . ''; - print $form->select_date($array_query['contact_create_end_dt'], 'contact_create_end_dt', 0, 0, 1, 'find_customer', 1, 1); - print '
'; - print '
' . "\n"; - print '
' . $langs->trans('Contact') . ' ' . $langs->trans("DateLastModification"); - if (! empty($array_query['contact_update_st_dt'])) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print ''; - print '
' . $langs->trans("AdvTgtStartDt") . ''; - print $form->select_date($array_query['contact_update_st_dt'], 'contact_update_st_dt', 0, 0, 1, 'find_customer', 1, 1); - print '' . $langs->trans("AdvTgtEndDt") . ''; - print $form->select_date($array_query['contact_update_end_dt'], 'contact_update_end_dt', 0, 0, 1, 'find_customer', 1, 1); - print '
'; - print '
' . "\n"; - print '
' . $langs->trans("ContactCategoriesShort"); - if (count($array_query['contact_categ']) > 0) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print '' . "\n"; - print $formadvtargetemaling->multiselectContactCategories('contact_categ', $array_query['contact_categ']); - print '' . "\n"; - print '
' . $extrafields->attribute_label[$key]; - if ($array_query['options_' . $key . '_cnct'] != '' || (is_array($array_query['options_' . $key . '_cnct']) && count($array_query['options_' . $key . '_cnct']) > 0)) { - print img_picto($langs->trans('AdvTgtUse'), 'ok.png@advtargetemailing'); - } - print ''; - if (($extrafields->attribute_type[$key] == 'varchar') || ($extrafields->attribute_type[$key] == 'text')) { - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchTextHelp"), 1, 'help'); - } elseif (($extrafields->attribute_type[$key] == 'int') || ($extrafields->attribute_type[$key] == 'double')) { - print $langs->trans("AdvTgtMinVal") . ''; - print $langs->trans("AdvTgtMaxVal") . ''; - print '' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchIntHelp"), 1, 'help'); - } elseif (($extrafields->attribute_type[$key] == 'date') || ($extrafields->attribute_type[$key] == 'datetime')) { - - print ''; - print '
' . $langs->trans("AdvTgtStartDt") . ''; - print $form->select_date('', 'options_' . $key . '_st_dt' . '_cnct'); - print '' . $langs->trans("AdvTgtEndDt") . ''; - print $form->select_date('', 'options_' . $key . '_end_dt' . '_cnct'); - print '
'; - - print '
' . "\n"; - print $form->textwithpicto('', $langs->trans("AdvTgtSearchDtHelp"), 1, 'help'); - } elseif (($extrafields->attribute_type[$key] == 'boolean')) { - print $form->selectarray('options_' . $key . '_cnct', array ( - '' => '', - '1' => $langs->trans('Yes'), - '0' => $langs->trans('No') - ), $array_query['options_' . $key . '_cnct']); - print '' . "\n"; - } elseif (($extrafields->attribute_type[$key] == 'select')) { - print $formadvtargetemaling->advMultiselectarray('options_' . $key . '_cnct', $extrafields->attribute_param[$key]['options'], $array_query['options_' . $key . '_cnct']); - print '' . "\n"; - } elseif (($extrafields->attribute_type[$key] == 'sellist')) { - print $formadvtargetemaling->advMultiselectarraySelllist('options_' . $key . '_cnct', $extrafields->attribute_param[$key]['options'], $array_query['options_' . $key . '_cnct']); - print '' . "\n"; - } else { - - print ''; - print '
'; - if (is_array($array_query['options_' . $key . '_cnct'])) { - print $extrafields->showInputField($key, implode(',', $array_query['options_' . $key . '_cnct']), '', '_cnct'); - } else { - print $extrafields->showInputField($key, $array_query['options_' . $key . '_cnct'], '', '_cnct'); - } - print '
'; - - print '
' . "\n"; - } - print '
' . "\n"; - - print '' . "\n"; - - print '
' . "\n"; - print '' . "\n"; - print '' . "\n"; - - print '
'; - print ''; - print_titre($langs->trans("ToClearAllRecipientsClickHere")); - print ''; - print ''; - print ''; - print ''; - print '
'; - print '
'; - print '
'; + + include DOL_DOCUMENT_ROOT . '/core/tpl/advtarget.tpl.php'; + } } llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index db19e943b4b..97746ad9d82 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; +// Load translation files required by the page $langs->load("mails"); if (! $user->rights->mailing->lire || (empty($conf->global->EXTERNAL_USERS_ARE_AUTHORIZED) && $user->societe_id > 0)) accessforbidden(); @@ -244,7 +245,7 @@ if (empty($reshook)) $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); } } - /* For backward compatibility */ + /* For backward compatibility, deprecated */ if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN)) { $substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); @@ -754,7 +755,7 @@ if ($action == 'create') $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } @@ -967,7 +968,7 @@ else * Boutons d'action */ - if (GETPOST('cancel','alpha') || $confirm=='no' || $action == '' || in_array($action,array('settodraft', 'valid','delete','sendall','clone'))) + if (GETPOST('cancel','alpha') || $confirm=='no' || $action == '' || in_array($action,array('settodraft','valid','delete','sendall','clone','test'))) { print "\n\n
\n"; @@ -1071,7 +1072,9 @@ else print '
'; print load_fiche_titre($langs->trans("TestMailing")); - // Create l'objet formulaire mail + dol_fiche_head(null, '', '', -1); + + // Create l'objet formulaire mail include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); $formmail->fromname = $object->email_from; @@ -1099,6 +1102,10 @@ else print $formmail->get_form(); print '
'; + + dol_fiche_end(); + + print dol_set_focus('#sendto'); } @@ -1114,7 +1121,7 @@ else dol_fiche_head('', '', '', -1); - print ''; + print '
'; // Subject print ''; @@ -1229,7 +1236,7 @@ else $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } @@ -1260,7 +1267,7 @@ else dol_fiche_head(null, '', '', -1); - print '
'.$langs->trans("MailTopic").''.$object->sujet.'
'; + print '
'; // Subject print ''; diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index 57af9f5c601..08ed54d2fc3 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -32,6 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +// Load translation files required by the page $langs->load("mails"); // Security check @@ -75,8 +76,6 @@ if ($action == 'add') $module=GETPOST("module"); $result=-1; - $var=true; - foreach ($modulesdir as $dir) { // Load modules attributes in arrays (name, numero, orders) from dir directory @@ -260,7 +259,7 @@ if ($object->fetch($id) >= 0) print load_fiche_titre($langs->trans("ToAddRecipientsChooseHere"), ($user->admin?info_admin($langs->trans("YouCanAddYourOwnPredefindedListHere"),1):''), 'title_generic'); //print '
'.$langs->trans("MailTopic").'
'; - print '
'; + print '
'; //print '
'; print '
'; @@ -277,8 +276,6 @@ if ($object->fetch($id) >= 0) clearstatcache(); - $var = true; - foreach ($modulesdir as $dir) { $modulenames=array(); @@ -306,6 +303,8 @@ if ($object->fetch($id) >= 0) // Sort $modulenames sort($modulenames); + $var = true; + // Loop on each submodule foreach($modulenames as $modulename) { @@ -331,7 +330,7 @@ if ($object->fetch($id) >= 0) // Si le module mailing est qualifie if ($qualified) { - $var = !$var; + $var = ! $var; if ($allowaddtarget) { @@ -425,7 +424,13 @@ if ($object->fetch($id) >= 0) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } + //$nbtotalofrecords=$object->nbemail; // nbemail is a denormalized field storing nb of targets $sql .= $db->plimit($limit+1, $offset); @@ -555,7 +560,7 @@ if ($object->fetch($id) >= 0) include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $objectstatic=new Adherent($db); $objectstatic->fetch($obj->source_id); - print $objectstatic->getNomUrl(2); + print $objectstatic->getNomUrl(1); } else if ($obj->source_type == 'user') { @@ -563,14 +568,21 @@ if ($object->fetch($id) >= 0) $objectstatic=new User($db); $objectstatic->fetch($obj->source_id); $objectstatic->id=$obj->source_id; - print $objectstatic->getNomUrl(2); + print $objectstatic->getNomUrl(1); } else if ($obj->source_type == 'thirdparty') { include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $objectstatic=new Societe($db); $objectstatic->fetch($obj->source_id); - print $objectstatic->getNomUrl(2); + print $objectstatic->getNomUrl(1); + } + else if ($obj->source_type == 'contact') + { + include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + $objectstatic=new Contact($db); + $objectstatic->fetch($obj->source_id); + print $objectstatic->getNomUrl(1); } else { diff --git a/htdocs/comm/mailing/class/advtargetemailing.class.php b/htdocs/comm/mailing/class/advtargetemailing.class.php index 70efeccead3..50d9faf0637 100644 --- a/htdocs/comm/mailing/class/advtargetemailing.class.php +++ b/htdocs/comm/mailing/class/advtargetemailing.class.php @@ -39,7 +39,8 @@ class AdvanceTargetingMailing extends CommonObject var $name; var $entity; - var $fk_mailing; + var $fk_element; + var $type_element; var $filtervalue; var $fk_user_author; var $datec=''; @@ -92,7 +93,9 @@ class AdvanceTargetingMailing extends CommonObject $error=0; // Clean parameters - if (isset($this->fk_mailing)) $this->fk_mailing=trim($this->fk_mailing); + if (isset($this->fk_element)) $this->fk_element=trim($this->fk_element); + if (isset($this->type_element)) $this->type_element=trim($this->type_element); + if (isset($this->name)) $this->name=trim($this->name); if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue); if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author); @@ -108,7 +111,8 @@ class AdvanceTargetingMailing extends CommonObject $sql.= "name,"; $sql.= "entity,"; - $sql.= "fk_mailing,"; + $sql.= "fk_element,"; + $sql.= "type_element,"; $sql.= "filtervalue,"; $sql.= "fk_user_author,"; $sql.= "datec,"; @@ -119,7 +123,8 @@ class AdvanceTargetingMailing extends CommonObject $sql.= " ".(! isset($this->name)?'NULL':"'".$this->db->escape($this->name)."'").","; $sql.= " ".$conf->entity.","; - $sql.= " ".(! isset($this->fk_mailing)?'NULL':"'".$this->db->escape($this->fk_mailing)."'").","; + $sql.= " ".(! isset($this->fk_element)?'NULL':"'".$this->db->escape($this->fk_element)."'").","; + $sql.= " ".(! isset($this->type_element)?'NULL':"'".$this->db->escape($this->type_element)."'").","; $sql.= " ".(! isset($this->filtervalue)?'NULL':"'".$this->db->escape($this->filtervalue)."'").","; $sql.= " ".$user->id.","; $sql.= " '".$this->db->idate(dol_now())."',"; @@ -184,7 +189,8 @@ class AdvanceTargetingMailing extends CommonObject $sql.= " t.name,"; $sql.= " t.entity,"; - $sql.= " t.fk_mailing,"; + $sql.= " t.fk_element,"; + $sql.= " t.type_element,"; $sql.= " t.filtervalue,"; $sql.= " t.fk_user_author,"; $sql.= " t.datec,"; @@ -206,7 +212,8 @@ class AdvanceTargetingMailing extends CommonObject $this->name = $obj->name; $this->entity = $obj->entity; - $this->fk_mailing = $obj->fk_mailing; + $this->fk_element = $obj->fk_element; + $this->type_element = $obj->type_element; $this->filtervalue = $obj->filtervalue; $this->fk_user_author = $obj->fk_user_author; $this->datec = $this->db->jdate($obj->datec); @@ -240,7 +247,8 @@ class AdvanceTargetingMailing extends CommonObject $sql.= " t.name,"; $sql.= " t.entity,"; - $sql.= " t.fk_mailing,"; + $sql.= " t.fk_element,"; + $sql.= " t.type_element,"; $sql.= " t.filtervalue,"; $sql.= " t.fk_user_author,"; $sql.= " t.datec,"; @@ -249,9 +257,9 @@ class AdvanceTargetingMailing extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; if (!empty($id)) { - $sql.= " WHERE t.fk_mailing = ".$id; + $sql.= " WHERE t.fk_element = ".$id." AND type_element='mailing'"; }else { - $sql.= " WHERE t.fk_mailing = ".$this->fk_mailing; + $sql.= " WHERE t.fk_element = ".$this->fk_element." AND type_element='mailing'"; } dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); @@ -266,7 +274,74 @@ class AdvanceTargetingMailing extends CommonObject $this->name = $obj->name; $this->entity = $obj->entity; - $this->fk_mailing = $obj->fk_mailing; + $this->fk_element = $obj->fk_element; + $this->type_element = $obj->type_element; + $this->filtervalue = $obj->filtervalue; + $this->fk_user_author = $obj->fk_user_author; + $this->datec = $this->db->jdate($obj->datec); + $this->fk_user_mod = $obj->fk_user_mod; + $this->tms = $this->db->jdate($obj->tms); + + } + $this->db->free($resql); + + return 1; + } + else + { + $this->error="Error ".$this->db->lasterror(); + dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); + return -1; + } + } + + + + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $type_element Type target + * @return int <0 if KO, >0 if OK + */ + function fetch_by_element($id=0, $type_element='mailing') + { + global $langs; + $sql = "SELECT"; + $sql.= " t.rowid,"; + + $sql.= " t.name,"; + $sql.= " t.entity,"; + $sql.= " t.fk_element,"; + $sql.= " t.type_element,"; + $sql.= " t.filtervalue,"; + $sql.= " t.fk_user_author,"; + $sql.= " t.datec,"; + $sql.= " t.fk_user_mod,"; + $sql.= " t.tms"; + + $sql.= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; + if (!empty($id)) { + $sql.= " WHERE t.fk_element = ".$id." AND type_element='$type_element'"; + }else { + $sql.= " WHERE t.fk_element = ".$this->fk_element." AND type_element='$type_element'"; + } + + dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + + $this->name = $obj->name; + $this->entity = $obj->entity; + $this->fk_element = $obj->fk_element; + $this->type_element = $obj->type_element; $this->filtervalue = $obj->filtervalue; $this->fk_user_author = $obj->fk_user_author; $this->datec = $this->db->jdate($obj->datec); @@ -299,7 +374,8 @@ class AdvanceTargetingMailing extends CommonObject $error=0; // Clean parameters - if (isset($this->fk_mailing)) $this->fk_mailing=trim($this->fk_mailing); + if (isset($this->fk_element)) $this->fk_element=trim($this->fk_element); + if (isset($this->type_element)) $this->type_element=trim($this->type_element); if (isset($this->name)) $this->name=trim($this->name); if (isset($this->filtervalue)) $this->filtervalue=trim($this->filtervalue); if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author); @@ -315,14 +391,14 @@ class AdvanceTargetingMailing extends CommonObject $sql.= " name=".(isset($this->name)?"'".$this->db->escape($this->name)."'":"''").","; $sql.= " entity=".$conf->entity.","; - $sql.= " fk_mailing=".(isset($this->fk_mailing)?$this->fk_mailing:"null").","; + $sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").","; + $sql.= " type_element=".(isset($this->type_element)?"'".$this->db->escape($this->type_element)."'":"null").","; $sql.= " filtervalue=".(isset($this->filtervalue)?"'".$this->db->escape($this->filtervalue)."'":"null").","; $sql.= " fk_user_mod=".$user->id; $sql.= " WHERE rowid=".$this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -432,7 +508,7 @@ class AdvanceTargetingMailing extends CommonObject global $langs,$conf; if (!empty($arrayquery)) { - $result=$this->fetch_by_mailing($this->fk_mailing); + $result=$this->fetch_by_mailing($this->fk_element); $this->filtervalue=json_encode($arrayquery); if ($result<0) { return -1; diff --git a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php index c7f425f8f7a..7408bb27d37 100644 --- a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php +++ b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php @@ -409,21 +409,22 @@ class FormAdvTargetEmailing extends Form } /** - * selectAdvtargetemailingTemplate + * Return a combo list to select emailing target selector * - * @param string $htmlname control name - * @param integer $selected defaut selected - * @param integer $showempty empty lines - * - * @return string HTML combo + * @param string $htmlname control name + * @param integer $selected defaut selected + * @param integer $showempty empty lines + * @param string $type_element Type element. Example: 'mailing' + * @return string HTML combo */ - public function selectAdvtargetemailingTemplate($htmlname='template_id',$selected=0,$showempty=0) { + public function selectAdvtargetemailingTemplate($htmlname='template_id', $selected=0, $showempty=0, $type_element='mailing') { global $conf, $user, $langs; $out = ''; - $sql = "SELECT c.rowid, c.name, c.fk_mailing"; + $sql = "SELECT c.rowid, c.name, c.fk_element"; $sql .= " FROM " . MAIN_DB_PREFIX . "advtargetemailing as c"; + $sql .= " WHERE type_element='$type_element'"; $sql .= " ORDER BY c.name"; dol_syslog ( get_class ( $this ) . "::".__METHOD__, LOG_DEBUG ); @@ -441,7 +442,7 @@ class FormAdvTargetEmailing extends Form $obj = $this->db->fetch_object ( $resql ); $label = $obj->name; if (empty($label)) { - $label=$obj->fk_mailing; + $label=$obj->fk_element; } if ($selected > 0 && $selected == $obj->rowid) { diff --git a/htdocs/comm/mailing/index.php b/htdocs/comm/mailing/index.php index 52eacf6c115..17693a1a73c 100644 --- a/htdocs/comm/mailing/index.php +++ b/htdocs/comm/mailing/index.php @@ -27,8 +27,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT .'/comm/mailing/class/mailing.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -$langs->load("commercial"); -$langs->load("orders"); +// Load translation files required by the page +$langs->loadLangs(array('commercial', 'orders')); // Security check @@ -52,7 +52,6 @@ print '
'; //if (! empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo //{ // Recherche emails - $var=false; print '
'; print ''; print '
'; @@ -62,7 +61,7 @@ print '
'; print '
'; print ''; - + print "
'; print $langs->trans("Other").':

\n"; //} @@ -74,7 +73,6 @@ print '
'.$langs->trans("TargetsStatistic $dir=DOL_DOCUMENT_ROOT."/core/modules/mailings"; $handle=opendir($dir); -$var=True; if (is_resource($handle)) { while (($file = readdir($handle))!==false) @@ -106,8 +104,6 @@ if (is_resource($handle)) // Si le module mailing est qualifi� if ($qualified) { - $var = !$var; - foreach ($mailmodule->getSqlArrayForStats() as $sql) { print '
'.img_object($langs->trans("ShowEMail"),"email").' '.$obj->rowid.'
'."\n"; diff --git a/htdocs/comm/multiprix.php b/htdocs/comm/multiprix.php index dd4e6cef1fa..1e8c5c82cf4 100644 --- a/htdocs/comm/multiprix.php +++ b/htdocs/comm/multiprix.php @@ -27,8 +27,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; -$langs->load("orders"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('orders', 'companies')); $id = GETPOST('id','int'); $_socid = GETPOST("id",'int'); diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index b2290b0f598..bf4bd28ab7a 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -56,14 +56,8 @@ if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } -$langs->load('companies'); -$langs->load('propal'); -$langs->load('compta'); -$langs->load('bills'); -$langs->load('orders'); -$langs->load('products'); -$langs->load("deliveries"); -$langs->load('sendings'); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'propal', 'compta', 'bills', 'orders', 'products', 'deliveries', 'sendings')); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); if (! empty($conf->margin->enabled)) $langs->load('margins'); @@ -105,16 +99,31 @@ if ($id > 0 || ! empty($ref)) { $ret = $object->fetch($id, $ref); if ($ret > 0) $ret = $object->fetch_thirdparty(); - if ($ret < 0) - dol_print_error('', $object->error); + if ($ret <= 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $action = ''; + } } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('propalcard','globalcard')); -$permissionnote = $user->rights->propale->creer; // Used by the include of actions_setnotes.inc.php -$permissiondellink=$user->rights->propale->creer; // Used by the include of actions_dellink.inc.php -$permissiontoedit = $user->rights->propale->creer; // Used by the include of actions_lineupdown.inc.php +$usercanread = $user->rights->propal->lire; +$usercancreate = $user->rights->propal->creer; +$usercanclose = $user->rights->propal->cloturer; +$usercandelete = $user->rights->propal->supprimer; +$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))); +$usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->propal->propal_advance->send); + +$usercancreateorder = $user->rights->commande->creer; +$usercancreateinvoice = $user->rights->facture->creer; +$usercancreatecontract = $user->rights->contrat->creer; +$usercancreateintervention = $user->rights->ficheinter->creer; + +$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php +$permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php /* @@ -144,7 +153,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes') + if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) { if (! GETPOST('socid', 3)) { @@ -195,7 +204,7 @@ if (empty($reshook)) } // Delete proposal - else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->propal->supprimer) + else if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { $result = $object->delete($user); if ($result > 0) { @@ -208,7 +217,7 @@ if (empty($reshook)) } // Remove line - else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->propal->creer) + else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { $result = $object->deleteline($lineid); // reorder lines @@ -232,10 +241,7 @@ if (empty($reshook)) } // Validation - else if ($action == 'confirm_validate' && $confirm == 'yes' && - ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->creer)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->propal->propal_advance->validate))) - ) + else if ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) { $result = $object->valid($user); if ($result >= 0) @@ -262,7 +268,7 @@ if (empty($reshook)) } } - else if ($action == 'setdate' && $user->rights->propal->creer) + else if ($action == 'setdate' && $usercancreate) { $datep = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); @@ -277,13 +283,13 @@ if (empty($reshook)) dol_print_error($db, $object->error); } } - else if ($action == 'setecheance' && $user->rights->propal->creer) + else if ($action == 'setecheance' && $usercancreate) { $result = $object->set_echeance($user, dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear'])); if ($result < 0) dol_print_error($db, $object->error); } - else if ($action == 'setdate_livraison' && $user->rights->propal->creer) + else if ($action == 'setdate_livraison' && $usercancreate) { $result = $object->set_date_livraison($user, dol_mktime(12, 0, 0, $_POST['date_livraisonmonth'], $_POST['date_livraisonday'], $_POST['date_livraisonyear'])); if ($result < 0) @@ -291,7 +297,7 @@ if (empty($reshook)) } // Positionne ref client - else if ($action == 'setref_client' && $user->rights->propal->creer) + else if ($action == 'setref_client' && $usercancreate) { $result = $object->set_ref_client($user, GETPOST('ref_client')); if ($result < 0) @@ -301,13 +307,13 @@ if (empty($reshook)) } // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) + elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled) && $usercancreate) { $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); } // Create proposal - else if ($action == 'add' && $user->rights->propal->creer) + else if ($action == 'add' && $usercancreate) { $object->socid = $socid; $object->fetch_thirdparty(); @@ -503,7 +509,7 @@ if (empty($reshook)) // Extrafields if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) { - $lines[$i]->fetch_optionals($lines[$i]->rowid); + $lines[$i]->fetch_optionals(); $array_options = $lines[$i]->array_options; } @@ -601,7 +607,7 @@ if (empty($reshook)) } // Classify billed - else if ($action == 'classifybilled' && $user->rights->propal->cloturer) + else if ($action == 'classifybilled' && $usercanclose) { $result=$object->cloture($user, 4, ''); if ($result < 0) @@ -612,7 +618,7 @@ if (empty($reshook)) } // Close proposal - else if ($action == 'setstatut' && $user->rights->propal->cloturer && ! GETPOST('cancel','alpha')) + else if ($action == 'setstatut' && $usercanclose && ! GETPOST('cancel','alpha')) { if (! (GETPOST('statut','int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CloseAs")), null, 'errors'); @@ -632,7 +638,7 @@ if (empty($reshook)) } // Reopen proposal - else if ($action == 'confirm_reopen' && $user->rights->propal->cloturer && ! GETPOST('cancel','alpha')) + else if ($action == 'confirm_reopen' && $usercanclose && ! GETPOST('cancel','alpha')) { // prevent browser refresh from reopening proposal several times if ($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) @@ -657,7 +663,7 @@ if (empty($reshook)) // Go back to draft - if ($action == 'modif' && $user->rights->propal->creer) + if ($action == 'modif' && $usercancreate) { $object->set_draft($user); @@ -675,7 +681,7 @@ if (empty($reshook)) } } - else if ($action == "setabsolutediscount" && $user->rights->propal->creer) { + else if ($action == "setabsolutediscount" && $usercancreate) { if ($_POST["remise_id"]) { if ($object->id > 0) { $result = $object->insert_discount($_POST["remise_id"]); @@ -687,7 +693,7 @@ if (empty($reshook)) } // Add line - else if ($action == 'addline' && $user->rights->propal->creer) { + else if ($action == 'addline' && $usercancreate) { // Set if we used free entry or predefined product $predef=''; @@ -846,7 +852,28 @@ if (empty($reshook)) // If price per quantity and customer elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - // TODO Same than PRODUIT_CUSTOMER_PRICES_BY_QTY but using $object->thirdparty->price_level + if ($prod->prices_by_qty[$object->thirdparty->price_level]) // yes, this product has some prices per quantity + { + // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. + $pqp = GETPOST('pbq','int'); + + // Search price into product_price_by_qty from $prod->id + foreach($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) + { + if ($priceforthequantityarray['rowid'] != $pqp) continue; + // We found the price + if ($priceforthequantityarray['price_base_type'] == 'HT') + { + $pu_ht = $priceforthequantityarray['unitprice']; + } + else + { + $pu_ttc = $priceforthequantityarray['unitprice']; + } + // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST. + break; + } + } } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx)); @@ -1029,7 +1056,7 @@ if (empty($reshook)) } // Update a line within proposal - else if ($action == 'updateligne' && $user->rights->propal->creer && GETPOST('save')) + else if ($action == 'updateligne' && $usercancreate && GETPOST('save')) { // Define info_bits $info_bits = 0; @@ -1166,73 +1193,75 @@ if (empty($reshook)) } } - else if ($action == 'updateligne' && $user->rights->propal->creer && GETPOST('cancel','alpha')) + else if ($action == 'updateligne' && $usercancreate && GETPOST('cancel','alpha')) { header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id); // Pour reaffichage de la fiche en cours d'edition exit(); } // Set project - else if ($action == 'classin' && $user->rights->propal->creer) { + else if ($action == 'classin' && $usercancreate) { $object->setProject(GETPOST('projectid','int')); } // Delai de livraison - else if ($action == 'setavailability' && $user->rights->propal->creer) { + else if ($action == 'setavailability' && $usercancreate) { $result = $object->set_availability($user, GETPOST('availability_id','int')); } // Origine de la propale - else if ($action == 'setdemandreason' && $user->rights->propal->creer) { + else if ($action == 'setdemandreason' && $usercancreate) { $result = $object->set_demand_reason($user, GETPOST('demand_reason_id','int')); } // Conditions de reglement - else if ($action == 'setconditions' && $user->rights->propal->creer) { + else if ($action == 'setconditions' && $usercancreate) { $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); } - else if ($action == 'setremisepercent' && $user->rights->propal->creer) { + else if ($action == 'setremisepercent' && $usercancreate) { $result = $object->set_remise_percent($user, $_POST['remise_percent']); } - else if ($action == 'setremiseabsolue' && $user->rights->propal->creer) { + else if ($action == 'setremiseabsolue' && $usercancreate) { $result = $object->set_remise_absolue($user, $_POST['remise_absolue']); } // Mode de reglement - else if ($action == 'setmode' && $user->rights->propal->creer) { + else if ($action == 'setmode' && $usercancreate) { $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); } // Multicurrency Code - else if ($action == 'setmulticurrencycode' && $user->rights->propal->creer) { + else if ($action == 'setmulticurrencycode' && $usercancreate) { $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); } // Multicurrency rate - else if ($action == 'setmulticurrencyrate' && $user->rights->propal->creer) { + else if ($action == 'setmulticurrencyrate' && $usercancreate) { $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx'))); } // bank account - else if ($action == 'setbankaccount' && $user->rights->propal->creer) { + else if ($action == 'setbankaccount' && $usercancreate) { $result=$object->setBankAccount(GETPOST('fk_account', 'int')); } // shipping method - else if ($action == 'setshippingmethod' && $user->rights->propal->creer) { + else if ($action == 'setshippingmethod' && $usercancreate) { $result=$object->setShippingMethod(GETPOST('shipping_method_id', 'int')); } else if ($action == 'update_extras') { + $object->oldcopy = dol_clone($object); + // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none')); if ($ret < 0) $error++; if (! $error) { - $result = $object->insertExtraFields(); + $result = $object->insertExtraFields('PROPAL_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -1242,7 +1271,7 @@ if (empty($reshook)) if ($error) $action = 'edit_extras'; } - if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->propal->creer) + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { if ($action == 'addcontact') { @@ -1288,8 +1317,8 @@ if (empty($reshook)) } // Actions to build doc - $upload_dir = $conf->propal->dir_output; - $permissioncreate=$user->rights->propal->creer; + $upload_dir = $conf->propal->multidir_output[$object->entity]; + $permissioncreate=$usercancreate; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; } @@ -1367,7 +1396,7 @@ if ($action == 'create') $soc = $objectsrc->thirdparty; - $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1454,17 +1483,13 @@ if ($action == 'create') // Ligne info remises tiers print ''; } @@ -1489,7 +1514,7 @@ if ($action == 'create') // Bank Account if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && ! empty($conf->banque->enabled)) { print ''; } @@ -1709,7 +1734,7 @@ if ($action == 'create') print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); + $absolute_discount = $soc->getAvailableDiscounts(); - print '. '; - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 1, -1, -1, $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; print '
' . $langs->trans('BankAccount') . ''; - $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + $form->select_comptes($soc->fk_account, 'fk_account', 0, '', 1); print '
'; } -} else { +} elseif ($object->id > 0) { /* * Show object in view mode */ @@ -1742,11 +1767,12 @@ if ($action == 'create') { //Form to close proposal (signed or not) $formquestion = array( - array('type' => 'select','name' => 'statut','label' => $langs->trans("CloseAs"),'values' => array(2=>$object->labelstatut [2],3=>$object->labelstatut [3])), - array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '') // Field to complete private note (not replace) + array('type' => 'select','name' => 'statut','label' => $langs->trans("CloseAs"),'values' => array(2=>$object->LibStatut(Propal::STATUS_SIGNED), 3=>$object->LibStatut(Propal::STATUS_NOTSIGNED))), + array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"),'value' => '') // Field to complete private note (not replace) ); - if (! empty($conf->notification->enabled)) { + if (! empty($conf->notification->enabled)) + { require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; $notify = new Notify($db); $formquestion = array_merge($formquestion, array( @@ -1816,20 +1842,19 @@ if ($action == 'create') $linkback = '' . $langs->trans("BackToList") . ''; - $morehtmlref='
'; // Ref customer - $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', 0, 1); - $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->propal->creer, 'string', '', null, null, '', 1); + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty - $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherProposals").')'; // Project if (! empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->propal->creer) + if ($usercancreate) { if ($action != 'classify') $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; @@ -1869,31 +1894,26 @@ if ($action == 'create') print ''; // Link for thirdparty discounts + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + print ''; // Date of proposal @@ -1902,11 +1922,11 @@ if ($action == 'create') print '
' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; - $absolute_discount = $soc->getAvailableDiscounts('', 'fk_facture_source IS NULL'); - $absolute_creditnote = $soc->getAvailableDiscounts('', 'fk_facture_source IS NOT NULL'); + + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > Propal::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount, 0, $langs, 0, 0, -1, $conf->currency)); - } else { - // Remise dispo de type non avoir - $filter = 'fk_facture_source IS NULL'; - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filter, 0, '', 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote, 0, $langs, 0, 0, -1, $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
'; - if ($action != 'editdate' && ! empty($object->brouillon)) + if ($action != 'editdate' && ! empty($object->brouillon) && $usercancreate) print ''; print '
'; print $langs->trans('Date'); print 'id . '">' . img_edit($langs->trans('SetDate'), 1) . '
'; print '
'; - if (! empty($object->brouillon) && $action == 'editdate') { + if (! empty($object->brouillon) && $action == 'editdate' && $usercancreate) { print ''; print ''; print ''; @@ -1915,7 +1935,7 @@ if ($action == 'create') print ''; } else { if ($object->date) { - print dol_print_date($object->date, 'daytext'); + print dol_print_date($object->date, 'day'); } else { print ' '; } @@ -1928,11 +1948,11 @@ if ($action == 'create') print ''; - if ($action != 'editecheance' && ! empty($object->brouillon)) + if ($action != 'editecheance' && ! empty($object->brouillon) && $usercancreate) print ''; print '
'; print $langs->trans('DateEndPropal'); print 'id . '">' . img_edit($langs->trans('SetConditions'), 1) . '
'; print '
'; - if (! empty($object->brouillon) && $action == 'editecheance') { + if (! empty($object->brouillon) && $action == 'editecheance' && $usercancreate) { print '
'; print ''; print ''; @@ -1941,7 +1961,7 @@ if ($action == 'create') print '
'; } else { if (! empty($object->fin_validite)) { - print dol_print_date($object->fin_validite, 'daytext'); + print dol_print_date($object->fin_validite, 'day'); if ($object->statut == Propal::STATUS_VALIDATED && $object->fin_validite < ($now - $conf->propal->cloture->warning_delay)) print img_warning($langs->trans("Late")); } else { @@ -1956,11 +1976,11 @@ if ($action == 'create') print ''; - if ($action != 'editconditions' && ! empty($object->brouillon)) + if ($action != 'editconditions' && ! empty($object->brouillon) && $usercancreate) print ''; print '
'; print $langs->trans('PaymentConditionsShort'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetConditions'), 1) . '
'; print '
'; - if ($action == 'editconditions') { + if (! empty($object->brouillon) && $action == 'editconditions' && $usercancreate) { $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->cond_reglement_id, 'none'); @@ -1971,9 +1991,9 @@ if ($action == 'create') // Delivery date $langs->load('deliveries'); print '
'; - print $form->editfieldkey($langs->trans('DeliveryDate'), 'date_livraison', $object->date_livraison, $object, $user->rights->propal->creer, 'datepicker'); + print $form->editfieldkey($langs->trans('DeliveryDate'), 'date_livraison', $object->date_livraison, $object, $usercancreate, 'datepicker'); print ''; - print $form->editfieldval($langs->trans('DeliveryDate'), 'date_livraison', $object->date_livraison, $object, $user->rights->propal->creer, 'datepicker'); + print $form->editfieldval($langs->trans('DeliveryDate'), 'date_livraison', $object->date_livraison, $object, $usercancreate, 'datepicker'); print '
id . '">' . img_edit($langs->transnoentitiesnoconv('SetAvailability'), 1) . '
'; print '
'; - if ($action == 'editavailability') { + if (! empty($object->brouillon) && $action == 'editavailability' && $usercancreate) { $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'availability_id', 1); } else { $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->availability_id, 'none', 1); @@ -2003,11 +2023,11 @@ if ($action == 'create') print ''; - if ($action != 'editshippingmethod' && $user->rights->propal->creer) + if ($action != 'editshippingmethod' && $usercancreate) print ''; print '
'; print $langs->trans('SendingMethod'); print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; print '
'; - if ($action == 'editshippingmethod') { + if ($action == 'editshippingmethod' && $usercancreate) { $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); } else { $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); @@ -2021,11 +2041,11 @@ if ($action == 'create') print ''; - if ($action != 'editdemandreason' && ! empty($object->brouillon)) + if ($action != 'editdemandreason' && ! empty($object->brouillon) && $usercancreate) print ''; print '
'; print $langs->trans('Source'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetDemandReason'), 1) . '
'; print '
'; - if ($action == 'editdemandreason') { + if (! empty($object->brouillon) && $action == 'editdemandreason' && $usercancreate) { $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'demand_reason_id', 1); } else { $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->demand_reason_id, 'none'); @@ -2039,11 +2059,11 @@ if ($action == 'create') print ''; - if ($action != 'editmode' && ! empty($object->brouillon)) + if ($action != 'editmode' && ! empty($object->brouillon) && $usercancreate) print ''; print '
'; print $langs->trans('PaymentMode'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMode'), 1) . '
'; print '
'; - if ($action == 'editmode') { + if (! empty($object->brouillon) && $action == 'editmode' && $usercancreate) { $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'mode_reglement_id'); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->mode_reglement_id, 'none'); @@ -2059,11 +2079,11 @@ if ($action == 'create') print ''; - if ($action != 'editmulticurrencycode' && ! empty($object->brouillon)) + if ($action != 'editmulticurrencycode' && ! empty($object->brouillon) && $usercancreate) print ''; print '
'; print fieldLabel('Currency','multicurrency_code'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
'; print '
'; - if ($action == 'editmulticurrencycode') { + if (! empty($object->brouillon) && $action == 'editmulticurrencycode' && $usercancreate) { $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code'); } else { $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none'); @@ -2076,11 +2096,11 @@ if ($action == 'create') print ''; - if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) + if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $usercancreate) print ''; print '
'; print fieldLabel('CurrencyRate','multicurrency_tx'); print 'id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '
'; print '
'; - if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { + if (! empty($object->brouillon) && ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') && $usercancreate) { if($action == 'actualizemulticurrencyrate') { list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code); } @@ -2115,7 +2135,7 @@ if ($action == 'create') print ''; - if ($action != 'editbankaccount' && $user->rights->propal->creer) + if ($action != 'editbankaccount' && $usercancreate) print ''; print '
'; print $langs->trans('BankAccount'); print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; print '
'; @@ -2128,6 +2148,22 @@ if ($action == 'create') print '
' . $langs->trans("CalculatedWeight") . ''; + print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); + print '
' . $langs->trans("CalculatedVolume") . ''; + print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); + print '
'; print $langs->trans('IncotermLabel'); print ''; - if ($user->rights->propal->creer) print ''.img_edit().''; + if ($usercancreate) print ''.img_edit().''; else print ' '; print '
'; print '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
\n"; diff --git a/htdocs/comm/propal/index.php b/htdocs/comm/propal/index.php index a313ab299f0..0dbe2fb855e 100644 --- a/htdocs/comm/propal/index.php +++ b/htdocs/comm/propal/index.php @@ -27,8 +27,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT .'/comm/propal/class/propal.class.php'; -$langs->load("propal"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('propal', 'companies')); // Security check $socid=GETPOST('socid','int'); @@ -216,7 +216,7 @@ $max=5; * Last modified proposals */ -$sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom as socname, s.rowid as socid, s.canvas, s.client,"; +$sql = "SELECT c.rowid, c.entity, c.ref, c.fk_statut, s.nom as socname, s.rowid as socid, s.canvas, s.client,"; $sql.= " date_cloture as datec"; $sql.= " FROM ".MAIN_DB_PREFIX."propal as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; @@ -262,7 +262,7 @@ if ($resql) print ''; $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir); print ''; @@ -296,7 +296,8 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) $now=dol_now(); - $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client, p.rowid as propalid, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; + $sql = "SELECT s.nom as socname, s.rowid as socid, s.canvas, s.client"; + $sql.= ", p.rowid as propalid, p.entity, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."propal as p"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -341,7 +342,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) print ''; print ''; $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->propalid; print $formfile->getDocumentsLink($propalstatic->element, $filename, $filedir); print ''; diff --git a/htdocs/comm/propal/info.php b/htdocs/comm/propal/info.php index 67cc8210402..317c9902d52 100644 --- a/htdocs/comm/propal/info.php +++ b/htdocs/comm/propal/info.php @@ -32,8 +32,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load('propal'); -$langs->load('compta'); +// Load translation files required by the page +$langs->loadLangs(array('propal', 'compta')); $id=GETPOST('id','int'); $ref=GETPOST('ref','alpha'); diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index eb16e54bbbb..a40a6e25b97 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -10,8 +10,9 @@ * Copyright (C) 2012 Christophe Battarel * Copyright (C) 2013 Cédric Salvador * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2016 Ferran Marcet + * Copyright (C) 2016-2018 Ferran Marcet * Copyright (C) 2017 Charlene Benke + * Copyright (C) 2018 Nicolas ZABOURI * * 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,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -$langs->loadLangs(array('companies','propal','compta','bills','orders','products')); +// Load translation files required by the page +$langs->loadLangs(array('companies','propal','compta','bills','orders','products','deliveries')); $socid=GETPOST('socid','int'); @@ -52,6 +54,7 @@ $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'proposallist'; $search_user=GETPOST('search_user','int'); $search_sale=GETPOST('search_sale','int'); @@ -74,6 +77,14 @@ $search_type_thirdparty=GETPOST("search_type_thirdparty",'int'); $search_day=GETPOST("search_day","int"); $search_month=GETPOST("search_month","int"); $search_year=GETPOST("search_year","int"); +$search_dayfin=GETPOST("search_dayfin","int"); +$search_month_end=GETPOST("search_month_end","int"); +$search_yearfin=GETPOST("search_yearfin","int"); +$search_daydelivery=GETPOST("search_daydelivery","int"); +$search_monthdelivery=GETPOST("search_monthdelivery","int"); +$search_yeardelivery=GETPOST("search_yeardelivery","int"); +$search_availability=GETPOST('search_availability','int'); +$search_categ_cus=trim(GETPOST("search_categ_cus",'int')); $search_btn=GETPOST('button_search','alpha'); $search_remove_btn=GETPOST('button_removefilter','alpha'); @@ -85,7 +96,7 @@ $sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alp $mesg=(GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -96,9 +107,6 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield='p.ref'; if (! $sortorder) $sortorder='DESC'; -// Initialize technical object to manage context to save list fields -$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'proposallist'; - // Security check $module='propal'; $dbtable=''; @@ -112,9 +120,10 @@ if (! empty($socid)) } $result = restrictedArea($user, $module, $objectid, $dbtable); -$diroutputmassaction=$conf->propal->dir_output . '/temp/massgeneration/'.$user->id; +$diroutputmassaction=$conf->propal->multidir_output[$conf->entity] . '/temp/massgeneration/'.$user->id; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$object = new Propal($db); $hookmanager->initHooks(array('propallist')); $extrafields = new ExtraFields($db); @@ -146,6 +155,8 @@ $arrayfields=array( 'typent.code'=>array('label'=>$langs->trans("ThirdPartyType"), 'checked'=>$checkedtypetiers), 'p.date'=>array('label'=>$langs->trans("Date"), 'checked'=>1), 'p.fin_validite'=>array('label'=>$langs->trans("DateEnd"), 'checked'=>1), + 'p.date_livraison'=>array('label'=>$langs->trans("DeliveryDate"), 'checked'=>0), + 'ava.rowid'=>array('label'=>$langs->trans("AvailabilityPeriod"), 'checked'=>0), 'p.total_ht'=>array('label'=>$langs->trans("AmountHT"), 'checked'=>1), 'p.total_vat'=>array('label'=>$langs->trans("AmountVAT"), 'checked'=>0), 'p.total_ttc'=>array('label'=>$langs->trans("AmountTTC"), 'checked'=>0), @@ -203,10 +214,19 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x', $search_year=''; $search_month=''; $search_day=''; + $search_yearfin=''; + $search_month_end=''; + $search_dayfin=''; + $search_yeardelivery=''; + $search_monthdelivery=''; + $search_daydelivery=''; + $search_availability=''; $viewstatut=''; $object_statut=''; $toselect=''; $search_array_options=array(); + $search_categ_cus=0; + } if ($object_statut != '') $viewstatut=$object_statut; @@ -216,7 +236,8 @@ if (empty($reshook)) $objectlabel='Proposals'; $permtoread = $user->rights->propal->lire; $permtodelete = $user->rights->propal->supprimer; - $uploaddir = $conf->propal->dir_output; + $permtoclose = $user->rights->propal->cloturer; + $uploaddir = $conf->propal->multidir_output[$conf->entity]; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -243,12 +264,15 @@ $sql = 'SELECT'; if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT'; $sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client, '; $sql.= " typent.code as typent_code,"; +$sql.= " ava.rowid as availability,"; $sql.= " state.code_departement as state_code, state.nom as state_name,"; -$sql.= ' p.rowid, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,'; +$sql.= ' p.rowid, p.entity, p.note_private, p.total_ht, p.tva as total_vat, p.total as total_ttc, p.localtax1, p.localtax2, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,p.date_livraison as ddelivery,'; $sql.= ' p.datec as date_creation, p.tms as date_update,'; $sql.= " pr.rowid as project_id, pr.ref as project_ref,"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= " sc.fk_soc, sc.fk_user,"; $sql.= ' u.login'; +if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; + // 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 @@ -259,12 +283,15 @@ $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; +if (! empty($search_categ_cus)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ + $sql.= ', '.MAIN_DB_PREFIX.'propal as p'; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."propal_extrafields as ef on (p.rowid = ef.fk_object)"; if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid=pd.fk_propal'; if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON p.fk_user_author = u.rowid'; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."projet as pr ON pr.rowid = p.fk_projet"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_availability as ava on (ava.rowid = p.fk_availability)"; // We'll need this table joined to the select in order to filter by sale if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; if ($search_user > 0) @@ -285,7 +312,8 @@ if ($search_country) $sql .= " AND s.fk_pays IN (".$db->escape($search_country). if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$db->escape($search_type_thirdparty).')'; if ($search_ref) $sql .= natural_search('p.ref', $search_ref); if ($search_refcustomer) $sql .= natural_search('p.ref_client', $search_refcustomer); -if ($search_refproject) $sql .= natural_search('pr.ref', $search_refproject); +if ($search_refproject) $sql .= natural_search('pr.ref', $search_refproject); +if ($search_availability) $sql .= " AND p.fk_availability IN (".$db->escape($search_availability).')'; if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_login) $sql .= natural_search("u.login", $search_login); @@ -295,6 +323,9 @@ if ($search_montant_ttc != '') $sql.= natural_search("p.total", $search_montant_ if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } +if ($search_categ_cus > 0) $sql.= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +if ($search_categ_cus == -2) $sql.= " AND cc.fk_categorie IS NULL"; + if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$db->escape($search_product_category); if ($socid > 0) $sql.= ' AND s.rowid = '.$socid; if ($viewstatut != '' && $viewstatut != '-1') @@ -314,6 +345,32 @@ else if ($search_year > 0) { $sql.= " AND p.datep BETWEEN '".$db->idate(dol_get_first_day($search_year,1,false))."' AND '".$db->idate(dol_get_last_day($search_year,12,false))."'"; } +if ($search_month_end > 0) +{ + if ($search_yearfin > 0 && empty($search_dayfin)) + $sql.= " AND p.fin_validite BETWEEN '".$db->idate(dol_get_first_day($search_yearfin,$search_month_end,false))."' AND '".$db->idate(dol_get_last_day($search_yearfin,$search_month_end,false))."'"; + else if ($search_yearfin > 0 && ! empty($search_dayfin)) + $sql.= " AND p.fin_validite BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month_end, $search_dayfin, $search_yearfin))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month_end, $search_dayfin, $search_yearfin))."'"; + else + $sql.= " AND date_format(p.fin_validite, '%m') = '".$db->escape($search_month_end)."'"; +} +else if ($search_yearfin > 0) +{ + $sql.= " AND p.fin_validite BETWEEN '".$db->idate(dol_get_first_day($search_yearfin,1,false))."' AND '".$db->idate(dol_get_last_day($search_yearfin,12,false))."'"; +} +if ($search_monthdelivery > 0) +{ + if ($search_yeardelivery > 0 && empty($search_daydelivery)) + $sql.= " AND p.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_yeardelivery,$search_monthdelivery,false))."' AND '".$db->idate(dol_get_last_day($search_yeardelivery,$search_monthdelivery,false))."'"; + else if ($search_yeardelivery > 0 && ! empty($search_daydelivery)) + $sql.= " AND p.date_livraison BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_monthdelivery, $search_daydelivery, $search_yeardelivery))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_monthdelivery, $search_daydelivery, $search_yeardelivery))."'"; + else + $sql.= " AND date_format(p.date_livraison, '%m') = '".$db->escape($search_monthdelivery)."'"; +} +else if ($search_yeardelivery > 0) +{ + $sql.= " AND p.date_livraison BETWEEN '".$db->idate(dol_get_first_day($search_yeardelivery,1,false))."' AND '".$db->idate(dol_get_last_day($search_yeardelivery,12,false))."'"; +} if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$db->escape($search_sale); if ($search_user > 0) { @@ -336,6 +393,12 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); @@ -371,7 +434,7 @@ if ($resql) if ($search_year) $param.='&search_year='.urlencode($search_year); if ($search_ref) $param.='&search_ref='.urlencode($search_ref); if ($search_refcustomer) $param.='&search_refcustomer='.urlencode($search_refcustomer); - if ($search_refprojet) $param.='&search_refprojet='.urlencode($search_refprojet); + if ($search_refproject) $param.='&search_refproject='.urlencode($search_refproject); if ($search_societe) $param.='&search_societe='.urlencode($search_societe); if ($search_user > 0) $param.='&search_user='.urlencode($search_user); if ($search_sale > 0) $param.='&search_sale='.urlencode($search_sale); @@ -381,7 +444,8 @@ if ($resql) if ($search_zip) $param.='&search_zip='.urlencode($search_zip); if ($socid > 0) $param.='&socid='.urlencode($socid); if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); - if ($search_product_category != '') $param.='&search_product_category='.$search_product_category; + if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus); + if ($search_product_category != '') $param.='&search_product_category='.$search_product_category; // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -392,9 +456,18 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), ); if ($user->rights->propal->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); + if ($user->rights->propal->cloturer) $arrayofmassactions['closed']=$langs->trans("Closed"); + if (in_array($massaction, array('presend','predelete','closed'))) $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + $newcardbutton=''; + if ($user->rights->propal->creer) + { + $newcardbutton=''.$langs->trans('NewPropal').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } + // Lignes des champs de filtre print '
'; if ($optioncss != '') print ''; @@ -406,7 +479,7 @@ if ($resql) print ''; print ''; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, $newcardbutton, '', $limit); $topicmail="SendPropalRef"; $modelmail="proposal_send"; @@ -417,7 +490,7 @@ if ($resql) if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + print '
'.$langs->trans("FilterOnInto", $all) . join(', ',$fieldstosearchall).'
'; } $i = 0; @@ -451,6 +524,14 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.=''; } + if (! empty($conf->categorie->enabled)) + { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter.=$formother->select_categories('customer',$search_categ_cus,'search_categ_cus',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; @@ -465,7 +546,7 @@ if ($resql) $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $selectedfields.=(count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
'; print ''."\n"; @@ -474,25 +555,25 @@ if ($resql) if (! empty($arrayfields['p.ref']['checked'])) { print ''; } if (! empty($arrayfields['p.ref_client']['checked'])) { print ''; } if (! empty($arrayfields['pr.ref']['checked'])) { print ''; } if (! empty($arrayfields['s.nom']['checked'])) { print ''; } if (! empty($arrayfields['s.town']['checked'])) print ''; @@ -516,15 +597,16 @@ if ($resql) { print ''; } // Date if (! empty($arrayfields['p.date']['checked'])) { - print ''; @@ -532,34 +614,59 @@ if ($resql) // Date end if (! empty($arrayfields['p.fin_validite']['checked'])) { - print ''; + print ''; + } + // Date delivery + if (! empty($arrayfields['p.date_livraison']['checked'])) + { + print ''; + } + // Availability + if (! empty($arrayfields['ava.rowid']['checked'])) + { + print ''; } if (! empty($arrayfields['p.total_ht']['checked'])) { // Amount print ''; } if (! empty($arrayfields['p.total_vat']['checked'])) { // Amount print ''; } if (! empty($arrayfields['p.total_ttc']['checked'])) { // Amount print ''; } if (! empty($arrayfields['u.login']['checked'])) { // Author print ''; } // Extra fields @@ -610,6 +717,8 @@ if ($resql) if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['p.date']['checked'])) print_liste_field_titre($arrayfields['p.date']['label'],$_SERVER["PHP_SELF"],'p.datep','',$param, 'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['p.fin_validite']['checked'])) print_liste_field_titre($arrayfields['p.fin_validite']['label'],$_SERVER["PHP_SELF"],'dfv','',$param, 'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['p.date_livraison']['checked'])) print_liste_field_titre($arrayfields['p.date_livraison']['label'],$_SERVER["PHP_SELF"],'ddelivery','',$param, 'align="center"',$sortfield,$sortorder); + if (! empty($arrayfields['ava.rowid']['checked'])) print_liste_field_titre($arrayfields['ava.rowid']['label'],$_SERVER["PHP_SELF"],'availability','',$param, '',$sortfield,$sortorder); if (! empty($arrayfields['p.total_ht']['checked'])) print_liste_field_titre($arrayfields['p.total_ht']['label'],$_SERVER["PHP_SELF"],'p.total_ht','',$param, 'align="right"',$sortfield,$sortorder); if (! empty($arrayfields['p.total_vat']['checked'])) print_liste_field_titre($arrayfields['p.total_vat']['label'],$_SERVER["PHP_SELF"],'p.tva','',$param, 'align="right"',$sortfield,$sortorder); if (! empty($arrayfields['p.total_ttc']['checked'])) print_liste_field_titre($arrayfields['p.total_ttc']['label'],$_SERVER["PHP_SELF"],'p.total','',$param, 'align="right"',$sortfield,$sortorder); @@ -666,7 +775,7 @@ if ($resql) // Other picto tool print '
'; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ajax_combobox('search_type_thirdparty'); print ''; + print ''; //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; //print ' '.$langs->trans('Year').': '; $formother->select_year($search_year,'search_year',1, 20, 5); print ' '; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + //print ' '.$langs->trans('Year').': '; + $formother->select_year($search_yearfin,'search_yearfin',1, 20, 5); + print ''; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + //print ' '.$langs->trans('Year').': '; + $formother->select_year($search_yeardelivery,'search_yeardelivery',1, 20, 5); + print ''; + print $form->selectAvailabilityDelay($search_availability, 'search_availability', '', 1); + print ajax_combobox('search_availability'); + print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->propal->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $filedir=$conf->propal->multidir_output[$obj->entity] . '/' . dol_sanitizeFileName($obj->ref); $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); print '
'; @@ -775,6 +884,28 @@ if ($resql) } if (! $i) $totalarray['nbfield']++; } + // Date delivery + if (! empty($arrayfields['p.date_livraison']['checked'])) + { + if ($obj->ddelivery) + { + print ''.dol_print_date($db->jdate($obj->ddelivery),'day'); + print ''; + } + else + { + print ' '; + } + if (! $i) $totalarray['nbfield']++; + } + // Availability + if (! empty($arrayfields['ava.rowid']['checked'])) + { + print ''; + $form->form_availability('', $obj->availability, 'none', 1); + print ''; + if (! $i) $totalarray['nbfield']++; + } // Amount HT if (! empty($arrayfields['p.total_ht']['checked'])) @@ -895,25 +1026,18 @@ if ($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); + $hidegeneratedfilelistifempty=1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; - $filedir=$diroutputmassaction; - $genallowed=$user->rights->propal->lire; - $delallowed=$user->rights->propal->creer; + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,'',''); - } - else - { - print '
'.$langs->trans("ShowTempMassFilesArea").''; - } + $filedir=$diroutputmassaction; + $genallowed=$user->rights->propal->lire; + $delallowed=$user->rights->propal->creer; + print $formfile->showdocuments('massfilesarea_proposals','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty); } else { diff --git a/htdocs/comm/propal/note.php b/htdocs/comm/propal/note.php index 17e53b89948..607cff245d9 100644 --- a/htdocs/comm/propal/note.php +++ b/htdocs/comm/propal/note.php @@ -33,10 +33,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load('propal'); -$langs->load('compta'); -$langs->load('bills'); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('propal', 'compta', 'bills', 'companies')); $id = GETPOST('id','int'); $ref=GETPOST('ref','alpha'); diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index 273862f68bf..ac6b42c45d8 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -54,11 +54,8 @@ $year = GETPOST('year')>0?GETPOST('year'):$nowyear; $startyear=$year-1; $endyear=$year; -$langs->load('orders'); -$langs->load('companies'); -$langs->load('other'); -$langs->load('suppliers'); -$langs->load('supplier_proposal'); +// Load translation files required by the page +$langs->loadLangs(array('orders', 'companies', 'other', 'suppliers', 'supplier_proposal')); /* @@ -329,7 +326,7 @@ print '
'; // Show graphs -print ''; - } - $db->free($resql); - print "
'; +print ' - - - - - + + + + - - + + load("propal"); @@ -88,8 +89,6 @@ if ($resql) $i = 0; if ($num > 0 ) { - $var=true; - print '
'; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php b/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php index cc8c6fe0547..cd49ca863e6 100644 --- a/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php +++ b/htdocs/comm/propal/tpl/linkedobjectblock.tpl.php @@ -41,29 +41,36 @@ global $user; $langs = $GLOBALS['langs']; $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; +// Load translation files required by the page $langs->load("propal"); $total=0; $ilink=0; -$var=true; foreach($linkedObjectBlock as $key => $objectlink) { $ilink++; - $trclass=($var?'pair':'impair'); + $trclass='oddeven'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total'; ?> -
trans("Proposal"); ?>getNomUrl(1); ?>ref_client; ?>date,'day'); ?>" data-element="element; ?>" data-id="id; ?>" > + trans("Proposal"); ?> + global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) + { + $url = DOL_URL_ROOT.'/comm/propal/card.php?id='.$objectlink->id; + print ' '; + } + ?> + getNomUrl(1); ?>ref_client; ?>date,'day'); ?>rights->propale->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?>getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
'; print ''; print ''; @@ -126,8 +125,6 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) $resql=$db->query($sql); if ($resql) { - $var=true; - $total=0; $num = $db->num_rows($resql); $i = 0; @@ -197,8 +194,6 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) $i = 0; if ($num > 0) { - $var=true; - print '
'.$langs->trans("ProspectsByStatus").'
'; print ''; @@ -223,7 +218,8 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) $i++; $total += $obj->price; } - if ($total>0) { + if ($total>0) + { print '"; } print "
'.$langs->trans("ProposalsOpened").'
'.$langs->trans("Total")."".price($total)."

"; @@ -255,8 +251,6 @@ if ($resql) $i = 0; if ($num > 0 ) { - $var=true; - print ''; print ''; diff --git a/htdocs/comm/prospect/recap-prospect.php b/htdocs/comm/prospect/recap-prospect.php index fe0fdc55b58..50127d719c8 100644 --- a/htdocs/comm/prospect/recap-prospect.php +++ b/htdocs/comm/prospect/recap-prospect.php @@ -26,8 +26,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -$langs->load("companies"); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'other')); if (! empty($conf->facture->enabled)) $langs->load("bills"); // Security check diff --git a/htdocs/comm/recap-client.php b/htdocs/comm/recap-client.php index 71add817dc5..6cd41c6c658 100644 --- a/htdocs/comm/recap-client.php +++ b/htdocs/comm/recap-client.php @@ -26,6 +26,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +// Load translation files required by the page $langs->load("companies"); if (! empty($conf->facture->enabled)) $langs->load("bills"); diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index 1ad4612d879..6f3287b8831 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -26,13 +26,12 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; -$langs->load("companies"); -$langs->load("orders"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'orders', 'bills')); $id=GETPOST("id",'int'); -$socid = GETPOST('id','int'); +$socid = GETPOST('id','int')?GETPOST('id','int'):GETPOST('socid','int'); // Security check if ($user->societe_id > 0) { @@ -56,7 +55,14 @@ if (GETPOST('action','aZ09') == 'setremise') { $object = new Societe($db); $object->fetch($id); - $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user); + + $discount_type = GETPOST('discount_type', 'int'); + + if(! empty($discount_type)) { + $result=$object->set_remise_supplier(price2num(GETPOST("remise")),GETPOST("note"),$user); + } else { + $result=$object->set_remise_client(price2num(GETPOST("remise")),GETPOST("note"),$user); + } if ($result > 0) { @@ -100,34 +106,73 @@ if ($socid > 0) $head = societe_prepare_head($object); - + $isCustomer = $object->client == 1 || $object->client == 3; + $isSupplier = $object->fournisseur == 1; print ''; print ''; print ''; print ''; - dol_fiche_head($head, 'relativediscount', $langs->trans("ThirdParty"), 0, 'company'); + dol_fiche_head($head, 'relativediscount', $langs->trans("ThirdParty"), -1, 'company'); dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom'); print '
'; print '
'; + + if(! $isCustomer && ! $isSupplier) { + print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; + + dol_fiche_end(); + + print ''; + + llxFooter(); + $db->close(); + exit; + } + print '
'.$langs->trans("ProspectToContact").'
'; - // Discount - print '"; + if($isCustomer) { + // Customer discount + print '"; + } + + if($isSupplier) { + // Supplier discount + print '"; + } + print '
'; - print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
'; + print $langs->trans("CustomerRelativeDiscount").''.price2num($object->remise_percent)."%
'; + print $langs->trans("SupplierRelativeDiscount").''.price2num($object->remise_supplier_percent)."%
'; print '
'; print load_fiche_titre($langs->trans("NewRelativeDiscount"),'',''); print '
'; - + + if($isCustomer && ! $isSupplier) { + print ''; + } + + if(! $isCustomer && $isSupplier) { + print ''; + } + print ''; + if($isCustomer && $isSupplier) { + // Discount type + print ''; + print ''; + } + // New value print ''; @@ -155,57 +200,128 @@ if ($socid > 0) print '
'; + if($isCustomer) { + if($isSupplier) { + print '
'; + print '
'; + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); + } - /* - * List log of all percent discounts - */ - $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; - $sql.= " u.login, u.rowid as user_id"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user_author"; - $sql.= " ORDER BY rc.datec DESC"; + /* + * List log of all customer percent discounts + */ + $sql = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,"; + $sql.= " u.login, u.rowid as user_id"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user_author"; + $sql.= " ORDER BY rc.datec DESC"; - $resql=$db->query($sql); - if ($resql) - { - print '
'.$langs->trans('DiscountType').' '; + print ' '; + print '
'; print $langs->trans("NewValue").'%
'; - $tag = !$tag; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $num = $db->num_rows($resql); - if ($num > 0) - { - $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($resql); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $i++; - } + $resql=$db->query($sql); + if ($resql) + { + print '
'.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
'.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'; + $tag = !$tag; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $num = $db->num_rows($resql); + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
'.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'.$langs->trans("None").'
"; } else { - print '
'.$langs->trans("None").'
"; - } - else - { - dol_print_error($db); + dol_print_error($db); + } } + if($isSupplier) { + if($isCustomer) { + print '
'; // class="fichehalfleft" + print '
'; + print '
'; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } + + /* + * List log of all supplier percent discounts + */ + $sql = "SELECT rc.rowid, rc.remise_supplier as remise_percent, rc.note, rc.datec as dc,"; + $sql.= " u.login, u.rowid as user_id"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_supplier as rc, ".MAIN_DB_PREFIX."user as u"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user_author"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print ''; + $tag = !$tag; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $num = $db->num_rows($resql); + if ($num > 0) + { + $i = 0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("CustomerRelativeDiscountShort").''.$langs->trans("NoteReason").''.$langs->trans("User").'
'.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'.$langs->trans("None").'
"; + } + else + { + dol_print_error($db); + } + + if($isCustomer) { + print '
'; // class="ficheaddleft" + print '
'; // class="fichehalfright" + print '
'; // class="fichecenter" + } + } } llxFooter(); diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 0127b8f15be..3eec109e6b3 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -26,11 +26,11 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; -$langs->load("orders"); -$langs->load("bills"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('orders', 'bills', 'companies')); $id=GETPOST('id','int'); @@ -92,6 +92,12 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount2->fk_facture=$discount->fk_facture; $newdiscount1->fk_facture_line=$discount->fk_facture_line; $newdiscount2->fk_facture_line=$discount->fk_facture_line; + $newdiscount1->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; + $newdiscount2->fk_invoice_supplier_source=$discount->fk_invoice_supplier_source; + $newdiscount1->fk_invoice_supplier=$discount->fk_invoice_supplier; + $newdiscount2->fk_invoice_supplier=$discount->fk_invoice_supplier; + $newdiscount1->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; + $newdiscount2->fk_invoice_supplier_line=$discount->fk_invoice_supplier_line; if ($discount->description == '(CREDIT_NOTE)' || $discount->description == '(DEPOSIT)') { $newdiscount1->description=$discount->description; @@ -106,6 +112,8 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount2->fk_user=$discount->fk_user; $newdiscount1->fk_soc=$discount->fk_soc; $newdiscount2->fk_soc=$discount->fk_soc; + $newdiscount1->discount_type=$discount->discount_type; + $newdiscount2->discount_type=$discount->discount_type; $newdiscount1->datec=$discount->datec; $newdiscount2->datec=$discount->datec; $newdiscount1->tva_tx=$discount->tva_tx; @@ -143,6 +151,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) $amount_ht=GETPOST('amount_ht'); $desc=GETPOST('desc','alpha'); $tva_tx=GETPOST('tva_tx','alpha'); + $discount_type=! empty($_POST['discount_type'])?GETPOST('discount_type','alpha'):0; if (price2num($amount_ht) > 0) { @@ -157,7 +166,7 @@ if ($action == 'setremise' && $user->rights->societe->creer) { $soc = new Societe($db); $soc->fetch($id); - $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx); + $discountid=$soc->set_remise_except($amount_ht,$user,$desc,$tva_tx,$discount_type); if ($discountid > 0) { @@ -215,6 +224,7 @@ if (GETPOST('action','aZ09') == 'confirm_remove' && GETPOST("confirm")=='yes') $form=new Form($db); $facturestatic=new Facture($db); +$facturefournstatic=new FactureFournisseur($db); llxHeader('',$langs->trans("GlobalDiscount")); @@ -224,12 +234,14 @@ if ($socid > 0) $object = new Societe($db); $object->fetch($socid); + $isCustomer = $object->client == 1 || $object->client == 3; + $isSupplier = $object->fournisseur == 1; + /* * Display tabs */ $head = societe_prepare_head($object); - print '
'; print ''; print ''; @@ -242,36 +254,85 @@ if ($socid > 0) print '
'; print '
'; + + if(! $isCustomer && ! $isSupplier) { + print '

'.$langs->trans('ThirdpartyIsNeitherCustomerNorClientSoCannotHaveDiscounts').'

'; + + dol_fiche_end(); + + print ''; + + llxFooter(); + $db->close(); + exit; + } + + print ''; - // Calcul avoirs en cours - $remise_all=$remise_user=0; - $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; - $sql.= " GROUP BY rc.fk_user"; - $resql=$db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $remise_all+=$obj->amount; - if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; - } - else - { - dol_print_error($db); + if($isCustomer) { // Calcul avoirs client en cours + $remise_all=$remise_user=0; + $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 0"; // Exclude supplier discounts + $sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)"; + $sql.= " GROUP BY rc.fk_user"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $remise_all+=$obj->amount; + if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + } + else + { + dol_print_error($db); + } + + print ''; + print ''; + + if (! empty($user->fk_soc)) // No need to show this for external users + { + print ''; + print ''; + } } - print ''; - print ''; - - if (! empty($user->fk_soc)) // No need to show this for external users - { - print ''; - print ''; + if($isSupplier) { + // Calcul avoirs fournisseur en cours + $remise_all=$remise_user=0; + $sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND discount_type = 1"; // Exclude customer discounts + $sql.= " AND (fk_invoice_supplier_line IS NULL AND fk_invoice_supplier IS NULL)"; + $sql.= " GROUP BY rc.fk_user"; + $resql=$db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $remise_all+=$obj->amount; + if ($obj->fk_user == $user->id) $remise_user+=$obj->amount; + } + else + { + dol_print_error($db); + } + + print ''; + print ''; + + if (! empty($user->fk_soc)) // No need to show this for external users + { + print ''; + print ''; + } } + print '
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("CustomerAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("SupplierAbsoluteDiscountAllUsers").''.$remise_all.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'.$langs->trans("SupplierAbsoluteDiscountMy").''.$remise_user.' '.$langs->trans("Currency".$conf->currency).' '.$langs->trans("HT").'
'; print '
'; @@ -283,7 +344,22 @@ if ($socid > 0) print load_fiche_titre($langs->trans("NewGlobalDiscount"),'',''); print '
'; + + if($isCustomer && ! $isSupplier) { + print ''; + } + + if(! $isCustomer && $isSupplier) { + print ''; + } + print ''; + if($isCustomer && $isSupplier) { + print ''; + print ''; + } print ''; print ''; @@ -321,132 +397,287 @@ if ($socid > 0) print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.GETPOST('remid'), $langs->trans('RemoveDiscount'), $langs->trans('ConfirmRemoveDiscount'), 'confirm_remove', '', 0, 1); } + /* - * Liste remises fixes restant en cours (= liees a aucune facture ni ligne de facture) + * Liste remises fixes client restant en cours (= liees a aucune facture ni ligne de facture) */ - $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql.= " rc.datec as dc, rc.description,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " fa.facnumber as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc = " . $object->id; - $sql.= " AND rc.entity = " . $conf->entity; - $sql.= " AND u.rowid = rc.fk_user"; - $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; - $sql.= " ORDER BY rc.datec DESC"; + + print load_fiche_titre($langs->trans("DiscountStillRemaining")); - $resql=$db->query($sql); - if ($resql) - { - print load_fiche_titre($langs->trans("DiscountStillRemaining")); - print '
'.$langs->trans('DiscountType').' '; + print ' '; + print '
'.$langs->trans("AmountHT").''; print ' '.$langs->trans("Currency".$conf->currency).'
'; - print ''; - print ''; // Need 120+ for format with AM/PM - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + if($isCustomer) { + if($isSupplier) { + print '
'; + print '
'; + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); + } - $showconfirminfo=array(); - - $i = 0; - $num = $db->num_rows($resql); - if ($num > 0) + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description,"; + $sql.= " rc.fk_facture_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " fa.facnumber as ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) { - while ($i < $num) - { - $obj = $db->fetch_object($resql); - - print '
'; - print ''; - if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) - { - print ''; - } - else - { - print ''; - } - print ''; - print ''; - print ''; - print ''; - print ''; - if ($user->rights->societe->creer || $user->rights->facture->creer) - { - print ''; - } - else print ''; - print ''; - - if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) - { - $showconfirminfo['rowid']=$obj->rowid; - $showconfirminfo['amount_ttc']=$obj->amount_ttc; - } - $i++; - } + print '
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - print $obj->description; - print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; - print ''; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; - print '   '; - print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; - print ' 
'; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $showconfirminfo=array(); + + $i = 0; + $num = $db->num_rows($resql); + if ($num > 0) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + if ($user->rights->societe->creer || $user->rights->facture->creer) + { + print ''; + } + else print ''; + print ''; + + if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + { + $showconfirminfo['rowid']=$obj->rowid; + $showconfirminfo['amount_ttc']=$obj->amount_ttc; + } + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("ExcessReceived"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + print $obj->description; + print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print '   '; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print ' 
'.$langs->trans("None").'
"; + + if (count($showconfirminfo)) + { + $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); + $amount2=($showconfirminfo['amount_ttc']-$amount1); + $formquestion=array( + 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), + array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), + array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') + ); + $langs->load("dict"); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + } } else { - print ''.$langs->trans("None").''; - } - $db->free($resql); - print ""; - - if (count($showconfirminfo)) - { - $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); - $amount2=($showconfirminfo['amount_ttc']-$amount1); - $formquestion=array( - 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), - array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), - array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') - ); - $langs->load("dict"); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + dol_print_error($db); } } - else - { - dol_print_error($db); + + if($isSupplier) { + if($isCustomer) { + print ''; // class="fichehalfleft" + print '
'; + print '
'; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); + } + + /* + * Liste remises fixes fournisseur restant en cours (= liees a aucune facture ni ligne de facture) + */ + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description,"; + $sql.= " rc.fk_invoice_supplier_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " fa.ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc = " . $object->id; + $sql.= " AND rc.entity = " . $conf->entity; + $sql.= " AND u.rowid = rc.fk_user"; + $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; + $sql.= " ORDER BY rc.datec DESC"; + + $resql=$db->query($sql); + if ($resql) + { + print ''; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $showconfirminfo=array(); + + $i = 0; + $num = $db->num_rows($resql); + if ($num > 0) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS PAID\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + if ($user->rights->societe->creer || $user->rights->facture->creer) + { + print ''; + } + else print ''; + print ''; + + if ($_GET["action"]=='split' && GETPOST('remid') == $obj->rowid) + { + $showconfirminfo['rowid']=$obj->rowid; + $showconfirminfo['amount_ttc']=$obj->amount_ttc; + } + $i++; + } + } + else + { + print ''; + } + $db->free($resql); + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("DiscountOfferedBy").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("ExcessPaid"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + print $obj->description; + print ''.$langs->trans("NotConsumed").''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_split($langs->trans("SplitDiscount")).''; + print '   '; + print 'rowid.($backtopage?'&backtopage='.urlencode($backtopage):'').'">'.img_delete($langs->trans("RemoveDiscount")).''; + print ' 
'.$langs->trans("None").'
"; + + if (count($showconfirminfo)) + { + $amount1=price2num($showconfirminfo['amount_ttc']/2,'MT'); + $amount2=($showconfirminfo['amount_ttc']-$amount1); + $formquestion=array( + 'text' => $langs->trans('TypeAmountOfEachNewDiscount'), + array('type' => 'text', 'name' => 'amount_ttc_1', 'label' => $langs->trans("AmountTTC").' 1', 'value' => $amount1, 'size' => '5'), + array('type' => 'text', 'name' => 'amount_ttc_2', 'label' => $langs->trans("AmountTTC").' 2', 'value' => $amount2, 'size' => '5') + ); + $langs->load("dict"); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&remid='.$showconfirminfo['rowid'].($backtopage?'&backtopage='.urlencode($backtopage):''), $langs->trans('SplitDiscount'), $langs->trans('ConfirmSplitDiscount',price($showconfirminfo['amount_ttc']),$langs->transnoentities("Currency".$conf->currency)), 'confirm_split', $formquestion, 0, 0); + } + } + else + { + dol_print_error($db); + } + + if($isCustomer) { + print '
'; // class="ficheaddleft" + print '
'; // class="fichehalfright" + print ''; // class="fichecenter" + } } print '
'; @@ -454,150 +685,317 @@ if ($socid > 0) /* * List discount consumed (=liees a une ligne de facture ou facture) */ + + print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); - // Remises liees a lignes de factures - $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql.= " rc.fk_facture_source,"; - $sql.= " u.login, u.rowid as user_id,"; - $sql.= " f.rowid, f.facnumber,"; - $sql.= " fa.facnumber as ref, fa.type as type"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= " , ".MAIN_DB_PREFIX."user as u"; - $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc"; - $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql.= " WHERE rc.fk_soc =". $object->id; - $sql.= " AND rc.fk_facture_line = fc.rowid"; - $sql.= " AND fc.fk_facture = f.rowid"; - $sql.= " AND rc.fk_user = u.rowid"; - $sql.= " ORDER BY dc DESC"; - //$sql.= " UNION "; - // Remises liees a factures - $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; - $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; - $sql2.= " rc.fk_facture_source,"; - $sql2.= " u.login, u.rowid as user_id,"; - $sql2.= " f.rowid, f.facnumber,"; - $sql2.= " fa.facnumber as ref, fa.type as type"; - $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql2.= " , ".MAIN_DB_PREFIX."user as u"; - $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; - $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; - $sql2.= " WHERE rc.fk_soc =". $object->id; - $sql2.= " AND rc.fk_facture = f.rowid"; - $sql2.= " AND rc.fk_user = u.rowid"; - - $sql2.= " ORDER BY dc DESC"; - - $resql=$db->query($sql); - $resql2=null; - if ($resql) $resql2=$db->query($sql2); - if ($resql2) - { - print load_fiche_titre($langs->trans("DiscountAlreadyCounted")); - print ''; - print ''; - print ''; // Need 120+ for format with AM/PM - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - $tab_sqlobj=array(); - $tab_sqlobjOrder=array(); - $num = $db->num_rows($resql); - if ($num > 0) - { - for ($i = 0;$i < $num; $i++) - { - $sqlobj = $db->fetch_object($resql); - $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); - } + if($isCustomer) { + if($isSupplier) { + print '
'; + print '
'; + print load_fiche_titre($langs->trans("CustomerDiscounts"), '', ''); } - $db->free($resql); - $num = $db->num_rows($resql2); - for ($i = 0;$i < $num;$i++) + // Remises liees a lignes de factures + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql.= " rc.fk_facture_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " f.rowid, f.facnumber,"; + $sql.= " fa.facnumber as ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql.= " , ".MAIN_DB_PREFIX."user as u"; + $sql.= " , ".MAIN_DB_PREFIX."facturedet as fc"; + $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc =". $object->id; + $sql.= " AND rc.fk_facture_line = fc.rowid"; + $sql.= " AND fc.fk_facture = f.rowid"; + $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql.= " ORDER BY dc DESC"; + //$sql.= " UNION "; + // Remises liees a factures + $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql2.= " rc.datec as dc, rc.description, rc.fk_facture_line, rc.fk_facture,"; + $sql2.= " rc.fk_facture_source,"; + $sql2.= " u.login, u.rowid as user_id,"; + $sql2.= " f.rowid, f.facnumber,"; + $sql2.= " fa.facnumber as ref, fa.type as type"; + $sql2.= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql2.= " , ".MAIN_DB_PREFIX."user as u"; + $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid"; + $sql2.= " WHERE rc.fk_soc =". $object->id; + $sql2.= " AND rc.fk_facture = f.rowid"; + $sql2.= " AND rc.fk_user = u.rowid"; + $sql2.= " AND rc.discount_type = 0"; // Eliminate supplier discounts + $sql2.= " ORDER BY dc DESC"; + + $resql=$db->query($sql); + $resql2=null; + if ($resql) $resql2=$db->query($sql2); + if ($resql2) { - $sqlobj = $db->fetch_object($resql2); - $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); - } - $db->free($resql2); - array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); - - $num = count($tab_sqlobj); - if ($num > 0) - { - $i = 0 ; - while ($i < $num ) - { - $obj = array_shift($tab_sqlobj); - print '
'; - print ''; - if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) - { - print ''; - } - elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) - { - print ''; - } - else - { - print ''; - } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $i++; - } + print '
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - $facturestatic->id=$obj->fk_facture_source; - $facturestatic->ref=$obj->ref; - $facturestatic->type=$obj->type; - print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1); - print ''; - print $obj->description; - print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; - print ' 
'; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $tab_sqlobj=array(); + $tab_sqlobjOrder=array(); + $num = $db->num_rows($resql); + if ($num > 0) + { + for ($i = 0;$i < $num; $i++) + { + $sqlobj = $db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + } + } + $db->free($resql); + + $num = $db->num_rows($resql2); + for ($i = 0;$i < $num;$i++) + { + $sqlobj = $db->fetch_object($resql2); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + } + $db->free($resql2); + array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); + + $num = count($tab_sqlobj); + if ($num > 0) + { + $i = 0 ; + while ($i < $num ) + { + $obj = array_shift($tab_sqlobj); + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS RECEIVED\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + $facturestatic->id=$obj->fk_facture_source; + $facturestatic->ref=$obj->ref; + $facturestatic->type=$obj->type; + print preg_replace('/\(EXCESS RECEIVED\)/',$langs->trans("Invoice"),$obj->description).' '.$facturestatic->getNomURl(1); + print ''; + print $obj->description; + print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ' 
'.$langs->trans("None").'
"; } else { - print ''.$langs->trans("None").''; + dol_print_error($db); + } + } + + if($isSupplier) { + if($isCustomer) { + print ''; // class="fichehalfleft" + print '
'; + print '
'; + print load_fiche_titre($langs->trans("SupplierDiscounts"), '', ''); } - print ""; - } - else - { - dol_print_error($db); - } + // Remises liees a lignes de factures + $sql = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql.= " rc.fk_invoice_supplier_source,"; + $sql.= " u.login, u.rowid as user_id,"; + $sql.= " f.rowid, f.ref as facnumber,"; + $sql.= " fa.ref, fa.type as type"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " , ".MAIN_DB_PREFIX."user as u"; + $sql.= " , ".MAIN_DB_PREFIX."facture_fourn_det as fc"; + $sql.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql.= " WHERE rc.fk_soc =". $object->id; + $sql.= " AND rc.fk_invoice_supplier_line = fc.rowid"; + $sql.= " AND fc.fk_facture_fourn = f.rowid"; + $sql.= " AND rc.fk_user = u.rowid"; + $sql.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql.= " ORDER BY dc DESC"; + //$sql.= " UNION "; + // Remises liees a factures + $sql2 = "SELECT rc.rowid, rc.amount_ht, rc.amount_tva, rc.amount_ttc, rc.tva_tx,"; + $sql2.= " rc.datec as dc, rc.description, rc.fk_invoice_supplier_line, rc.fk_invoice_supplier,"; + $sql2.= " rc.fk_invoice_supplier_source,"; + $sql2.= " u.login, u.rowid as user_id,"; + $sql2.= " f.rowid, f.ref as facnumber,"; + $sql2.= " fa.ref, fa.type as type"; + $sql2.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql2.= " , ".MAIN_DB_PREFIX."user as u"; + $sql2.= " , ".MAIN_DB_PREFIX."societe_remise_except as rc"; + $sql2.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_fourn as fa ON rc.fk_invoice_supplier_source = fa.rowid"; + $sql2.= " WHERE rc.fk_soc =". $object->id; + $sql2.= " AND rc.fk_invoice_supplier = f.rowid"; + $sql2.= " AND rc.fk_user = u.rowid"; + $sql2.= " AND rc.discount_type = 1"; // Eliminate customer discounts + $sql2.= " ORDER BY dc DESC"; + + $resql=$db->query($sql); + $resql2=null; + if ($resql) $resql2=$db->query($sql2); + if ($resql2) + { + print ''; + print ''; + print ''; // Need 120+ for format with AM/PM + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $tab_sqlobj=array(); + $tab_sqlobjOrder=array(); + $num = $db->num_rows($resql); + if ($num > 0) + { + for ($i = 0;$i < $num; $i++) + { + $sqlobj = $db->fetch_object($resql); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]=$db->jdate($sqlobj->dc); + } + } + $db->free($resql); + + $num = $db->num_rows($resql2); + for ($i = 0;$i < $num;$i++) + { + $sqlobj = $db->fetch_object($resql2); + $tab_sqlobj[] = $sqlobj; + $tab_sqlobjOrder[]= $db->jdate($sqlobj->dc); + } + $db->free($resql2); + array_multisort($tab_sqlobjOrder,SORT_DESC,$tab_sqlobj); + + $num = count($tab_sqlobj); + if ($num > 0) + { + $i = 0 ; + while ($i < $num ) + { + $obj = array_shift($tab_sqlobj); + print ''; + print ''; + if (preg_match('/\(CREDIT_NOTE\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(DEPOSIT\)/',$obj->description)) + { + print ''; + } + elseif (preg_match('/\(EXCESS PAID\)/',$obj->description)) + { + print ''; + } + else + { + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i++; + } + } + else + { + print ''; + } + + print "
'.$langs->trans("Date").''.$langs->trans("ReasonDiscount").''.$langs->trans("ConsumedBy").''.$langs->trans("AmountHT").''.$langs->trans("VATRate").''.$langs->trans("AmountTTC").''.$langs->trans("Author").' 
'.dol_print_date($db->jdate($obj->dc),'dayhour').''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(CREDIT_NOTE\)/',$langs->trans("CreditNote"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(DEPOSIT\)/',$langs->trans("InvoiceDeposit"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + $facturefournstatic->id=$obj->fk_invoice_supplier_source; + $facturefournstatic->ref=$obj->ref; + $facturefournstatic->type=$obj->type; + print preg_replace('/\(EXCESS PAID\)/',$langs->trans("Invoice"),$obj->description).' '.$facturefournstatic->getNomURl(1); + print ''; + print $obj->description; + print ''.img_object($langs->trans("ShowBill"),'bill').' '.$obj->facnumber.''.price($obj->amount_ht).''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ' 
'.$langs->trans("None").'
"; + } + else + { + dol_print_error($db); + } + if($isCustomer) { + print '
'; // class="ficheaddleft" + print '
'; // class="fichehalfright" + print ''; // class="fichecenter" + } + } } llxFooter(); diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 27fc1821a03..0fe49cf9f12 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -56,15 +56,8 @@ if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } -$langs->load('orders'); -$langs->load('sendings'); -$langs->load('companies'); -$langs->load('bills'); -$langs->load('propal'); -$langs->load('deliveries'); -$langs->load('sendings'); -$langs->load('products'); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('orders','sendings','companies','bills','propal','deliveries','products','other')); if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); if (! empty($conf->margin->enabled)) $langs->load('margins'); if (! empty($conf->productbatch->enabled)) $langs->load("productbatch"); @@ -366,8 +359,7 @@ if (empty($reshook)) } // Extrafields - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if - // trigger used + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if trigger used { $lines[$i]->fetch_optionals($lines[$i]->rowid); $array_options = $lines[$i]->array_options; @@ -376,7 +368,12 @@ if (empty($reshook)) $tva_tx = $lines[$i]->tva_tx; if (! empty($lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')'; - $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid); + $result = $object->addline( + $desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, + $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type, + $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, + $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid + ); if ($result < 0) { $error++; @@ -806,7 +803,27 @@ if (empty($reshook)) // If price per quantity and customer elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - // TODO Same than PRODUIT_CUSTOMER_PRICES_BY_QTY but using $object->thirdparty->price_level + if ($prod->prices_by_qty[$object->thirdparty->price_level]) // yes, this product has some prices per quantity + { + // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. + $pqp = GETPOST('pbq','int'); + // Search price into product_price_by_qty from $prod->id + foreach($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) + { + if ($priceforthequantityarray['rowid'] != $pqp) continue; + // We found the price + if ($priceforthequantityarray['price_base_type'] == 'HT') + { + $pu_ht = $priceforthequantityarray['unitprice']; + } + else + { + $pu_ttc = $priceforthequantityarray['unitprice']; + } + // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST. + break; + } + } } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx)); @@ -1027,8 +1044,8 @@ if (empty($reshook)) $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]; + if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_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') : ''); @@ -1269,31 +1286,25 @@ if (empty($reshook)) if ($action == 'update_extras') { + $object->oldcopy = dol_clone($object); + // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none')); if ($ret < 0) $error++; if (! $error) { - // Actions on extra fields (by external module or standard code) - $hookmanager->initHooks(array('orderdao')); - $parameters = array('id' => $object->id); - $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by - // some hooks - if (empty($reshook)) { - $result = $object->insertExtraFields(); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } else if ($reshook < 0) + // Actions on extra fields + $result = $object->insertExtraFields('ORDER_MODIFY'); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); $error++; + } } - if ($error) - $action = 'edit_extras'; + if ($error) $action = 'edit_extras'; } if ($action == 'set_thirdparty' && $user->rights->commande->creer) @@ -1448,7 +1459,7 @@ if ($action == 'create' && $user->rights->commande->creer) $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); $soc = $objectsrc->thirdparty; - $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0)); // TODO maybe add default value option $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); @@ -1554,17 +1565,14 @@ if ($action == 'create' && $user->rights->commande->creer) // Ligne info remises tiers print '' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; + $absolute_discount = $soc->getAvailableDiscounts(); - if ($absolute_discount) - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency" . $conf->currency)); - else - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print ''; } // Date @@ -1661,7 +1669,7 @@ if ($action == 'create' && $user->rights->commande->creer) $parameters = array('objectsrc' => $objectsrc, 'socid'=>$socid); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1802,7 +1810,7 @@ if ($action == 'create' && $user->rights->commande->creer) $author = new User($db); $author->fetch($object->user_author_id); - $res = $object->fetch_optionals($object->id, $extralabels); + $res = $object->fetch_optionals(); $head = commande_prepare_head($object); dol_fiche_head($head, 'order', $langs->trans("CustomerOrder"), -1, 'order'); @@ -1954,7 +1962,6 @@ if ($action == 'create' && $user->rights->commande->creer) // 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=3)'))); - // Paiement incomplet. On demande si motif = escompte ou autre $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('CloneOrder'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } @@ -1990,17 +1997,17 @@ if ($action == 'create' && $user->rights->commande->creer) { if ($action != 'classify') $morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='
'; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.=''; - $morehtmlref.='
'; - } else { - $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } + 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); @@ -2039,12 +2046,11 @@ if ($action == 'create' && $user->rights->commande->creer) // Relative and absolute discounts if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final - // invoice + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')"; - $filtercreditnote = "fk_facture_source IS NOT NULL AND description NOT LIKE '(DEPOSIT)%'"; + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; @@ -2052,29 +2058,17 @@ if ($action == 'create' && $user->rights->commande->creer) $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; print '' . $langs->trans('Discounts') . ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; - $absolute_discount = $soc->getAvailableDiscounts('', 'fk_facture_source IS NULL'); - $absolute_creditnote = $soc->getAvailableDiscounts('', 'fk_facture_source IS NOT NULL'); + + $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount); + $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote); $absolute_discount = price2num($absolute_discount, 'MT'); $absolute_creditnote = price2num($absolute_creditnote, 'MT'); - if ($absolute_discount) { - if ($object->statut > Commande::STATUS_DRAFT) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - } else { - // Remise dispo de type remise fixe (not credit note) - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?id=' . $object->id, 0, 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, 0, '', 1); - } - } - if ($absolute_creditnote) { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '. '; - } - if (! $absolute_discount && ! $absolute_creditnote) - print $langs->trans("CompanyHasNoAbsoluteDiscount") . '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print ''; // Date @@ -2301,12 +2295,15 @@ if ($action == 'create' && $user->rights->commande->creer) $tmparray=$object->getTotalWeightVolume(); $totalWeight=$tmparray['weight']; $totalVolume=$tmparray['volume']; - if ($totalWeight || $totalVolume) + if ($totalWeight) { print ''.$langs->trans("CalculatedWeight").''; print ''; print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND)?$conf->global->MAIN_WEIGHT_DEFAULT_ROUND:-1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT)?$conf->global->MAIN_WEIGHT_DEFAULT_UNIT:'no'); print ''; + } + if ($totalVolume) + { print ''.$langs->trans("CalculatedVolume").''; print ''; print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND)?$conf->global->MAIN_VOLUME_DEFAULT_ROUND:-1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT)?$conf->global->MAIN_VOLUME_DEFAULT_UNIT:'no'); @@ -2389,8 +2386,12 @@ if ($action == 'create' && $user->rights->commande->creer) } // Total HT + $alert = ''; + if($object->total_ht < $object->thirdparty->order_min_amount) { + $alert = ' ' . img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->order_min_amount)); + } print '' . $langs->trans('AmountHT') . ''; - print '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . ''; + print '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . $alert . ''; // Total VAT print '' . $langs->trans('AmountVAT') . '' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . ''; @@ -2467,7 +2468,7 @@ if ($action == 'create' && $user->rights->commande->creer) /* * Form to add new line */ - if ($object->statut == Commande::STATUS_DRAFT && $user->rights->commande->creer) + if ($object->statut == Commande::STATUS_DRAFT && $user->rights->commande->creer && $action != 'selectlines') { if ($action != 'editline') { @@ -2498,9 +2499,9 @@ if ($action == 'create' && $user->rights->commande->creer) // Send if ($object->statut > Commande::STATUS_DRAFT) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { - print ''; + print ''; } else - print ''; + print ''; } // Valid @@ -2639,9 +2640,8 @@ if ($action == 'create' && $user->rights->commande->creer) $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); // Show online payment link - //$useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)); - $useonlinepayment = $conf->global->ORDER_SHOW_ONLINE_PAYMENT_ON_ORDER; - + $useonlinepayment = (! empty($conf->paypal->enabled) || ! empty($conf->stripe->enabled) || ! empty($conf->paybox->enabled)); + if (! empty($conf->global->ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER)) $useonlinepayment = 0; if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment) { print '
'; diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index cbd505a41b8..e52da47e11b 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -76,9 +76,11 @@ class Orders extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $this->commande->fetchObjectLinked(); + // Add external contacts ids + $this->commande->contacts_ids = $this->commande->liste_contact(-1,'external',1); + $this->commande->fetchObjectLinked(); return $this->_cleanObjectDatas($this->commande); - } + } @@ -159,6 +161,8 @@ class Orders extends DolibarrApi $obj = $db->fetch_object($result); $commande_static = new Commande($db); if($commande_static->fetch($obj->rowid)) { + // Add external contacts ids + $commande_static->contacts_ids = $commande_static->liste_contact(-1,'external',1); $obj_ret[] = $this->_cleanObjectDatas($commande_static); } $i++; @@ -179,7 +183,7 @@ class Orders extends DolibarrApi * @param array $request_data Request data * @return int ID of order */ - function post($request_data = NULL) + function post($request_data = null) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401, "Insuffisant rights"); @@ -245,7 +249,7 @@ class Orders extends DolibarrApi * * @return int */ - function postLine($id, $request_data = NULL) { + function postLine($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } @@ -308,7 +312,7 @@ class Orders extends DolibarrApi * * @return object */ - function putLine($id, $lineid, $request_data = NULL) { + function putLine($id, $lineid, $request_data = null) { if(! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } @@ -402,7 +406,7 @@ class Orders extends DolibarrApi * * @return int */ - function put($id, $request_data = NULL) { + function put($id, $request_data = null) { if (! DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 9007490d421..ecd2be95d7a 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -10,6 +10,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2015 Marcos García * Copyright (C) 2016-2017 Ferran Marcet + * Copyright (C) 2018 Nicolas ZABOURI * * 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,10 +80,9 @@ class Commande extends CommonOrder */ public $statut; /** - * @deprecated - * @see billed + * Billed + * @var int */ - public $facturee; public $billed; // billed or not public $brouillon; @@ -545,7 +545,6 @@ class Commande extends CommonOrder { $this->statut = self::STATUS_VALIDATED; $this->billed = 0; - $this->facturee = 0; // deprecated $this->db->commit(); return 1; @@ -825,7 +824,7 @@ class Commande extends CommonOrder $line = $this->lines[$i]; // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array - //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE); // convert recursively array into object. + //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. if (! is_object($line)) $line = (object) $line; // Reset fk_parent_line for no child products and special product @@ -1024,7 +1023,7 @@ class Commande extends CommonOrder // get lines so they will be clone foreach($this->lines as $line) - $line->fetch_optionals($line->rowid); + $line->fetch_optionals(); // Load source object $objFrom = clone $this; @@ -1073,11 +1072,6 @@ class Commande extends CommonOrder $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; } - - // Call trigger - $result=$this->call_trigger('ORDER_CLONE',$user); - if ($result < 0) $error++; - // End call triggers } unset($this->context['createfromclone']); @@ -1150,7 +1144,7 @@ class Commande extends CommonOrder $line->marque_tx = $marginInfos[2]; // get extrafields from original line - $object->lines[$i]->fetch_optionals($object->lines[$i]->rowid); + $object->lines[$i]->fetch_optionals(); foreach($object->lines[$i]->array_options as $options_key => $value) $line->array_options[$options_key] = $value; @@ -1264,7 +1258,10 @@ class Commande extends CommonOrder { global $mysoc, $conf, $langs, $user; - dol_syslog(get_class($this)."::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start, date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); + $logtext = "::addline commandeid=$this->id, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, fk_product=$fk_product, remise_percent=$remise_percent"; + $logtext.= ", info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, date_start=$date_start"; + $logtext.= ", date_end=$date_end, type=$type special_code=$special_code, fk_unit=$fk_unit, origin=$origin, origin_id=$origin_id, pu_ht_devise=$pu_ht_devise"; + dol_syslog(get_class($this).$logtext, LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1538,8 +1535,8 @@ class Commande extends CommonOrder { $prod = new Product($this->db); $prod->fetch($idproduct); - $prod -> get_sousproduits_arbo (); - $prods_arbo = $prod->get_each_prod(); + $prod -> get_sousproduits_arbo(); + $prods_arbo = $prod->get_arbo_each_prod(); if(count($prods_arbo) > 0) { foreach($prods_arbo as $key => $value) @@ -1589,13 +1586,15 @@ class Commande extends CommonOrder $sql.= ', ca.code as availability_code, ca.label as availability_label'; $sql.= ', dr.code as demand_reason_code'; $sql.= ' FROM '.MAIN_DB_PREFIX.'commande as c'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid AND cr.entity IN ('.getEntity('c_payment_term').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as cr ON c.fk_cond_reglement = cr.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON c.fk_mode_reglement = p.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_availability as ca ON c.fk_availability = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_input_reason as dr ON c.fk_input_reason = ca.rowid'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; - $sql.= " WHERE c.entity IN (".getEntity('commande').")"; - if ($id) $sql.= " AND c.rowid=".$id; + + if ($id) $sql.= " WHERE c.rowid=".$id; + else $sql.= " WHERE c.entity IN (".getEntity('commande').")"; // Dont't use entity if you use rowid + if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'"; if ($ref_ext) $sql.= " AND c.ref_ext='".$this->db->escape($ref_ext)."'"; if ($ref_int) $sql.= " AND c.ref_int='".$this->db->escape($ref_int)."'"; @@ -1630,7 +1629,6 @@ class Commande extends CommonOrder $this->remise_percent = $obj->remise_percent; $this->remise_absolue = $obj->remise_absolue; $this->source = $obj->source; - $this->facturee = $obj->billed; // deprecated $this->billed = $obj->billed; $this->note = $obj->note_private; // deprecated $this->note_private = $obj->note_private; @@ -1675,12 +1673,9 @@ class Commande extends CommonOrder if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; - // Retrieve all extrafields for invoice + // Retreive all extrafield // fetch optionals attributes and labels - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + $this->fetch_optionals(); $this->db->free($result); @@ -2710,7 +2705,6 @@ class Commande extends CommonOrder if (! $error) { $this->oldcopy= clone $this; - $this->facturee=1; // deprecated $this->billed=1; } @@ -2746,21 +2740,6 @@ class Commande extends CommonOrder } } - /** - * Classify the order as invoiced - * - * @return int <0 if ko, >0 if ok - * @deprecated - * @see classifyBilled() - */ - function classer_facturee() - { - global $user; - dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING); - - return $this->classifyBilled($user); - } - /** * Classify the order as not invoiced * @@ -2782,7 +2761,6 @@ class Commande extends CommonOrder if (! $error) { $this->oldcopy= clone $this; - $this->facturee=1; // deprecated $this->billed=1; } @@ -2793,7 +2771,6 @@ class Commande extends CommonOrder if (! $error) { - $this->facturee=0; // deprecated $this->billed=0; $this->db->commit(); @@ -3090,17 +3067,23 @@ class Commande extends CommonOrder $error++; $this->errors[]="Error ".$this->db->lasterror(); } - if (! $error) + if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) { - if (! $notrigger) + $result=$this->insertExtraFields(); + if ($result < 0) { - // Call trigger - $result=$this->call_trigger('ORDER_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers + $error++; } } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ORDER_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } + // Commit or rollback if ($error) { @@ -3329,7 +3312,6 @@ class Commande extends CommonOrder */ function getLibStatut($mode) { - if ($this->facturee && empty($this->billed)) $this->billed=$this->facturee; // For backward compatibility return $this->LibStatut($this->statut, $this->billed, $mode); } @@ -3704,9 +3686,10 @@ class Commande extends CommonOrder * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information * @return int 0 if KO, 1 if OK */ - public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null) { global $conf,$langs; @@ -3725,7 +3708,7 @@ class Commande extends CommonOrder $modelpath = "core/modules/commande/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } @@ -4240,7 +4223,7 @@ class OrderLine extends CommonOrderLine } } - if (! $notrigger) + if (! $error && ! $notrigger) { // Call trigger $result=$this->call_trigger('LINEORDER_UPDATE',$user); diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php index 0eb4ed2cd63..7669239134a 100644 --- a/htdocs/commande/contact.php +++ b/htdocs/commande/contact.php @@ -32,9 +32,8 @@ 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.'/projet/class/project.class.php'; -$langs->load("orders"); -$langs->load("sendings"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('orders', 'sendings', 'companies')); $id=GETPOST('id','int'); $ref=GETPOST('ref','alpha'); diff --git a/htdocs/commande/customer.php b/htdocs/commande/customer.php index 205efc3ad91..9263ceb3f45 100644 --- a/htdocs/commande/customer.php +++ b/htdocs/commande/customer.php @@ -42,8 +42,8 @@ if ($user->societe_id > 0) if (! $user->rights->facture->creer) accessforbidden(); -$langs->load("companies"); -$langs->load("orders"); +// Load translation files required by the page +$langs->loadLangs(array("companies", "orders")); $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -102,6 +102,12 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1, $offset); @@ -149,14 +155,10 @@ if ($resql) print "\n"; - $var=true; - while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); - - print ''; print ''; diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index ee688bed307..ffebbaa260a 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -36,9 +36,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } - -$langs->load('companies'); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'other')); $action = GETPOST('action','aZ09'); $confirm = GETPOST('confirm'); @@ -69,6 +68,7 @@ $object = new Commande($db); /* * Actions */ + if ($object->fetch($id)) { $object->fetch_thirdparty(); @@ -163,7 +163,7 @@ if ($id > 0 || ! empty($ref)) print ''; print ''; - print ''; + print ''; print "
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
\n"; diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php index feacdd70b07..5cfb87c7a25 100644 --- a/htdocs/commande/index.php +++ b/htdocs/commande/index.php @@ -31,8 +31,8 @@ require_once DOL_DOCUMENT_ROOT .'/commande/class/commande.class.php'; if (!$user->rights->commande->lire) accessforbidden(); -$langs->load("orders"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('orders', 'bills')); // Security check $socid=GETPOST('socid','int'); diff --git a/htdocs/commande/info.php b/htdocs/commande/info.php index 518ab856474..4bac4a3a447 100644 --- a/htdocs/commande/info.php +++ b/htdocs/commande/info.php @@ -33,8 +33,8 @@ if (! empty($conf->projet->enabled)) { if (!$user->rights->commande->lire) accessforbidden(); -$langs->load("orders"); -$langs->load("sendings"); +// Load translation files required by the page +$langs->loadLangs(array('orders', 'sendings')); $socid=0; $comid = GETPOST("id",'int'); diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 04ef69b2638..3734ab18a93 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -44,6 +44,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +// Load translation files required by the page $langs->loadLangs(array("orders",'sendings','deliveries','companies','compta','bills')); $action=GETPOST('action','aZ09'); @@ -51,6 +52,7 @@ $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'orderlist'; $search_orderyear=GETPOST("search_orderyear","int"); $search_ordermonth=GETPOST("search_ordermonth","int"); @@ -72,6 +74,7 @@ $socid=GETPOST('socid','int'); $search_user=GETPOST('search_user','int'); $search_sale=GETPOST('search_sale','int'); $search_total_ht=GETPOST('search_total_ht','alpha'); +$search_categ_cus=trim(GETPOST("search_categ_cus",'int')); $optioncss = GETPOST('optioncss','alpha'); $billed = GETPOST('billed','int'); $viewstatut=GETPOST('viewstatut'); @@ -98,11 +101,9 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield='c.ref'; if (! $sortorder) $sortorder='DESC'; -// Initialize technical object to manage context to save list fields -$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'orderlist'; - // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array($contextpage)); +$object = new Commande($db); +$hookmanager->initHooks(array('orderlist')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -197,6 +198,7 @@ if (empty($reshook)) $billed=''; $toselect=''; $search_array_options=array(); + $search_categ_cus=0; } if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha') || GETPOST('button_search_x','alpha') || GETPOST('button_search.x','alpha') || GETPOST('button_search','alpha')) @@ -212,6 +214,7 @@ if (empty($reshook)) $uploaddir = $conf->commande->dir_output; $trigger_name='ORDER_SENTBYMAIL'; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + } @@ -241,6 +244,8 @@ $sql.= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_clie $sql.= ' c.date_valid, c.date_commande, c.note_private, c.date_livraison as date_delivery, c.fk_statut, c.facture as billed,'; $sql.= ' c.date_creation as date_creation, c.tms as date_update,'; $sql.= " p.rowid as project_id, p.ref as project_ref"; +if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; + // 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 @@ -251,6 +256,7 @@ $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; +if (! empty($search_categ_cus)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ $sql.= ', '.MAIN_DB_PREFIX.'commande as c'; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)"; if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande'; @@ -331,6 +337,8 @@ if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$sear if ($search_user > 0) $sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; if ($search_total_ht != '') $sql.= natural_search('c.total_ht', $search_total_ht, 1); if ($search_project_ref != '') $sql.= natural_search("p.ref",$search_project_ref); +if ($search_categ_cus > 0) $sql.= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +if ($search_categ_cus == -2) $sql.= " AND cc.fk_categorie IS NULL"; // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -346,6 +354,12 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1,$offset); @@ -408,12 +422,13 @@ if ($resql) if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat); if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc); if ($search_project_ref >= 0) $param.="&search_project_ref=".urlencode($search_project_ref); - 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_type_thirdparty != '') $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); - if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); + 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_type_thirdparty != '') $param.='&search_type_thirdparty='.urlencode($search_type_thirdparty); + if ($search_product_category != '') $param.='&search_product_category='.urlencode($search_product_category); + if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus); if ($show_files) $param.='&show_files=' .urlencode($show_files); if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); if ($billed != '') $param.='&billed='.urlencode($billed); @@ -425,12 +440,22 @@ if ($resql) $arrayofmassactions = array( 'presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"), + 'cancelorders'=>$langs->trans("Cancel"), + ); if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if ($user->rights->commande->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); if (in_array($massaction, array('presend','predelete','createbills'))) $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + $newcardbutton=''; + if ($contextpage == 'orderlist' && $user->rights->commande->creer) + { + $newcardbutton=''.$langs->trans('NewOrder').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } + // Lines of title fields print '
'; if ($optioncss != '') print ''; @@ -443,7 +468,7 @@ if ($resql) print ''; print ''; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, '', '', $limit); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_commercial.png', 0, $newcardbutton, '', $limit); $topicmail="SendOrderRef"; $modelmail="order_send"; @@ -487,7 +512,7 @@ if ($resql) { print $form->selectyesno('valdate_invoices', 0, 1); } - if (! empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print '     '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").''; + if (! empty($conf->workflow->enabled) && ! empty($conf->global->WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_ORDER)) print '     '.$langs->trans("IfValidateInvoiceIsNoOrderStayUnbilled").''; else print '     '.$langs->trans("OptionToSetOrderBilledNotEnabled").''; print ''; print ''; @@ -504,7 +529,7 @@ if ($resql) if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + print '
'.$langs->trans("FilterOnInto", $all) . join(', ',$fieldstosearchall).'
'; } $moreforfilter=''; @@ -536,6 +561,14 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.=''; } + if (! empty($conf->categorie->enabled)) + { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter.=$formother->select_categories('customer',$search_categ_cus,'search_categ_cus',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; @@ -610,17 +643,17 @@ if ($resql) // Date order if (! empty($arrayfields['c.date_commande']['checked'])) { - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; $formother->select_year($search_orderyear?$search_orderyear:-1,'search_orderyear',1, 20, 5); print ''; } if (! empty($arrayfields['c.date_delivery']['checked'])) { - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; $formother->select_year($search_deliveryyear?$search_deliveryyear:-1,'search_deliveryyear',1, 20, 5); print ''; } @@ -1112,25 +1145,18 @@ if ($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); + $hidegeneratedfilelistifempty=1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; - $filedir=$diroutputmassaction; - $genallowed=$user->rights->commande->lire; - $delallowed=$user->rights->commande->creer; + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
'.$langs->trans("ShowTempMassFilesArea").''; - } + $filedir=$diroutputmassaction; + $genallowed=$user->rights->commande->lire; + $delallowed=$user->rights->commande->creer; + print $formfile->showdocuments('massfilesarea_orders','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty); } else { diff --git a/htdocs/commande/note.php b/htdocs/commande/note.php index 6598805490d..6cff3bfb3bc 100644 --- a/htdocs/commande/note.php +++ b/htdocs/commande/note.php @@ -32,10 +32,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } - -$langs->load("companies"); -$langs->load("bills"); -$langs->load("orders"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'bills', 'orders')); $id = GETPOST('id','int'); $ref=GETPOST('ref','alpha'); diff --git a/htdocs/commande/orderstoinvoice.php b/htdocs/commande/orderstoinvoice.php index 77c533b88b8..03d379270b1 100644 --- a/htdocs/commande/orderstoinvoice.php +++ b/htdocs/commande/orderstoinvoice.php @@ -39,9 +39,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } -$langs->load('orders'); -$langs->load('deliveries'); -$langs->load('companies'); +// Load translation files required by the page +$langs->loadLangs(array("orders", "deliveries", "companies")); if (! $user->rights->facture->creer) accessforbidden(); @@ -480,7 +479,7 @@ if ($action == 'create' && !$error) $parameters=array('objectsrc' => $objectsrc, 'idsrc' => $listoforders); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { $object=new Facture($db); print $object->showOptionals($extrafields,'edit'); @@ -553,7 +552,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -655,7 +654,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) print ''; print '
'; - $var=true; + $generic_commande = new Commande($db); while ($i < $num) @@ -703,7 +702,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error) print ''; // Statut - print ''.$generic_commande->LibStatut($objp->fk_statut,$objp->facturee,5).''; + print ''.$generic_commande->LibStatut($objp->fk_statut,$objp->billed,5).''; // Checkbox print ''; diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index b1baf7332a1..8f259808357 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -55,10 +55,8 @@ $year = GETPOST('year')>0?GETPOST('year'):$nowyear; $startyear=$year-1; $endyear=$year; -$langs->load('orders'); -$langs->load('companies'); -$langs->load('other'); -$langs->load('suppliers'); +// Load translation files required by the page +$langs->loadLangs(array('orders', 'companies', 'other', 'suppliers')); /* @@ -354,7 +352,7 @@ print '
'; // Show graphs -print ''; print "\n"; - $var=true; while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); @@ -178,7 +176,6 @@ if ($resql) $soc = new Societe($db); if ($obj->socid) $soc->fetch($obj->socid); - print ''; // Id print ''; diff --git a/htdocs/compta/deplacement/stats/index.php b/htdocs/compta/deplacement/stats/index.php index 36bc107d672..cf652948a6e 100644 --- a/htdocs/compta/deplacement/stats/index.php +++ b/htdocs/compta/deplacement/stats/index.php @@ -27,8 +27,8 @@ require '../../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacementstats.class.php'; -$langs->load("trips"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('trips', 'companies')); $WIDTH=DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT=DolGraph::getDefaultGraphSizeForStats('height'); @@ -294,7 +294,7 @@ print '
'; // Show graphs -print '
'; +print ' - - - - - + + + + - - + '; -$var=true; for ($mois = 1 ; $mois < 13 ; $mois++) { diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index f85e2a664fb..ec41a28327f 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -1,12 +1,13 @@ - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2018 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 * Copyright (C) 2016 Juanjo Menent * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -47,6 +48,7 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class. require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +// Load translation files required by the page $langs->loadLangs(array("banks","bills","categories","companies","margins","salaries","loan","donations","trips","members","compta","accountancy")); $id = GETPOST('id','int'); @@ -54,6 +56,7 @@ $ref = GETPOST('ref','alpha'); $action=GETPOST('action','alpha'); $cancel=GETPOST('cancel','alpha'); $confirm=GETPOST('confirm','alpha'); +$contextpage='banktransactionlist'.(empty($object->ref)?'':'-'.$object->id); // Security check $fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref :'')); @@ -90,7 +93,7 @@ $num_releve=GETPOST("num_releve","alpha"); $cat=GETPOST("cat"); if (empty($dateop)) $dateop=-1; -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -100,7 +103,7 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortorder) $sortorder='ASC'; +if (! $sortorder) $sortorder='desc,desc,desc'; if (! $sortfield) $sortfield='b.datev,b.dateo,b.rowid'; $mode_balance_ok=false; @@ -110,7 +113,6 @@ if (($sortfield == 'b.datev' || $sortfield == 'b.datev,b.dateo,b.rowid')) $sortfield = 'b.datev,b.dateo,b.rowid'; if ($id > 0 || ! empty($ref) || $search_account > 0) $mode_balance_ok = true; } -if (strtolower($sortorder) == 'desc') $mode_balance_ok = false; $object = new Account($db); if ($id > 0 || ! empty($ref)) @@ -120,10 +122,6 @@ if ($id > 0 || ! empty($ref)) } -// 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 page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('banktransactionlist', $contextpage)); $extrafields = new ExtraFields($db); @@ -430,9 +428,9 @@ if ($id > 0 || ! empty($ref)) if ($user->rights->banque->consolidate) { $newparam = $param; $newparam = preg_replace('/search_conciliated=\d+/i','',$newparam); - $buttonreconcile = ''.$langs->trans("Conciliate").''; + $buttonreconcile = ''.$langs->trans("Conciliate").''; } else { - $buttonreconcile = ''.$langs->trans("Conciliate").''; + $buttonreconcile = ''.$langs->trans("Conciliate").''; } } } @@ -446,7 +444,7 @@ $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappr $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"; +$sql.= " s.nom, s.name_alias, s.client, s.fournisseur, s.email, 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 @@ -527,8 +525,8 @@ 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); - +$sql.= $db->plimit($limit+1, $offset); +//print $sql; dol_syslog('compta/bank/bankentries_list.php', LOG_DEBUG); $resql = $db->query($sql); if ($resql) @@ -672,7 +670,7 @@ if ($resql) print ''; print ''; print ''; print ''; } if (! empty($arrayfields['b.num_chq']['checked'])) @@ -904,7 +912,7 @@ if ($resql) if (! empty($arrayfields['b.conciliated']['checked'])) { print ''; } print '\n"; - $balance = 0; // For balance + $balance = 0; // For balance + $balancebefore = 0; // For balance $balancecalculated = false; $posconciliatecol = 0; @@ -965,7 +974,7 @@ if ($resql) // Loop on each record before $sign = 1; $i = 0; - $sqlforbalance='SELECT SUM(b.amount) as balance'; + $sqlforbalance='SELECT SUM(b.amount) as previoustotal'; $sqlforbalance.= " FROM "; $sqlforbalance.= " ".MAIN_DB_PREFIX."bank_account as ba,"; $sqlforbalance.= " ".MAIN_DB_PREFIX."bank as b"; @@ -980,7 +989,16 @@ if ($resql) $objforbalance = $db->fetch_object($resqlforbalance); if ($objforbalance) { - $balance = $objforbalance->balance; + // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show + if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') + { + $balancebefore = $objforbalance->previoustotal + ($sign * $objp->amount); + } + // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show + else + { + $balance = $objforbalance->previoustotal; + } } } else dol_print_error($db); @@ -1028,6 +1046,7 @@ if ($resql) print ''; } + if (! empty($arrayfields['balancebefore']['checked'])) { print ''; print ''; @@ -1049,7 +1074,17 @@ if ($resql) } } - $balance = price2num($balance + ($sign * $objp->amount),'MT'); + + if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') + { + $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc) + $balancebefore = price2num($balancebefore - ($sign * $objp->amount),'MT'); + } + else + { + $balancebefore = price2num($balance, 'MT'); // balancebefore = balance of previous line (sort is asc) + $balance = price2num($balance + ($sign * $objp->amount),'MT'); + } if (empty($cachebankaccount[$objp->bankid])) { @@ -1269,6 +1304,7 @@ if ($resql) $companystatic->name=$objp->nom; $companystatic->name_alias=$objp->name_alias; $companystatic->client=$objp->client; + $companystatic->email=$objp->email; $companystatic->fournisseur=$objp->fournisseur; $companystatic->code_client=$objp->code_client; $companystatic->code_fournisseur=$objp->code_fournisseur; @@ -1326,7 +1362,6 @@ if ($resql) { if ($mode_balance_ok) { - $balancebefore = price2num($balance - ($sign * $objp->amount),'MT'); if ($balancebefore >= 0) { print ''; @@ -1388,14 +1423,14 @@ if ($resql) if (! empty($arrayfields['b.conciliated']['checked'])) { - print ''; if (! $i) $totalarray['nbfield']++; } // Action edit/delete - print ''; print ''; - $var=true; - // Current balance print ''; diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 2828963d889..1b4d7579892 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -35,6 +35,7 @@ if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } +// Load translation files required by the page $langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy")); // Get parameters diff --git a/htdocs/compta/bank/various_payment/document.php b/htdocs/compta/bank/various_payment/document.php index ff304676686..cf596860a4b 100644 --- a/htdocs/compta/bank/various_payment/document.php +++ b/htdocs/compta/bank/various_payment/document.php @@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; +// Load translation files required by the page $langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy")); $id = GETPOST('id','int'); diff --git a/htdocs/compta/bank/various_payment/index.php b/htdocs/compta/bank/various_payment/index.php index d52cbeb7595..6535e0c0082 100644 --- a/htdocs/compta/bank/various_payment/index.php +++ b/htdocs/compta/bank/various_payment/index.php @@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +// Load translation files required by the page $langs->loadLangs(array("compta","banks","bills","accountancy")); // Security check @@ -38,7 +39,7 @@ $result = restrictedArea($user, 'banque', '', '', ''); $optioncss = GETPOST('optioncss','alpha'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $search_ref = GETPOST('search_ref','int'); $search_user = GETPOST('search_user','alpha'); $search_label = GETPOST('search_label','alpha'); @@ -102,7 +103,7 @@ $sql = "SELECT v.rowid, v.sens, v.amount, v.label, v.datep as datep, v.datev as $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number as bank_account_number, ba.fk_accountancy_journal as accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_various as v"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id AND pst.entity IN (" . getEntity('c_paiement').")"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON v.fk_typepayment = pst.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON v.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE v.entity IN (".getEntity('payment_various').")"; @@ -137,7 +138,6 @@ if ($result) $num = $db->num_rows($result); $i = 0; $total = 0 ; - $var=true; $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); @@ -153,6 +153,14 @@ if ($result) if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + $newcardbutton=''; + if ($user->rights->banque->modifier) + { + $newcardbutton=''.$langs->trans('MenuNewVariousPayment').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } + print ''; if ($optioncss != '') print ''; @@ -163,7 +171,7 @@ if ($result) print ''; print ''; - print_barre_liste($langs->trans("VariousPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); + print_barre_liste($langs->trans("VariousPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, $newcardbutton, '', $limit); print '
'; print '
'; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/commande/tpl/linkedobjectblock.tpl.php b/htdocs/commande/tpl/linkedobjectblock.tpl.php index 39479ba220b..758a37eddb8 100644 --- a/htdocs/commande/tpl/linkedobjectblock.tpl.php +++ b/htdocs/commande/tpl/linkedobjectblock.tpl.php @@ -36,34 +36,36 @@ global $noMoreLinkedObjectBlockAfter; $langs = $GLOBALS['langs']; $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; +// Load translation files required by the page $langs->load("orders"); $total=0; $ilink=0; -$var=true; foreach($linkedObjectBlock as $key => $objectlink) { $ilink++; - $trclass=($var?'pair':'impair'); + $trclass='oddeven'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total'; ?> -
trans("CustomerOrder"); ?>getNomUrl(1); ?>ref_client; ?>date,'day'); ?>" > + trans("CustomerOrder"); ?> + global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) print ' + getNomUrl(1); ?>ref_client; ?>date,'day'); ?>rights->commande->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?>getLibStatut(3); ?> + getLibStatut(3); ?> element != 'shipping') { ?> - ">transnoentitiesnoconv("RemoveLink")); ?> + ">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?> @@ -87,4 +89,4 @@ if (count($linkedObjectBlock) > 1) } ?> - \ No newline at end of file + diff --git a/htdocs/compta/ajaxpayment.php b/htdocs/compta/ajaxpayment.php index 27a167bc576..5e83b3032c1 100644 --- a/htdocs/compta/ajaxpayment.php +++ b/htdocs/compta/ajaxpayment.php @@ -20,16 +20,11 @@ * \brief File to return Ajax response on payment breakdown process */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no menu to show if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) require '../main.inc.php'; @@ -66,7 +61,7 @@ foreach ($remains as $key => $value) } // Treatment -$result = $amountPayment != '' ? ($amountPayment - array_sum($amounts)) : ($amountPayment + array_sum($amounts)); // Remaining amountPayment +$result = ($amountPayment != '') ? ($amountPayment - array_sum($amounts)) : array_sum($amounts); // Remaining amountPayment $toJsonArray = array(); $totalRemaining = price2num(array_sum($remains)); $toJsonArray['label'] = $amountPayment == '' ? '' : $langs->transnoentities('RemainingAmountPayment'); diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index 3eee68bcb24..a786cf5ca28 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -29,8 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; -$langs->load("banks"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories')); $WIDTH=DolGraph::getDefaultGraphSizeForStats('width',380); // Large for one graph in a smarpthone. $HEIGHT=DolGraph::getDefaultGraphSizeForStats('height',160); @@ -200,7 +200,6 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) } print '
 '; - $form->select_types_paiements((GETPOST('operation')?GETPOST('operation'):($object->courant == Account::TYPE_CASH ? 'LIQ' : '')),'operation','1,2',2,1); + $form->select_types_paiements((GETPOST('operation')?GETPOST('operation'):($object->courant == Account::TYPE_CASH ? 'LIQ' : '')), 'operation', '1,2', 2, 1); print ''; print ''; @@ -725,7 +723,7 @@ if ($resql) // Title $bankcateg=new BankCateg($db); - $addbutton = ''; + $newcardbutton = ''; if ($action != 'addline' && $action != 'reconcile') { if (empty($conf->global->BANK_DISABLE_DIRECT_INPUT)) @@ -733,27 +731,37 @@ if ($resql) if (! empty($conf->global->BANK_USE_VARIOUS_PAYMENT)) // If direct entries is done using miscellaneous payments { if ($user->rights->banque->modifier) { - $addbutton = ''.$langs->trans("AddBankRecord").''; + $newcardbutton = ''.$langs->trans("AddBankRecord").''; + $newcardbutton.= ''; + $newcardbutton.= ''; } else { - $addbutton = ''.$langs->trans("AddBankRecord").''; + $newcardbutton = ''.$langs->trans("AddBankRecord"); + $newcardbutton.= ''; + $newcardbutton.= ''; } } else // If direct entries is not done using miscellaneous payments { if ($user->rights->banque->modifier) { - $addbutton = ''.$langs->trans("AddBankRecord").''; + $newcardbutton = ''.$langs->trans("AddBankRecord"); + $newcardbutton.= ''; + $newcardbutton.= ''; } else { - $addbutton = ''.$langs->trans("AddBankRecord").''; + $newcardbutton = ''.$langs->trans("AddBankRecord"); + $newcardbutton.= ''; + $newcardbutton.= ''; } } } else { - $addbutton = ''.$langs->trans("AddBankRecord").''; + $newcardbutton = ''.$langs->trans("AddBankRecord"); + $newcardbutton.= ''; + $newcardbutton.= ''; } } - $morehtml='
'; + $morehtml='
'; $morehtml.= ' "; // ' Page '; $morehtml.=''; $morehtml.='/'.$nbtotalofpages.' '; @@ -764,7 +772,7 @@ if ($resql) $morehtml.=$buttonreconcile; } - $morehtml.=$addbutton; + $morehtml.=$newcardbutton; $picto='title_bank'; if ($id > 0 || ! empty($ref)) $picto=''; @@ -851,7 +859,7 @@ if ($resql) if (! empty($arrayfields['type']['checked'])) { print '
'; - $form->select_types_paiements(empty($search_type)?'':$search_type, 'search_type', '', 2, 0, 1, 0, 1, 'maxwidth100'); + $form->select_types_paiements(empty($search_type)?'':$search_type, 'search_type', '', 2, 1, 1, 0, 1, 'maxwidth100'); print ''; - print $form->selectyesno('search_conciliated', $search_conciliated, 1, False, 1); + print $form->selectyesno('search_conciliated', $search_conciliated, 1, false, 1); print ''; @@ -934,14 +942,15 @@ if ($resql) // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields - $parameters=array('arrayfields'=>$arrayfields); + $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); $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="center"',$sortfield,$sortorder,'maxwidthsearch '); print "
'; print ''; @@ -1042,6 +1061,12 @@ if ($resql) } print ''; + print ''; + print ' '; print ''; print ' '.price($balancebefore).''; + print ''; print $objp->conciliated?$langs->trans("Yes"):$langs->trans("No"); print ''; + print ''; // Transaction reconciliated or edit link if ($objp->conciliated && $bankaccount->canBeConciliated() > 0) // If line not conciliated and account can be conciliated { diff --git a/htdocs/compta/bank/bilan.php b/htdocs/compta/bank/bilan.php index 22f7c8c9e79..5e5194d55c8 100644 --- a/htdocs/compta/bank/bilan.php +++ b/htdocs/compta/bank/bilan.php @@ -25,8 +25,8 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories')); if (!$user->rights->banque->lire) accessforbidden(); diff --git a/htdocs/compta/bank/budget.php b/htdocs/compta/bank/budget.php index 15aae28c1d1..280cd9bdbc0 100644 --- a/htdocs/compta/bank/budget.php +++ b/htdocs/compta/bank/budget.php @@ -27,8 +27,8 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories')); // Security check if ($user->societe_id) $socid=$user->societe_id; @@ -70,7 +70,6 @@ if ($result) $num = $db->num_rows($result); $i = 0; $total = 0; $totalnb = 0; - $var=true; while ($i < $num) { $objp = $db->fetch_object($result); diff --git a/htdocs/compta/bank/card.php b/htdocs/compta/bank/card.php index 38add1141f7..db497733863 100644 --- a/htdocs/compta/bank/card.php +++ b/htdocs/compta/bank/card.php @@ -39,6 +39,7 @@ if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; +// Load translation files required by the page $langs->loadLangs(array("banks","bills","categories","companies","compta")); $action = GETPOST('action','aZ09'); @@ -413,7 +414,7 @@ if ($action == 'create') $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit',$parameters); } @@ -803,15 +804,15 @@ else print ''; print ''."\n\n"; - dol_fiche_head(''); + dol_fiche_head(array(), 0, '', 0); - print '
'; + //print '
'; print ''; // Ref print ''; - print ''; + print ''; // Label print ''; @@ -914,7 +915,7 @@ else $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } diff --git a/htdocs/compta/bank/categ.php b/htdocs/compta/bank/categ.php index 83e1f15ef36..be029fcb2f5 100644 --- a/htdocs/compta/bank/categ.php +++ b/htdocs/compta/bank/categ.php @@ -30,8 +30,8 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; -$langs->load("banks"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories')); $action=GETPOST('action','aZ09'); @@ -101,11 +101,10 @@ if ($result) $num = $db->num_rows($result); $i = 0; $total = 0; - $var=True; while ($i < $num) { $objp = $db->fetch_object($result); - + print ''; print ''; if (GETPOST('action','aZ09') == 'edit' && GETPOST("categid")== $objp->rowid) @@ -136,7 +135,7 @@ if ($result) */ if ($action != 'edit') { - + print ''; print ''; print ''; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 8afcf967874..7228214e51c 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -395,9 +395,10 @@ class Account extends CommonObject * @param string $emetteur Name of cheque writer * @param string $banque Bank of cheque writer * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on. + * @param int $datev Date value * @return int Rowid of added entry, <0 if KO */ - function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='') + function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='', $accountancycode='', $datev=null) { // Deprecatîon warning if (is_numeric($oper)) { @@ -447,7 +448,7 @@ class Account extends CommonObject $this->db->begin(); - $datev = $date; + if (is_null($datev) || empty($datev)) $datev = $date; $accline = new AccountLine($this->db); $accline->datec = $now; @@ -505,10 +506,12 @@ class Account extends CommonObject * @param int $notrigger 1=Disable triggers * @return int < 0 if KO, > 0 if OK */ - function create(User $user = null, $notrigger=0) + function create(User $user, $notrigger=0) { global $langs,$conf, $hookmanager; + $error=0; + // Clean parameters if (! $this->min_allowed) $this->min_allowed=0; if (! $this->min_desired) $this->min_desired=0; @@ -668,7 +671,7 @@ class Account extends CommonObject * @param int $notrigger 1=Disable triggers * @return int <0 if KO, >0 if OK */ - function update(User $user = null, $notrigger = 0) + function update(User $user, $notrigger = 0) { global $langs,$conf, $hookmanager; @@ -913,12 +916,9 @@ class Account extends CommonObject $this->date_creation = $this->db->jdate($obj->date_creation); $this->date_update = $this->db->jdate($obj->date_update); - // Retreive all extrafield for thirdparty + // Retreive all extrafield // fetch optionals attributes and labels - require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + $this->fetch_optionals(); return 1; } @@ -1138,6 +1138,8 @@ class Account extends CommonObject */ function solde($option=0) { + $solde=0; + $sql = "SELECT sum(amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."bank"; $sql.= " WHERE fk_account = ".$this->id; @@ -1152,8 +1154,13 @@ class Account extends CommonObject $solde = $obj->amount; } $this->db->free($resql); - return $solde; + } else { + $this->errors[]=$this->db->lasterror; + return -1; } + + return $solde; + } /** @@ -1596,7 +1603,7 @@ class Account extends CommonObject $this->code_banque = '123'; $this->code_guichet = '456'; $this->number = 'ABC12345'; - $this->cle_rib = 50; + $this->cle_rib = '50'; $this->bic = 'AA12'; $this->iban = 'FR999999999'; $this->domiciliation = 'My bank address'; @@ -1907,7 +1914,7 @@ class AccountLine extends CommonObject */ function update_conciliation(User $user, $cat) { - global $conf; + global $conf,$langs; $this->db->begin(); @@ -2135,9 +2142,10 @@ class AccountLine extends CommonObject * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto * @param int $maxlen Longueur max libelle * @param string $option Option ('showall') + * @param int $notooltip 1=Disable tooltip * @return string Chaine avec URL */ - function getNomUrl($withpicto=0,$maxlen=0,$option='') + function getNomUrl($withpicto=0,$maxlen=0,$option='',$notooltip=0) { global $langs; diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php index 2fca317d1c4..33e74dc3691 100644 --- a/htdocs/compta/bank/document.php +++ b/htdocs/compta/bank/document.php @@ -25,17 +25,14 @@ * \brief Page de gestion des documents attaches a un compte bancaire */ require('../../main.inc.php'); -require_once(DOL_DOCUMENT_ROOT . "/core/lib/bank.lib.php"); -require_once(DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php"); -require_once(DOL_DOCUMENT_ROOT . "/core/lib/images.lib.php"); -require_once(DOL_DOCUMENT_ROOT . "/core/class/html.formfile.class.php"); +require_once DOL_DOCUMENT_ROOT . "/core/lib/bank.lib.php"; +require_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php"; +require_once DOL_DOCUMENT_ROOT . "/core/lib/images.lib.php"; +require_once DOL_DOCUMENT_ROOT . "/core/class/html.formfile.class.php"; require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php'; -$langs->load("banks"); - - -$langs->load('companies'); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'companies', 'other')); $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('account', 'int')); $ref = GETPOST('ref', 'alpha'); @@ -127,7 +124,7 @@ if ($id > 0 || !empty($ref)) { print '
'.$langs->trans("Ref").'ref).'">
ref).'">
'.$langs->trans("Label").'
'.$objp->rowid.'
 
'; print ''; - print ''; + print ''; print "
' . $langs->trans("NbOfAttachedFiles") . '' . count($filearray) . '
' . $langs->trans("TotalSizeOfAttachedFiles") . '' . $totalsize . ' ' . $langs->trans("bytes") . '
' . $langs->trans("TotalSizeOfAttachedFiles") . '' .dol_print_size($totalsize,1,1).'
\n"; print ''; diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index a813a71eeca..b829002a990 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -28,8 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; -$langs->load("banks"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories')); $WIDTH=DolGraph::getDefaultGraphSizeForStats('width',768); $HEIGHT=DolGraph::getDefaultGraphSizeForStats('height',200); diff --git a/htdocs/compta/bank/info.php b/htdocs/compta/bank/info.php index 832ec95dcd2..ab43b9374aa 100644 --- a/htdocs/compta/bank/info.php +++ b/htdocs/compta/bank/info.php @@ -26,9 +26,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'companies')); $id = GETPOST("rowid"); diff --git a/htdocs/compta/bank/ligne.php b/htdocs/compta/bank/ligne.php index 5cb97be90bb..e006f78c6e7 100644 --- a/htdocs/compta/bank/ligne.php +++ b/htdocs/compta/bank/ligne.php @@ -32,10 +32,8 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'compta', 'bills')); if (! empty($conf->adherent->enabled)) $langs->load("members"); if (! empty($conf->don->enabled)) $langs->load("donations"); if (! empty($conf->loan->enabled)) $langs->load("loan"); @@ -62,6 +60,7 @@ if (! $user->rights->banque->lire && ! $user->rights->banque->consolidate) acces /* * Actions */ + if ($cancel) { if ($backtopage) @@ -108,10 +107,23 @@ if ($user->rights->banque->modifier && $action == "update") { $error=0; - $ac = new Account($db); - $ac->fetch($id); + $acline = new AccountLine($db); + $acline->fetch($rowid); - if ($ac->courant == Account::TYPE_CASH && $_POST['value'] != 'LIQ') + $acsource = new Account($db); + $acsource->fetch($id); + + $actarget = new Account($db); + if (GETPOST('accountid','int') > 0 && ! $acline->rappro && ! $acline->getVentilExportCompta()) // We ask to change bank account + { + $actarget->fetch(GETPOST('accountid','int')); + } + else + { + $actarget->fetch($id); + } + + if ($actarget->courant == Account::TYPE_CASH && GETPOST('value','alpha') != 'LIQ') { setEventMessages($langs->trans("ErrorCashAccountAcceptsOnlyCashMoney"), null, 'errors'); $error++; @@ -119,16 +131,6 @@ if ($user->rights->banque->modifier && $action == "update") if (! $error) { - // Avant de modifier la date ou le montant, on controle si ce n'est pas encore rapproche - $conciliated=0; - $sql = "SELECT b.rappro FROM ".MAIN_DB_PREFIX."bank as b WHERE rowid=".$rowid; - $result = $db->query($sql); - if ($result) - { - $objp = $db->fetch_object($result); - $conciliated=$objp->rappro; - } - $db->begin(); $amount = price2num($_POST['amount']); @@ -142,15 +144,15 @@ if ($user->rights->banque->modifier && $action == "update") if (isset($_POST['banque'])) $sql.=" banque='".$db->escape($_POST["banque"])."',"; if (isset($_POST['emetteur'])) $sql.=" emetteur='".$db->escape($_POST["emetteur"])."',"; // Blocked when conciliated - if (! $conciliated) + if (! $acline->rappro) { if (isset($_POST['label'])) $sql.=" label='".$db->escape($_POST["label"])."',"; if (isset($_POST['amount'])) $sql.=" amount='".$amount."',"; if (isset($_POST['dateomonth'])) $sql.=" dateo = '".$db->idate($dateop)."',"; if (isset($_POST['datevmonth'])) $sql.=" datev = '".$db->idate($dateval)."',"; } - $sql.= " fk_account = ".$id; - $sql.= " WHERE rowid = ".$rowid; + $sql.= " fk_account = ".$actarget->id; + $sql.= " WHERE rowid = ".$acline->id; $result = $db->query($sql); if (! $result) @@ -282,7 +284,7 @@ if ($result) $account = $acct->id; $bankline = new AccountLine($db); - $bankline->fetch($rowid,$ref); + $bankline->fetch($rowid, $ref); $links=$acct->get_url($rowid); $bankline->load_previous_next_ref('','rowid'); @@ -311,21 +313,19 @@ if ($result) print '
'; print ''; - // Ref - /* - print '"; - print ''; - print ''; - */ - $i++; // Bank account print ''; print ''; print ''; diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 6a39416342e..e52e285742c 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -1,8 +1,11 @@ * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -32,16 +35,15 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("accountancy"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'accountancy', 'compta')); $action=GETPOST('action','alpha'); $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'bankaccountlist'; // To manage different context of search $search_ref=GETPOST('search_ref','alpha'); $search_label=GETPOST('search_label','alpha'); @@ -51,7 +53,8 @@ $optioncss = GETPOST('optioncss','alpha'); // Security check if ($user->societe_id) $socid=$user->societe_id; -$result=restrictedArea($user,'banque'); +if (! empty($user->rights->accounting->chartofaccount)) $allowed=1; // Dictionary with list of banks accounting account allowed to manager of chart account +if (! $allowed) $result=restrictedArea($user,'banque'); $diroutputmassaction=$conf->bank->dir_output . '/temp/massgeneration/'.$user->id; @@ -66,11 +69,9 @@ $pagenext = $page + 1; if (! $sortfield) $sortfield='b.label'; if (! $sortorder) $sortorder='ASC'; -// Initialize technical object to manage context to save list fields -$contextpage='bankaccountlist'; - // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array($contextpage)); +$object = new Account($db); +$hookmanager->initHooks(array('bankaccountlist')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -228,7 +229,9 @@ $massactionbutton=$form->selectMassAction('', $arrayofmassactions); $newcardbutton=''; if ($user->rights->banque->configurer) { - $newcardbutton.=''.$langs->trans("NewFinancialAccount").''; + $newcardbutton.=''.$langs->trans("NewFinancialAccount").''; + $newcardbutton.= ''; + $newcardbutton.= ''; } @@ -254,7 +257,7 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + print '
'.$langs->trans("FilterOnInto", $all) . join(', ',$fieldstosearchall).'
'; } $moreforfilter=''; @@ -387,7 +390,7 @@ if (! empty($arrayfields['toreconcile']['checked'])) print_liste_field_titr // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields -$parameters=array('arrayfields'=>$arrayfields); +$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (! empty($arrayfields['b.datec']['checked'])) print_liste_field_titre($arrayfields['b.datec']['label'],$_SERVER["PHP_SELF"],"b.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); @@ -399,7 +402,7 @@ print "\n"; $total = array(); $found = 0; $i=0; $lastcurrencycode=''; -$var=true; + foreach ($accounts as $key=>$type) { if ($i >= $limit) break; @@ -409,7 +412,6 @@ foreach ($accounts as $key=>$type) $obj = new Account($db); $obj->fetch($key); - $var = !$var; $solde = $obj->solde(1); if (! empty($lastcurrencycode) && $lastcurrencycode != $obj->currency_code) @@ -551,7 +553,7 @@ foreach ($accounts as $key=>$type) if (! empty($arrayfields['balance']['checked'])) { print '
'; if (! $i) $totalarray['nbfield']++; if (! $i) $totalarray['totalbalancefield']=$totalarray['nbfield']; diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php index a1e69cdc651..1d9d5526700 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -41,6 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; +// Load translation files required by the page $langs->loadLangs(array("banks","categories","companies","bills","trips")); $action=GETPOST('action', 'alpha'); @@ -72,7 +73,7 @@ if ($user->rights->banque->consolidate && $action == 'dvprev' && ! empty($dvid)) } -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -395,7 +396,6 @@ if (empty($numref)) $result = $db->query($sql); if ($result) { - $var=True; $numrows = $db->num_rows($result); $i = 0; @@ -534,11 +534,10 @@ else $title=$langs->trans("AccountStatement").' '.$numref.' - '.$langs->trans("BankAccount").' '.$object->getNomUrl(1, 'receipts'); print load_fiche_titre($title, $mesprevnext, 'title_bank.png'); //print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, 0, $nbtotalofrecords, 'title_bank.png', 0, '', '', 0, 1); - print '
'; print ""; print ''; - print ""; + print ''; print '
'; print '
'.$langs->trans("Ref")."'; - print $form->showrefnav($bankline, 'rowid', $linkback, 1, 'rowid', 'rowid'); - print '
'.$langs->trans("Account").''; - print $acct->getNomUrl(1,'transactions','reflabel'); + if (! $objp->rappro && ! $bankline->getVentilExportCompta()) + { + print $form->select_comptes($acct->id, 'accountid', 0, '', 0); + } + else + { + print $acct->getNomUrl(1,'transactions','reflabel'); + } print '
'; - print ''.price($solde, 0, $langs, 0, 0, -1, $obj->currency_code).''; + print ''.price($solde, 0, $langs, 0, -1, -1, $obj->currency_code).''; print '
'; @@ -573,7 +572,6 @@ else $result = $db->query($sql); if ($result) { - $var=False; $numrows = $db->num_rows($result); $i = 0; @@ -753,7 +751,7 @@ else while ($ii < $numc) { $objc = $db->fetch_object($resc); - print "
$objc->label"; + print "
".$objc->label.""; $ii++; } } @@ -776,7 +774,7 @@ else print '\n"; } - print '\n"; + print '\n"; if ($user->rights->banque->modifier || $user->rights->banque->consolidate) { @@ -798,8 +796,9 @@ else print "\n".'"; // Line Balance - print "\n"; - print '"; + print "\n"; + print ""; + print '"; print "\n"; print "
 '.price($objp->amount)."'.price($total)."'.price(price2num($total, 'MT'))."
'.$langs->trans("Total")." :".price($totald)."".price($totalc)."  
 ".$langs->trans("EndBankBalance")." :'.price($total)." 
 ".$langs->trans("EndBankBalance")." :'.price(price2num($total, 'MT'))." 
"; print ""; diff --git a/htdocs/compta/bank/transfer.php b/htdocs/compta/bank/transfer.php index e50d4822da7..765001e75a5 100644 --- a/htdocs/compta/bank/transfer.php +++ b/htdocs/compta/bank/transfer.php @@ -30,6 +30,7 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +// Load translation files required by the page $langs->loadLangs(array("banks", "categories", "multicurrency")); if (! $user->rights->banque->transfer) diff --git a/htdocs/compta/bank/treso.php b/htdocs/compta/bank/treso.php index 136e352ff00..0fb8880ce87 100644 --- a/htdocs/compta/bank/treso.php +++ b/htdocs/compta/bank/treso.php @@ -33,10 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.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"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'bills', 'companies')); // Security check if (isset($_GET["account"]) || isset($_GET["ref"])) @@ -117,8 +115,6 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) print '
'.$langs->trans("BankBalance").'
'."\n"; @@ -187,7 +195,7 @@ if ($result) // Type print ''; // Account diff --git a/htdocs/compta/bank/various_payment/info.php b/htdocs/compta/bank/various_payment/info.php index f6c7dc063f7..bb66871d6c0 100644 --- a/htdocs/compta/bank/various_payment/info.php +++ b/htdocs/compta/bank/various_payment/info.php @@ -26,6 +26,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +// Load translation files required by the page $langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy")); $id=GETPOST('id','int'); diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index 6e765cdacb0..6d369b696b9 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -34,8 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); // Security check if ($user->societe_id) $socid=$user->societe_id; @@ -48,7 +48,7 @@ if (! $year && $mode != 'sconly') { $year=date("Y", time()); } $search_account = GETPOST('search_account','int'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -139,7 +139,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pc.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE cs.fk_type = c.id"; @@ -166,12 +166,10 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $total = 0; $totalnb = 0; $totalpaye = 0; - $var=true; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $var = !$var; print ''; // Date $date=$obj->periode; @@ -260,7 +258,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."tva as pv"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON pv.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pv.fk_typepayment = pct.id"; $sql.= " WHERE pv.entity IN (".getEntity("tax").")"; if ($year > 0) { @@ -417,14 +415,13 @@ while($j<$numlt) print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"pv.datep","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"pv.amount","",$param,'align="right"',$sortfield,$sortorder); print "\n"; - $var=1; + while ($i < $num) { $obj = $db->fetch_object($result); $total = $total + $obj->amount; - print ''; print ''."\n"; @@ -474,7 +471,7 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read) $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id"; $sql.= " , ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE s.entity IN (".getEntity('user').")"; $sql.= " AND u.rowid = s.fk_user"; @@ -501,7 +498,7 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read) if (! empty($conf->banque->enabled)) print_liste_field_titre("Account",$_SERVER["PHP_SELF"],"ba.label","",$param,"",$sortfield,$sortorder); print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"s.amount","",$param,'align="right"',$sortfield,$sortorder); print "\n"; - $var=1; + while ($i < $num) { $obj = $db->fetch_object($result); diff --git a/htdocs/compta/clients.php b/htdocs/compta/clients.php index c65a7a670ae..ceb9324961e 100644 --- a/htdocs/compta/clients.php +++ b/htdocs/compta/clients.php @@ -39,7 +39,7 @@ if ($user->societe_id > 0) if (! $user->rights->facture->lire) accessforbidden(); - +// Load translation files required by the page $langs->load("companies"); $mode=GETPOST("mode"); @@ -172,14 +172,10 @@ if ($resql) print ''; print "\n"; - $var=true; - while ($i < min($num,$conf->liste_limit)) { $obj = $db->fetch_object($resql); - - print ''; print '"; print ''; - print ''; + print ''; print '
'; - $form->select_types_paiements($typeid,'typeid','',0,0,1,16); + $form->select_types_paiements($typeid,'typeid','',0,1,1,16); print '
'.dol_print_date($db->jdate($obj->dm),'day').'
'; $thirdpartystatic->id=$obj->rowid; diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index 979ef5960e0..05d509e268d 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -33,6 +33,7 @@ if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } +// Load translation files required by the page $langs->load("trips"); diff --git a/htdocs/compta/deplacement/document.php b/htdocs/compta/deplacement/document.php index 1f3974ce041..59d92140c86 100644 --- a/htdocs/compta/deplacement/document.php +++ b/htdocs/compta/deplacement/document.php @@ -34,10 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/trip.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -$langs->load("other"); -$langs->load("trips"); -$langs->load("companies"); -$langs->load("interventions"); +// Load translation files required by the page +$langs->loadLangs(array('other', 'trips', 'companies', 'interventions')); $id = GETPOST('id','int'); $ref = GETPOST('ref', 'alpha'); @@ -115,7 +113,7 @@ if ($object->id) //print "
".$langs->trans("Company")."".$object->client->getNomUrl(1)."
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
'; print ''; diff --git a/htdocs/compta/deplacement/index.php b/htdocs/compta/deplacement/index.php index 2cd3823bacd..a390023e280 100644 --- a/htdocs/compta/deplacement/index.php +++ b/htdocs/compta/deplacement/index.php @@ -27,9 +27,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; -$langs->load("companies"); -$langs->load("users"); -$langs->load("trips"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'users', 'trips')); // Security check $socid = GETPOST('socid','int'); @@ -45,7 +44,7 @@ $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder="DESC"; if (! $sortfield) $sortfield="d.dated"; -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; /* diff --git a/htdocs/compta/deplacement/info.php b/htdocs/compta/deplacement/info.php index 1e0279263e3..6a62484323f 100644 --- a/htdocs/compta/deplacement/info.php +++ b/htdocs/compta/deplacement/info.php @@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/trip.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; +// Load translation files required by the page $langs->load("trips"); // Security check diff --git a/htdocs/compta/deplacement/list.php b/htdocs/compta/deplacement/list.php index 807ddfee700..bdbdad0a712 100644 --- a/htdocs/compta/deplacement/list.php +++ b/htdocs/compta/deplacement/list.php @@ -30,9 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php' require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -$langs->load("companies"); -$langs->load("users"); -$langs->load("trips"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'users', 'trips')); // Security check $socid = GETPOST('socid','int'); @@ -46,7 +45,7 @@ $search_company=GETPOST('search_company','alpha'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -170,7 +169,6 @@ if ($resql) print '
'.img_object($langs->trans("ShowTrip"),"trip").' '.$obj->rowid.'
'; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; + + + if (count($object->tab_next_situation_invoice) > 0) { + // List of next invoices + /*print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print '';*/ + + $total_next_ht = $total_next_ttc = 0; + + foreach ($object->tab_next_situation_invoice as $next_invoice) { + $totalpaye = $next_invoice->getSommePaiement(); + $total_next_ht += $next_invoice->total_ht; + $total_next_ttc += $next_invoice->total_ttc; + + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; + + } + + $total_global_ht += $total_next_ht; + $total_global_ttc += $total_next_ttc; + + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; + } + + print '
'; +print ''; print ''; } @@ -2796,7 +3108,7 @@ if ($action == 'create') $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="2"', 'cols'=>2); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -2888,7 +3200,7 @@ if ($action == 'create') print ''; print ''; - switch ($classname) { + switch (get_class($objectsrc)) { case 'Propal': $newclassname = 'CommercialProposal'; break; @@ -2905,7 +3217,7 @@ if ($action == 'create') $newclassname = 'Intervention'; break; default: - $newclassname = $classname; + $newclassname = get_class($objectsrc); } print ''; // Relative and absolute discounts - $addrelativediscount = '' . $langs->trans("EditRelativeDiscounts") . ''; - $addabsolutediscount = '' . $langs->trans("EditGlobalDiscounts") . ''; - $addcreditnote = '' . $langs->trans("AddCreditNote") . ''; - $viewabsolutediscount = '' . $langs->trans("ViewAvailableGlobalDiscounts") . ''; - print ''; // Date invoice @@ -3629,54 +3889,10 @@ else if ($id > 0 || ! empty($ref)) print ""; print ''; - // Situations - if (! empty($conf->global->INVOICE_USE_SITUATION)) - { - if ($object->type == 5 && ($object->situation_counter > 1)) - { - $prevsits = $object->get_prev_sits(); - print ''; - print ''; - - // Previous situation(s) deduction(s) - for ($i = 0; $i < $cprevsits; $i++) { - print ''; - - print ''; - } - } - } // Incoterms if (!empty($conf->incoterm->enabled)) @@ -3812,8 +4028,6 @@ else if ($id > 0 || ! empty($ref)) print '
'; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/compta/facture/admin/facture_cust_extrafields.php b/htdocs/compta/facture/admin/facture_cust_extrafields.php index 7e6b069b0d9..2c676e399de 100644 --- a/htdocs/compta/facture/admin/facture_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_cust_extrafields.php @@ -29,9 +29,8 @@ require '../../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("admin"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'admin', 'bills')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php index 76284e7fe73..18aa3c99442 100644 --- a/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_rec_cust_extrafields.php @@ -30,9 +30,8 @@ require '../../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("admin"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'admin', 'bills')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php index d42139e4ec0..2b90ae7fe05 100644 --- a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php @@ -30,9 +30,8 @@ require '../../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("admin"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'admin', 'bills')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php index cc33b8dc026..97f8b78b195 100644 --- a/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_rec_cust_extrafields.php @@ -30,9 +30,8 @@ require '../../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("admin"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadlangs(array('companies', 'admin', 'bills')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 1d22d21d574..20d279c5113 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -64,6 +64,7 @@ if (! empty($conf->accounting->enabled)) { require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; } +// Load translation files required by the page $langs->loadLangs(array('bills','companies','compta','products','banks','main','withdrawals')); if (! empty($conf->incoterm->enabled)) $langs->load('incoterm'); if (! empty($conf->margin->enabled)) $langs->load('margins'); @@ -556,7 +557,7 @@ if (empty($reshook)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) ) { - $idwarehouse = GETPOST('idwarehouse'); + $idwarehouse = GETPOST('idwarehouse','int'); $object->fetch($id); $object->fetch_thirdparty(); @@ -643,8 +644,8 @@ if (empty($reshook)) else if ($action == 'confirm_paid_partially' && $confirm == 'yes' && $user->rights->facture->paiement) { $object->fetch($id); - $close_code = $_POST["close_code"]; - $close_note = $_POST["close_note"]; + $close_code = GETPOST("close_code",'none'); + $close_note = GETPOST("close_note",'none'); if ($close_code) { $result = $object->set_paid($user, $close_code, $close_note); if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); @@ -654,8 +655,8 @@ if (empty($reshook)) } // Classify "abandoned" else if ($action == 'confirm_canceled' && $confirm == 'yes') { $object->fetch($id); - $close_code = $_POST["close_code"]; - $close_note = $_POST["close_note"]; + $close_code = GETPOST("close_code",'none'); + $close_note = GETPOST("close_note",'none'); if ($close_code) { $result = $object->set_canceled($user, $close_code, $close_note); if ($result<0) setEventMessages($object->error, $object->errors, 'errors'); @@ -719,7 +720,7 @@ if (empty($reshook)) $sql = 'SELECT SUM(pf.amount) as total_paiements'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement') . ')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql.= ' WHERE pf.fk_facture = '.$object->id; $sql.= ' AND pf.fk_paiement = p.rowid'; $sql.= ' AND p.entity IN (' . getEntity('facture').')'; @@ -916,12 +917,21 @@ if (empty($reshook)) $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : ''; $object->type = Facture::TYPE_CREDIT_NOTE; + $facture_source = new Facture($db); // fetch origin object + if ($facture_source->fetch($object->fk_facture_source)>0) + { + if ($facture_source->type == Facture::TYPE_SITUATION) + { + $object->situation_counter = $facture_source->situation_counter; + $object->situation_cycle_ref = $facture_source->situation_cycle_ref; + $facture_source->fetchPreviousNextSituationInvoice(); + } + } $id = $object->create($user); if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0) { - $facture_source = new Facture($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source)>0) + if (!empty($facture_source->lines)) { $fk_parent_line = 0; @@ -938,6 +948,61 @@ if (empty($reshook)) $fk_parent_line = 0; } + + + + if($facture_source->type == Facture::TYPE_SITUATION) + { + + if(!empty($facture_source->tab_previous_situation_invoice)) + { + // search the last invoice in cycle + $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1; + $searchPreviousInvoice = true; + while( $searchPreviousInvoice ) + { + if($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) + { + $searchPreviousInvoice=false; // find, exit; + break; + } + else + { + $lineIndex--; // go to previous invoice in cycle + } + } + + + $maxPrevSituationPercent = 0; + foreach($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) + { + if($prevLine->id == $line->fk_prev_id) + { + $maxPrevSituationPercent = max($maxPrevSituationPercent,$prevLine->situation_percent); + + //$line->subprice = $line->subprice - $prevLine->subprice; + $line->total_ht = $line->total_ht - $prevLine->total_ht; + $line->total_tva = $line->total_tva - $prevLine->total_tva; + $line->total_ttc = $line->total_ttc - $prevLine->total_ttc; + $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1; + $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2; + + $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice; + $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht; + $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva; + $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc; + + + } + } + + // prorata + $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent; + + + } + } + $line->fk_facture = $object->id; $line->fk_parent_line = $fk_parent_line; @@ -971,7 +1036,6 @@ if (empty($reshook)) if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0) { - $facture_source = new Facture($db); // fetch origin object if not previously defined if ($facture_source->fetch($object->fk_facture_source)>0) { $totalpaye = $facture_source->getSommePaiement(); @@ -982,6 +1046,18 @@ if (empty($reshook)) $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC'); } } + + // Add link between credit note and origin + if(! empty($object->fk_facture_source)) { + $facture_source->fetch($object->fk_facture_source); + $facture_source->fetchObjectLinked(); + + if(! empty($facture_source->linkedObjectsIds)) { + foreach($facture_source->linkedObjectsIds as $sourcetype => $TIds) { + $object->add_object_linked($sourcetype, current($TIds)); + } + } + } } } @@ -1214,7 +1290,7 @@ if (empty($reshook)) { $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); $descline = $langs->trans('Deposit'); - $descline.= ' - '.$langs->trans($arraylist[$typeamount]); + //$descline.= ' - '.$langs->trans($arraylist[$typeamount]); if ($typeamount=='amount') { $descline.= ' ('. price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')'; } elseif ($typeamount=='variable') { @@ -1341,7 +1417,13 @@ if (empty($reshook)) $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty); $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty); - $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $localtax1_tx, $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, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit); + $result = $object->addline( + $desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $localtax1_tx, $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, $lines[$i]->rang, $lines[$i]->special_code, $object->origin, $lines[$i]->rowid, + $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, + $lines[$i]->situation_percent, $lines[$i]->fk_prev_id, $lines[$i]->fk_unit + ); if ($result > 0) { $lineid = $result; @@ -1421,6 +1503,7 @@ if (empty($reshook)) } } + // Situation invoices if (GETPOST('type') == Facture::TYPE_SITUATION && (!empty($_POST['situations']))) { $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); @@ -1472,16 +1555,16 @@ if (empty($reshook)) $object->fetch_thirdparty(); $object->date = $datefacture; $object->date_pointoftax = $date_pointoftax; - $object->note_public = trim($_POST['note_public']); - $object->note = trim($_POST['note']); - $object->ref_client = $_POST['ref_client']; - $object->ref_int = $_POST['ref_int']; - $object->modelpdf = $_POST['model']; - $object->fk_project = $_POST['projectid']; - $object->cond_reglement_id = $_POST['cond_reglement_id']; - $object->mode_reglement_id = $_POST['mode_reglement_id']; - $object->remise_absolue = $_POST['remise_absolue']; - $object->remise_percent = $_POST['remise_percent']; + $object->note_public = trim(GETPOST('note_public','none')); + $object->note = trim(GETPOST('note','none')); + $object->ref_client = GETPOST('ref_client','alpha'); + $object->ref_int = GETPOST('ref_int','alpha'); + $object->modelpdf = GETPOST('model','alpha'); + $object->fk_project = GETPOST('projectid','int'); + $object->cond_reglement_id = GETPOST('cond_reglement_id','int'); + $object->mode_reglement_id = GETPOST('mode_reglement_id','int'); + $object->remise_absolue = GETPOST('remise_absolue','int'); + $object->remise_percent = GETPOST('remise_percent','int'); // Proprietes particulieres a facture de remplacement @@ -1550,14 +1633,14 @@ if (empty($reshook)) // Set if we used free entry or predefined product $predef=''; - $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $product_desc=(GETPOST('dp_desc','none')?GETPOST('dp_desc','none'):''); $price_ht = GETPOST('price_ht'); $price_ht_devise = GETPOST('multicurrency_price_ht'); $prod_entry_mode = GETPOST('prod_entry_mode','alpha'); if ($prod_entry_mode == 'free') { $idprod=0; - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $tva_tx = (GETPOST('tva_tx','alpha') ? GETPOST('tva_tx','alpha') : 0); } else { @@ -1734,7 +1817,28 @@ if (empty($reshook)) // If price per quantity and customer elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - // TODO Same than PRODUIT_CUSTOMER_PRICES_BY_QTY but using $object->thirdparty->price_level + if ($prod->prices_by_qty[$object->thirdparty->price_level]) // yes, this product has some prices per quantity + { + // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. + $pqp = GETPOST('pbq','int'); + + // Search price into product_price_by_qty from $prod->id + foreach($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) + { + if ($priceforthequantityarray['rowid'] != $pqp) continue; + // We found the price + if ($priceforthequantityarray['price_base_type'] == 'HT') + { + $pu_ht = $priceforthequantityarray['unitprice']; + } + else + { + $pu_ttc = $priceforthequantityarray['unitprice']; + } + // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST. + break; + } + } } $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx)); @@ -1965,7 +2069,25 @@ if (empty($reshook)) $line->fetch(GETPOST('lineid')); $percent = $line->get_prev_progress($object->id); - if (GETPOST('progress') < $percent) + if($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref>0) + { + // in case of situation credit note + if(GETPOST('progress') >= 0 ) + { + $mesg = $langs->trans("CantBeNullOrPositive"); + setEventMessages($mesg, null, 'warnings'); + $error++; + $result = -1; + } + elseif (GETPOST('progress') < $line->situation_percent) // TODO : use a modified $line->get_prev_progress($object->id) result + { + $mesg = $langs->trans("CantBeLessThanMinPercent"); + setEventMessages($mesg, null, 'warnings'); + $error++; + $result = -1; + } + } + elseif (GETPOST('progress') < $percent) { $mesg = '
' . $langs->trans("CantBeLessThanMinPercent") . '
'; setEventMessages($mesg, null, 'warnings'); @@ -1983,7 +2105,7 @@ if (empty($reshook)) $type = $product->type; $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_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') : ''); @@ -2111,6 +2233,208 @@ if (empty($reshook)) exit(); } + // Outing situation invoice from cycle + elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $user->rights->facture->creer) + { + $object->fetch($id,'', '','', true); + + if ($object->statut == Facture::STATUS_VALIDATED + && $object->type == Facture::TYPE_SITUATION + && $user->rights->facture->creer + && !$objectidnext + && $object->is_last_in_cycle() + && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + ) + { + $outingError = 0; + $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle + if($newCycle > 1) + { + // Search credit notes + $lastCycle = $object->situation_cycle_ref; + $lastSituationCounter = $object->situation_counter; + $linkedCreditNotesList = array(); + + if (count($object->tab_next_situation_invoice) > 0) { + foreach ($object->tab_next_situation_invoice as $next_invoice) { + if($next_invoice->type == Facture::TYPE_CREDIT_NOTE + && $next_invoice->situation_counter == $object->situation_counter + && $next_invoice->fk_facture_source == $object->id + ) + { + $linkedCreditNotesList[] = $next_invoice->id ; + } + } + } + + $object->situation_cycle_ref = $newCycle; + $object->situation_counter = 1; + $object->situation_final = 0; + if($object->update($user) > 0) + { + $errors = 0; + if(count($linkedCreditNotesList) > 0) + { + // now, credit note must follow + $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture '; + $sql.= ' SET situation_cycle_ref='.$newCycle; + $sql.= ' , situation_final=0'; + $sql.= ' , situation_counter='.$object->situation_counter; + $sql.= ' WHERE rowid IN ('.implode(',',$linkedCreditNotesList).')'; + + $resql=$db->query($sql); + if (!$resql) $errors++; + + // Change each progression persent on each lines + foreach($object->lines as $line) + { + + // no traitement for special product + if ($line->product_type == 9 ) continue; + + + if(!empty($object->tab_previous_situation_invoice)) + { + // search the last invoice in cycle + $lineIndex = count($object->tab_previous_situation_invoice) - 1; + $searchPreviousInvoice = true; + while( $searchPreviousInvoice ) + { + if($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) + { + $searchPreviousInvoice=false; // find, exit; + break; + } + else + { + $lineIndex--; // go to previous invoice in cycle + } + } + + + $maxPrevSituationPercent = 0; + foreach($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) + { + if($prevLine->id == $line->fk_prev_id) + { + $maxPrevSituationPercent = max($maxPrevSituationPercent,$prevLine->situation_percent); + } + } + + + $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent; + + if($line->update()<0) $errors++; + + } + } + } + + if (!$errors) + { + setEventMessages($langs->trans('Updated'), '', 'mesgs'); + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); + } + else + { + setEventMessages($langs->trans('ErrorOutingSituationInvoiceCreditNote'), array(), 'errors'); + } + } + else + { + setEventMessages($langs->trans('ErrorOutingSituationInvoiceOnUpdate'), array(), 'errors'); + } + } + else + { + setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors'); + } + } + } + + // add lines from objectlinked + elseif($action == 'import_lines_from_object' + && $user->rights->facture->creer + && $object->statut == Facture::STATUS_DRAFT + && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) + { + $fromElement = GETPOST('fromelement'); + $fromElementid = GETPOST('fromelementid'); + $importLines = GETPOST('line_checkbox'); + + if(!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) + { + if($fromElement == 'commande') + { + dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php'); + $lineClassName = 'OrderLine'; + } + elseif($fromElement == 'propal') + { + dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php'); + $lineClassName = 'PropaleLigne'; + } + $nextRang = count($object->lines) + 1; + $importCount = 0; + $error = 0; + foreach($importLines as $lineId) + { + $lineId = intval($lineId); + $originLine = new $lineClassName($db); + if(intval($fromElementid) > 0 && $originLine->fetch( $lineId ) > 0) + { + $originLine->fetch_optionals($lineId); + $desc = $originLine->desc; + $pu_ht = $originLine->subprice; + $qty = $originLine->qty; + $txtva = $originLine->tva_tx; + $txlocaltax1 = $originLine->localtax1_tx; + $txlocaltax2 = $originLine->localtax2_tx; + $fk_product = $originLine->fk_product; + $remise_percent = $originLine->remise_percent; + $date_start = $originLine->date_start; + $date_end = $originLine->date_end; + $ventil = 0; + $info_bits = $originLine->info_bits; + $fk_remise_except = $originLine->fk_remise_except; + $price_base_type='HT'; + $pu_ttc=0; + $type = $originLine->product_type; + $rang=$nextRang++; + $special_code = $originLine->special_code; + $origin = $originLine->element; + $origin_id = $originLine->id; + $fk_parent_line=0; + $fk_fournprice=$originLine->fk_fournprice; + $pa_ht = $originLine->pa_ht; + $label = $originLine->label; + $array_options = $originLine->array_options; + $situation_percent = 100; + $fk_prev_id = ''; + $fk_unit = $originLine->fk_unit; + $pu_ht_devise = $originLine->multicurrency_subprice; + + $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $ventil, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit,$pu_ht_devise); + + if($res > 0){ + $importCount++; + }else{ + $error++; + } + } + else{ + $error++; + } + } + + if($error) + { + setEventMessage($langs->trans('ErrorsOnXLines',$error), 'errors'); + } + } + } + // Actions when printing a doc from card include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; @@ -2129,27 +2453,22 @@ if (empty($reshook)) if ($action == 'update_extras') { + $object->oldcopy = dol_clone($object); + // Fill array 'array_options' with data from add form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none')); if ($ret < 0) $error++; - if (! $error) { - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - $hookmanager->initHooks(array('invoicedao')); - $parameters = array('id' => $object->id); - $reshook = $hookmanager->executeHooks('insertExtraFields', $parameters, $object, $action); // Note that $action and $object may have been modified by - // some hooks - if (empty($reshook)) { - $result = $object->insertExtraFields(); - if ($result < 0) - { - setEventMessages($object->error, $object->errors, 'errors'); - $error++; - } - } else if ($reshook < 0) - $error ++; + if (! $error) + { + // Actions on extra fields + $result = $object->insertExtraFields('BILL_MODIFY'); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + $error++; + } } if ($error) @@ -2554,7 +2873,7 @@ if ($action == 'create') if (($origin == 'propal') || ($origin == 'commande')) { print '
'; - $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount'); + $arraylist = array('amount' => $langs->transnoentitiesnoconv('FixAmount'), 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit'))); print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1); print '' . $langs->trans('Value') . ':'; @@ -2714,19 +3033,12 @@ if ($action == 'create') { // 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 '.'; + + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1); @@ -3015,7 +3327,7 @@ else if ($id > 0 || ! empty($ref)) $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice } else { - $filterabsolutediscount = "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%'))"; + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; } @@ -3074,7 +3386,25 @@ else if ($id > 0 || ! empty($ref)) ); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1); } else { - $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', '', 1); + $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1); + } + } + + // Confirmation to remove invoice from cycle + if ($action == 'situationout') { + $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref); + $label = $langs->trans("ConfirmOuting"); + $formquestion = array(); + // remove situation from cycle + if ($object->statut == Facture::STATUS_VALIDATED + && $user->rights->facture->creer + && !$objectidnext + && $object->is_last_in_cycle() + && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + ) + { + $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1); } } @@ -3185,31 +3515,31 @@ else if ($id > 0 || ! empty($ref)) if ($action == 'paid' && $resteapayer > 0) { // Code $i = 0; - $close [$i] ['code'] = 'discount_vat'; // escompte + $close [$i]['code'] = 'discount_vat'; // escompte $i ++; - $close [$i] ['code'] = 'badcustomer'; + $close [$i]['code'] = 'badcustomer'; $i ++; // Help $i = 0; - $close [$i] ['label'] = $langs->trans("HelpEscompte") . '

' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc"); + $close [$i]['label'] = $langs->trans("HelpEscompte") . '

' . $langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc"); $i ++; - $close [$i] ['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc"); + $close [$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc"); $i ++; // Texte $i = 0; - $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1); + $close [$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1); $i ++; - $close [$i] ['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close [$i] ['label'], 1); + $close [$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency" . $conf->currency)), $close[$i]['label'], 1); $i ++; // arrayreasons[code]=reason foreach ($close as $key => $val) { - $arrayreasons [$close [$key] ['code']] = $close [$key] ['reason']; + $arrayreasons[$close [$key]['code']] = $close[$key]['reason']; } // Cree un tableau formulaire - $formquestion = array('text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"),array('type' => 'radio','name' => 'close_code','label' => $langs->trans("Reason"),'values' => $arrayreasons),array('type' => 'text','name' => 'close_note','label' => $langs->trans("Comment"),'value' => '','size' => '100')); + $formquestion = array('text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"),array('type' => 'radio','name' => 'close_code','label' => $langs->trans("Reason"),'values' => $arrayreasons),array('type' => 'text','name' => 'close_note','label' => $langs->trans("Comment"),'value' => '','morecss' => 'minwidth300')); // Paiement incomplet. On demande si motif = escompte ou autre - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes"); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?facid=' . $object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 310); } // Confirmation du classement abandonne @@ -3238,16 +3568,16 @@ else if ($id > 0 || ! empty($ref)) $arrayreasons [$close [2] ['code']] = $close [2] ['reason']; // Cree un tableau formulaire - $formquestion = array('text' => $langs->trans("ConfirmCancelBillQuestion"),array('type' => 'radio','name' => 'close_code','label' => $langs->trans("Reason"),'values' => $arrayreasons),array('type' => 'text','name' => 'close_note','label' => $langs->trans("Comment"),'value' => '','size' => '100')); + $formquestion = array('text' => $langs->trans("ConfirmCancelBillQuestion"),array('type' => 'radio','name' => 'close_code','label' => $langs->trans("Reason"),'values' => $arrayreasons),array('type' => 'text','name' => 'close_note','label' => $langs->trans("Comment"),'value' => '','morecss' => 'minwidth300')); - $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes"); + $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 250); } } if ($action == 'deletepaiement') { $payment_id = GETPOST('paiement_id'); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 'no', 1); } @@ -3288,7 +3618,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') . ' : ' . $object->thirdparty->getNomUrl(1); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' ('.$langs->trans("OtherBills").')'; // Project if (! empty($conf->projet->enabled)) @@ -3373,90 +3703,20 @@ else if ($id > 0 || ! empty($ref)) $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, $object->id); if ($result > 0){ - print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(), $discount->getNomUrl(1, 'discount')).'
'; + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'
'; } } print '
' . $langs->trans('Discounts'); - print ''; - if ($soc->remise_percent) - print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else - print $langs->trans("CompanyHasNoRelativeDiscount"); - // print ' ('.$addrelativediscount.')'; - // Is there is commercial discount or down payment available ? - if ($absolute_discount > 0) { - print '. '; - if ($object->statut > 0 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) { - if ($object->statut == 0) { - print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '. '; - } else { - if ($object->statut < 1 || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - print '
' . $text . '.
'; - } else { - $text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency)); - $text2 = $langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text, $text2); - } - } - } else { - // 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 . ')'); - } - } else { - if ($absolute_creditnote > 0) // If not, link will be added later - { - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
'; - else - print '. '; - } else - print '. '; - } - // Is there credit notes availables ? - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE) { - if ($object->statut == 0 && $object->type != Facture::TYPE_DEPOSIT) { - $text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)); - print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse")); - } else { - print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.'; - } - } else { // We can add a credit note on a down payment or standard invoice or situation invoice - // There is credit notes discounts available - if (! $absolute_discount) print '
'; - // $form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer); - $more=' ('.$addcreditnote. (($addcreditnote && $viewabsolutediscount) ? ' - ' : '') . $viewabsolutediscount . ')'; - $form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0, $more); // We allow credit note even if amount is higher - } - } - if (! $absolute_discount && ! $absolute_creditnote) { - print $langs->trans("CompanyHasNoAbsoluteDiscount"); - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT) - print ' (' . $addabsolutediscount . ')
'; - else - print '. '; - } - // if ($object->statut == 0 && $object->type != 2 && $object->type != 3) - // { - // if (! $absolute_discount && ! $absolute_creditnote) print '
'; - // print '   -   '; - // print $addabsolutediscount; - // print '   -   '.$addcreditnote; // We disbale link to credit note - // } + print '
'; + $thirdparty = $soc; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print '
'; - print $langs->trans('SituationAmount'); - print ' '; - print $prevsits[0]->situation_counter; - $cprevsits = count($prevsits); - for ($i = 1; $i < $cprevsits; $i++) { - print ' + '; - print $prevsits[$i]->situation_counter; - } - print ' + '; - print $object->situation_counter; - print ''; - $prevsits_total_amount = 0; - foreach ($prevsits as $situation) { - $prevsits_total_amount += $situation->total_ht; - } - $prevsits_total_amount += $object->total_ht; - - print price($prevsits_total_amount, 0, $langs, 1, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency) ); - - print '
'; - print ''; - print $langs->trans('SituationDeduction'); - print ' '; - print $prevsits[$i]->situation_counter; - print ''; - print '- ' . price($prevsits[$i]->total_ht, 0, $langs, 1, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency) ); - print '
'; - // List of previous situation invoices - $sign = 1; if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = - 1; $nbrows = 8; @@ -3835,88 +4049,129 @@ else if ($id > 0 || ! empty($ref)) if (! empty($conf->incoterm->enabled)) $nbrows += 1; - if ($object->type == Facture::TYPE_SITUATION && ! empty($conf->global->INVOICE_USE_SITUATION)) + // List of previous situation invoices + if (($object->situation_cycle_ref > 0) && ! empty($conf->global->INVOICE_USE_SITUATION)) { - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print ''; - if (count($object->tab_previous_situation_invoice) > 0) { - // List of previous invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + print '
' . $langs->trans('ListOfPreviousSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
'; - $total_prev_ht = $total_prev_ttc = 0; - foreach ($object->tab_previous_situation_invoice as $prev_invoice) { - $totalpaye = $prev_invoice->getSommePaiement(); - $total_prev_ht += $prev_invoice->total_ht; - $total_prev_ttc += $prev_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; - } - if (count($object->tab_next_situation_invoice) > 0) { - // List of next invoices - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + $total_prev_ht = $total_prev_ttc = 0; + $total_global_ht = $total_global_ttc = 0; - $total_next_ht = $total_next_ttc = 0; + if (count($object->tab_previous_situation_invoice) > 0) { + // List of previous invoices - foreach ($object->tab_next_situation_invoice as $next_invoice) { - $totalpaye = $next_invoice->getSommePaiement(); - $total_next_ht += $next_invoice->total_ht; - $total_next_ttc += $next_invoice->total_ttc; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print ''; + $current_situation_counter = array(); + foreach ($object->tab_previous_situation_invoice as $prev_invoice) { + $totalpaye = $prev_invoice->getSommePaiement(); + $total_prev_ht += $prev_invoice->total_ht; + $total_prev_ttc += $prev_invoice->total_ttc; + $current_situation_counter[] = (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE)?-1:1) * $prev_invoice->situation_counter; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; + } + } - } - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; + $total_global_ht += $total_prev_ht ; + $total_global_ttc += $total_prev_ttc ; + $total_global_ht += $object->total_ht; + $total_global_ttc += $object->total_ttc; + $current_situation_counter[] = (($object->type == Facture::TYPE_CREDIT_NOTE)?-1:1) * $object->situation_counter; + print ''; + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; - } - if (count($object->tab_previous_situation_invoice) > 0 || count($object->tab_next_situation_invoice) > 0) - print '
' . $prev_invoice->getNomUrl(1) . '' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
' . $langs->trans('ListOfSituationInvoices') . '' . $langs->trans('Situation') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . price($total_prev_ht) . '' . price($total_prev_ttc) . ' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $next_invoice->getNomUrl(1) . '' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
' . $prev_invoice->getNomUrl(1) . ''.(($prev_invoice->type == Facture::TYPE_CREDIT_NOTE)?$langs->trans('situationInvoiceShortcode_AS'):$langs->trans('situationInvoiceShortcode_S')) . $prev_invoice->situation_counter.'' . price($prev_invoice->total_ht) . '' . price($prev_invoice->total_ttc) . '' . $prev_invoice->getLibStatut(3, $totalpaye) . '
' . $object->getNomUrl(1) . ''.(($object->type == Facture::TYPE_CREDIT_NOTE)?$langs->trans('situationInvoiceShortcode_AS'):$langs->trans('situationInvoiceShortcode_S')) . $object->situation_counter.'' . price($object->total_ht) . '' . price($object->total_ttc) . '' . $object->getLibStatut(3, $object->getSommePaiement()) . '
' . price($total_next_ht) . '' . price($total_next_ttc) . ' 
'; + print '
' . $langs->trans('CurrentSituationTotal') . ''; + $i =0; + foreach ($current_situation_counter as $sit) + { + $curSign = $sit>0?'+':'-'; + $curType = $sit>0?$langs->trans('situationInvoiceShortcode_S'):$langs->trans('situationInvoiceShortcode_AS'); + if($i>0) print ' '.$curSign.' '; + print $curType . abs($sit); + $i++; + } + print '' . price($total_global_ht) . '' . price($total_global_ttc) . ' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $next_invoice->getNomUrl(1) . ''.(($next_invoice->type == Facture::TYPE_CREDIT_NOTE)?$langs->trans('situationInvoiceShortcode_AS'):$langs->trans('situationInvoiceShortcode_S')) . $next_invoice->situation_counter.'' . price($next_invoice->total_ht) . '' . price($next_invoice->total_ttc) . '' . $next_invoice->getLibStatut(3, $totalpaye) . '
' . price($total_global_ht) . '' . price($total_global_ttc) . ' 
'; } @@ -4068,7 +4323,7 @@ else if ($id > 0 || ! empty($ref)) print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1); print '' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' '; $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; + $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Paye partiellement ou Abandon 'badcustomer' if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') { @@ -4076,7 +4331,7 @@ else if ($id > 0 || ! empty($ref)) print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1); print '' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' '; // $resteapayeraffiche=0; - $cssforamountpaymentcomplete = ''; + $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Paye partiellement ou Abandon 'product_returned' if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') { @@ -4084,7 +4339,7 @@ else if ($id > 0 || ! empty($ref)) print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1); print '' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' '; $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; + $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Paye partiellement ou Abandon 'abandon' if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { @@ -4095,7 +4350,7 @@ else if ($id > 0 || ! empty($ref)) print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1); print '' . price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')) . ' '; $resteapayeraffiche = 0; - $cssforamountpaymentcomplete = ''; + $cssforamountpaymentcomplete = 'amountpaymentneutral'; } // Billed @@ -4113,7 +4368,7 @@ else if ($id > 0 || ! empty($ref)) } else // Credit note { - $cssforamountpaymentcomplete=''; + $cssforamountpaymentcomplete='amountpaymentneutral'; // Total already paid back print ''; @@ -4128,7 +4383,7 @@ else if ($id > 0 || ! empty($ref)) if ($resteapayeraffiche <= 0) print $langs->trans('RemainderToPayBack'); else - print $langs->trans('ExcessPaydBack'); + print $langs->trans('ExcessPaid'); print ' :'; print '' . price($sign * $resteapayeraffiche) . ''; print ' '; @@ -4248,7 +4503,7 @@ else if ($id > 0 || ! empty($ref)) // Form to add new line if ($object->statut == 0 && $user->rights->facture->creer && $action != 'valid' && $action != 'editline' && ($object->is_first() || !$object->situation_cycle_ref)) { - if ($action != 'editline') + if ($action != 'editline' && $action != 'selectlines') { // Add free products/services $object->formAddObjectLine(1, $mysoc, $soc); @@ -4290,7 +4545,7 @@ else if ($id > 0 || ! empty($ref)) if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) { - print ''; + print ''; } else { print '
' . $langs->trans('Modify') . '
'; } @@ -4319,7 +4574,7 @@ else if ($id > 0 || ! empty($ref)) { if (! $objectidnext && $object->close_code != 'replaced') // Not replaced by another invoice { - print ''; + print ''; } else { print '
' . $langs->trans('ReOpen') . '
'; } @@ -4330,19 +4585,19 @@ else if ($id > 0 || ! empty($ref)) if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->validate))) { - print ''; + print ''; } } // Send by mail if (($object->statut == Facture::STATUS_VALIDATED || $object->statut == Facture::STATUS_CLOSED) || ! empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) { if ($objectidnext) { - print '
' . $langs->trans('SendByMail') . '
'; + print '
' . $langs->trans('SendMail') . '
'; } else { if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->facture->invoice_advance->send) { - print ''; + print ''; } else - print ''; + print ''; } } @@ -4402,16 +4657,16 @@ else if ($id > 0 || ! empty($ref)) // For standard invoice with excess received if ($object->type == Facture::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $user->rights->facture->creer && empty($discount->id)) { - print ''; + print ''; } // For credit note if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->facture->creer && $object->getSommePaiement() == 0) { - print ''; + print ''; } // For deposit invoice if ($object->type == Facture::TYPE_DEPOSIT && $user->rights->facture->creer && $object->statut > 0 && empty($discount->id)) { - print ''; + print ''; } } @@ -4420,7 +4675,7 @@ else if ($id > 0 || ! empty($ref)) || ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $user->rights->facture->paiement && empty($discount->id)) ) { - print ''; + print ''; } // Classify 'closed not completely paid' (possible si validee et pas encore classee payee) @@ -4430,7 +4685,7 @@ else if ($id > 0 || ! empty($ref)) if ($totalpaye > 0 || $totalcreditnotes > 0) { // If one payment or one credit note was linked to this invoice - print ''; + print ''; } else { @@ -4442,7 +4697,7 @@ else if ($id > 0 || ! empty($ref)) } else { - print ''; + print ''; } } } @@ -4451,7 +4706,7 @@ else if ($id > 0 || ! empty($ref)) // Clone if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $user->rights->facture->creer) { - print ''; + print ''; } // Clone as predefined / Create template @@ -4472,6 +4727,45 @@ else if ($id > 0 || ! empty($ref)) } } + // For situation invoice with excess received + if ($object->statut > Facture::STATUS_DRAFT + && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) > 0 + && $user->rights->facture->creer + && !$objectidnext + && $object->is_last_in_cycle() + && $conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE + ) + { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + { + print ''; + } else { + print '
' . $langs->trans("CreateCreditNote") . '
'; + } + } + + // remove situation from cycle + if ($object->statut > Facture::STATUS_DRAFT + && $object->type == Facture::TYPE_SITUATION + && $user->rights->facture->creer + && !$objectidnext + && $object->situation_counter > 1 + && $object->is_last_in_cycle() + && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->creer)) + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->facture->invoice_advance->unvalidate))) + ) + { + if(($object->total_ttc - $totalcreditnotes ) == 0 ) + { + print ''; + } + else + { + print ''; + } + } + // Create next situation invoice if ($user->rights->facture->creer && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) { if ($object->is_last_in_cycle() && $object->situation_final != 1) { @@ -4510,7 +4804,7 @@ else if ($id > 0 || ! empty($ref)) } else { - print ''; + print ''; } } else { print ''; @@ -4540,7 +4834,15 @@ else if ($id > 0 || ! empty($ref)) // Show links to link elements $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + + $compatibleImportElementsList = false; + if($user->rights->facture->creer + && $object->statut == Facture::STATUS_DRAFT + && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) ) + { + $compatibleImportElementsList = array('commande','propal'); // import from linked elements + } + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem,$compatibleImportElementsList); // Show online payment link diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index a114829d43c..7012b0ef800 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -81,6 +81,9 @@ class Invoices extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } + // Add external contacts ids + $this->invoice->contacts_ids = $this->invoice->liste_contact(-1,'external',1); + $this->invoice->fetchObjectLinked(); return $this->_cleanObjectDatas($this->invoice); } @@ -176,6 +179,9 @@ class Invoices extends DolibarrApi $invoice_static->totaldeposits = $invoice_static->getSumDepositsUsed(); $invoice_static->remaintopay = price2num($invoice_static->total_ttc - $invoice_static->totalpaid - $invoice_static->totalcreditnotes - $invoice_static->totaldeposits, 'MT'); + // Add external contacts ids + $invoice_static->contacts_ids = $invoice_static->liste_contact(-1,'external',1); + $obj_ret[] = $this->_cleanObjectDatas($invoice_static); } $i++; @@ -196,7 +202,7 @@ class Invoices extends DolibarrApi * @param array $request_data Request datas * @return int ID of invoice */ - function post($request_data = NULL) + function post($request_data = null) { if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401, "Insuffisant rights"); @@ -313,7 +319,7 @@ class Invoices extends DolibarrApi * @throws 401 * @throws 404 */ - function putLine($id, $lineid, $request_data = NULL) { + function putLine($id, $lineid, $request_data = null) { if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } @@ -414,7 +420,7 @@ class Invoices extends DolibarrApi * @param array $request_data Datas * @return int */ - function put($id, $request_data = NULL) + function put($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); @@ -485,7 +491,13 @@ class Invoices extends DolibarrApi /** * Add a line to a given invoice * - * Exemple of POST query : { "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null } + * Exemple of POST query : + * { + * "desc": "Desc", "subprice": "1.00000000", "qty": "1", "tva_tx": "20.000", "localtax1_tx": "0.000", "localtax2_tx": "0.000", + * "fk_product": "1", "remise_percent": "0", "date_start": "", "date_end": "", "fk_code_ventilation": 0, "info_bits": "0", + * "fk_remise_except": null, "product_type": "1", "rang": "-1", "special_code": "0", "fk_parent_line": null, "fk_fournprice": null, + * "pa_ht": "0.00000000", "label": "", "array_options": [], "situation_percent": "100", "fk_prev_id": null, "fk_unit": null + * } * * @param int $id Id of invoice * @param array $request_data InvoiceLine data @@ -499,7 +511,7 @@ class Invoices extends DolibarrApi * @throws 404 * @throws 400 */ - function postLine($id, $request_data = NULL) { + function postLine($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->facture->creer) { throw new RestException(401); } @@ -562,6 +574,59 @@ class Invoices extends DolibarrApi return $updateRes; } + /** + * Adds a contact to an invoice + * + * @param int $id Order ID + * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link + * @param string $type_contact Type of contact (code). Must a code found into table llx_c_type_contact. For example: BILLING + * @param string $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) + * @param int $notrigger Disable all triggers + * + * @url POST {id}/contacts + * + * @return array + * + * @throws 200 + * @throws 304 + * @throws 401 + * @throws 404 + * @throws 500 + * + */ + function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0) + { + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(401); + } + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->invoice->add_contact($fk_socpeople,$type_contact,$source,$notrigger); + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->invoice->error); + } + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + return $this->_cleanObjectDatas($this->invoice); + } + + + /** * Sets an invoice as draft * @@ -899,14 +964,13 @@ class Invoices extends DolibarrApi return $result; } - /** - * Add payment line to a specific invoice - * - * The model schema is defined by the PaymentData class. + + /** + * Add payment line to a specific invoice with the remain to pay as amount. * * @param int $id Id of invoice - * @param string $datepaye {@from body} Payment date {@type timestamp} - * @param int $paiementid {@from body} Payment mode Id {@min 1} + * @param string $datepaye {@from body} Payment date {@type timestamp} + * @param int $paiementid {@from body} Payment mode Id {@min 1} * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} * @param int $accountid {@from body} Account Id {@min 1} * @param string $num_paiement {@from body} Payment number (optional) @@ -922,63 +986,194 @@ class Invoices extends DolibarrApi * @throws 404 */ function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement='', $comment='', $chqemetteur='', $chqbank='') { + global $conf; + + require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; + + if(! DolibarrApiAccess::$user->rights->facture->creer) { + throw new RestException(403); + } + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory'); + } + + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + if (! empty($conf->banque->enabled)) { + if(empty($accountid)) { + throw new RestException(400, 'Account ID is mandatory'); + } + } + + if(empty($paiementid)) { + throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + } + + + $result = $this->invoice->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Invoice not found'); + } + + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement(); + $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $totaldeposits = $this->invoice->getSumDepositsUsed(); + $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + + $this->db->begin(); + + $amounts = array(); + $multicurrency_amounts = array(); + + // Clean parameters amount if payment is for a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = -$resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = -$newvalue; + } else { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = $resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = $newvalue; + } + + + // Creation of payment line + $paiement = new Paiement($this->db); + $paiement->datepaye = $datepaye; + $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id + $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching + $paiement->paiementid = $paiementid; + $paiement->paiementcode = dol_getIdFromCode($this->db,$paiementid,'c_paiement','id','code',1); + $paiement->num_paiement = $num_paiement; + $paiement->note = $comment; + + $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices=='yes'?1:0)); // This include closing invoices + if ($paiement_id < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Payment error : '.$paiement->error); + } + + if (! empty($conf->banque->enabled)) { + $label='(CustomerInvoicePayment)'; + + if($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { + throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); + } + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label='(CustomerInvoicePaymentBack)'; // Refund of a credit note + $result=$paiement->addPaymentToBank(DolibarrApiAccess::$user,'payment',$label,$accountid,$chqemetteur,$chqbank); + if ($result < 0) + { + $this->db->rollback(); + throw new RestException(400, 'Add payment to bank error : '.$paiement->error); + } + } + + $this->db->commit(); + + return $paiement_id; + } + + /** + * Add a payment to pay partially or completely one or several invoices. + * Warning: Take care that all invoices are owned by the same customer. + * Example of value for parameter arrayofamounts: {"1": "99.99", "2": "10"} + * + * @param array $arrayofamounts {@from body} Array with id of invoices with amount to pay for each invoice + * @param string $datepaye {@from body} Payment date {@type timestamp} + * @param int $paiementid {@from body} Payment mode Id {@min 1} + * @param string $closepaidinvoices {@from body} Close paid invoices {@choice yes,no} + * @param int $accountid {@from body} Account Id {@min 1} + * @param string $num_paiement {@from body} Payment number (optional) + * @param string $comment {@from body} Note (optional) + * @param string $chqemetteur {@from body} Payment issuer (mandatory if paiementcode = 'CHQ') + * @param string $chqbank {@from body} Issuer bank name (optional) + * + * @url POST /paymentsdistributed + * + * @return int Payment ID + * @throws 400 + * @throws 401 + * @throws 403 + * @throws 404 + */ + function addPaymentDistributed($arrayofamounts, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement='', $comment='', $chqemetteur='', $chqbank='') + { global $conf; require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php'; if(! DolibarrApiAccess::$user->rights->facture->creer) { - throw new RestException(401); + throw new RestException(403); } - if(empty($id)) { - throw new RestException(400, 'Invoice ID is mandatory'); - } - - if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + foreach($arrayofamounts as $id => $amount) { + if(empty($id)) { + throw new RestException(400, 'Invoice ID is mandatory. Fill the invoice id and amount into arrayofamounts parameter. For example: {"1": "99.99", "2": "10"}'); + } + if( ! DolibarrApi::_checkAccessToResource('facture',$id)) { + throw new RestException(403, 'Access not allowed on invoice ID '.$id.' for login '.DolibarrApiAccess::$user->login); + } } if (! empty($conf->banque->enabled)) { - if(empty($accountid)) { - throw new RestException(400, 'Account ID is mandatory'); - } + if(empty($accountid)) { + throw new RestException(400, 'Account ID is mandatory'); + } } - if(empty($paiementid)) { - throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); + throw new RestException(400, 'Paiement ID or Paiement Code is mandatory'); } - - $result = $this->invoice->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Invoice not found'); - } - - // Calculate amount to pay - $totalpaye = $this->invoice->getSommePaiement(); - $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); - $totaldeposits = $this->invoice->getSumDepositsUsed(); - $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - $this->db->begin(); $amounts = array(); $multicurrency_amounts = array(); - // Clean parameters amount if payment is for a credit note - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { - $resteapayer = price2num($resteapayer,'MT'); - $amounts[$id] = -$resteapayer; - // Multicurrency - $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); - $multicurrency_amounts[$id] = -$newvalue; - } else { - $resteapayer = price2num($resteapayer,'MT'); - $amounts[$id] = $resteapayer; - // Multicurrency - $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); - $multicurrency_amounts[$id] = $newvalue; - } + // Loop on each invoice to pay + foreach($arrayofamounts as $id => $amount) + { + $result = $this->invoice->fetch($id); + if( ! $result ) { + $this->db->rollback(); + throw new RestException(404, 'Invoice ID '.$id.' not found'); + } + // Calculate amount to pay + $totalpaye = $this->invoice->getSommePaiement(); + $totalcreditnotes = $this->invoice->getSumCreditNotesUsed(); + $totaldeposits = $this->invoice->getSumDepositsUsed(); + $resteapayer = price2num($this->invoice->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); + if ($amount != 'remain') + { + if ($amount > $resteapayer) + { + $this->db->rollback(); + throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$resteapayer.')'); + } + $resteapayer = $amount; + } + // Clean parameters amount if payment is for a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = -$resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = -$newvalue; + } else { + $resteapayer = price2num($resteapayer,'MT'); + $amounts[$id] = $resteapayer; + // Multicurrency + $newvalue = price2num($this->invoice->multicurrency_total_ttc,'MT'); + $multicurrency_amounts[$id] = $newvalue; + } + } // Creation of payment line $paiement = new Paiement($this->db); @@ -989,17 +1184,14 @@ class Invoices extends DolibarrApi $paiement->paiementcode = dol_getIdFromCode($this->db,$paiementid,'c_paiement','id','code',1); $paiement->num_paiement = $num_paiement; $paiement->note = $comment; - $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices=='yes'?1:0)); // This include closing invoices if ($paiement_id < 0) { $this->db->rollback(); throw new RestException(400, 'Payment error : '.$paiement->error); } - if (! empty($conf->banque->enabled)) { $label='(CustomerInvoicePayment)'; - if($paiement->paiementcode == 'CHQ' && empty($chqemetteur)) { throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paiement->paiementcode); } @@ -1011,7 +1203,9 @@ class Invoices extends DolibarrApi throw new RestException(400, 'Add payment to bank error : '.$paiement->error); } } + $this->db->commit(); + return $paiement_id; } diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 799fd25c5ae..a82f06ad851 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -68,6 +68,13 @@ class FactureRec extends CommonInvoice var $usenewprice=0; + var $suspended; // status + + const STATUS_NOTSUSPENDED = 0; + const STATUS_SUSPENDED = 1; + + + /** * Constructor * @@ -95,12 +102,13 @@ class FactureRec extends CommonInvoice // Clean parameters $this->titre=trim($this->titre); $this->usenewprice=empty($this->usenewprice)?0:$this->usenewprice; + if (empty($this->suspended)) $this->suspended=0; // No frequency defined then no next date to execution if (empty($this->frequency)) { $this->frequency=0; - $this->date_when=NULL; + $this->date_when=null; } @@ -147,6 +155,7 @@ class FactureRec extends CommonInvoice $sql.= ", fk_multicurrency"; $sql.= ", multicurrency_code"; $sql.= ", multicurrency_tx"; + $sql.= ", suspended"; $sql.= ") VALUES ("; $sql.= "'".$this->db->escape($this->titre)."'"; $sql.= ", ".$facsrc->socid; @@ -167,13 +176,14 @@ class FactureRec extends CommonInvoice $sql.= ", '".$this->db->escape($this->unit_frequency)."'"; $sql.= ", ".(!empty($this->date_when)?"'".$this->db->idate($this->date_when)."'":'NULL'); $sql.= ", ".(!empty($this->date_last_gen)?"'".$this->db->idate($this->date_last_gen)."'":'NULL'); - $sql.= ", ".$this->nb_gen_done; - $sql.= ", ".$this->nb_gen_max; - $sql.= ", ".$this->auto_validate; - $sql.= ", ".$this->generate_pdf; - $sql.= ", ".$facsrc->fk_multicurrency; - $sql.= ", '".$facsrc->multicurrency_code."'"; - $sql.= ", ".$facsrc->multicurrency_tx; + $sql.= ", ".$this->db->escape($this->nb_gen_done); + $sql.= ", ".$this->db->escape($this->nb_gen_max); + $sql.= ", ".$this->db->escape($this->auto_validate); + $sql.= ", ".$this->db->escape($this->generate_pdf); + $sql.= ", ".$this->db->escape($facsrc->fk_multicurrency); + $sql.= ", '".$this->db->escape($facsrc->multicurrency_code)."'"; + $sql.= ", ".$this->db->escape($facsrc->multicurrency_tx); + $sql.= ", ".$this->db->escape($this->suspended); $sql.= ")"; if ($this->db->query($sql)) @@ -304,8 +314,8 @@ class FactureRec extends CommonInvoice $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; //$sql.= ', el.fk_source'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN ('.getEntity('c_payment_term').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; $sql.= ' WHERE f.entity IN ('.getEntity('facture').')'; if ($rowid) $sql.= ' AND f.rowid='.$rowid; @@ -381,12 +391,9 @@ class FactureRec extends CommonInvoice if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; - // Retreive all extrafield for thirdparty + // Retreive all extrafield // fetch optionals attributes and labels - require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + $this->fetch_optionals(); /* * Lines @@ -442,7 +449,7 @@ class FactureRec extends CommonInvoice $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, '; $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; + $sql.= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc,'; //$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,'; @@ -468,7 +475,6 @@ class FactureRec extends CommonInvoice $line->id = $objp->rowid; $line->rowid = $objp->rowid; - $line->label = $objp->custom_label; // Label line $line->desc = $objp->description; // Description line $line->description = $objp->description; // Description line $line->product_type = $objp->product_type; // Type of line @@ -481,6 +487,8 @@ class FactureRec extends CommonInvoice $line->qty = $objp->qty; $line->subprice = $objp->subprice; + $line->label = $objp->custom_label; // @deprecated + $line->vat_src_code = $objp->vat_src_code; $line->tva_tx = $objp->tva_tx; $line->localtax1_tx = $objp->localtax1_tx; @@ -490,6 +498,8 @@ class FactureRec extends CommonInvoice $line->remise_percent = $objp->remise_percent; $line->fk_remise_except = $objp->fk_remise_except; $line->fk_product = $objp->fk_product; + $line->date_start_fill = $objp->date_start_fill; + $line->date_end_fill = $objp->date_end_fill; $line->info_bits = $objp->info_bits; $line->total_ht = $objp->total_ht; $line->total_tva = $objp->total_tva; @@ -504,7 +514,7 @@ class FactureRec extends CommonInvoice $line->price = $objp->price; $line->remise = $objp->remise; - $extralabelsline = $line->fetch_optionals($line->id,$extrafieldsline); + $extralabelsline = $line->fetch_optionals($line->id); // Multicurrency $line->fk_multicurrency = $objp->fk_multicurrency; @@ -605,15 +615,17 @@ class FactureRec extends CommonInvoice * @param string $label Label of the line * @param string $fk_unit Unit * @param double $pu_ht_devise Unit price in currency + * @param int $date_start_fill 1=Flag to fill start date when generating invoice + * @param int $date_end_fill 1=Flag to fill end date when generating invoice * @return int <0 if KO, Id of line if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0, $date_start_fill=0, $date_end_fill=0) { global $mysoc; $facid=$this->id; - dol_syslog(get_class($this)."::addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise", LOG_DEBUG); + dol_syslog(get_class($this)."::addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva,txlocaltax1=$txlocaltax1,txlocaltax2=$txlocaltax2,fk_product=$fk_product,remise_percent=$remise_percent,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise,date_start_fill=$date_start_fill,date_end_fill=$date_end_fill", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Check parameters @@ -703,6 +715,8 @@ class FactureRec extends CommonInvoice $sql.= ", total_localtax1"; $sql.= ", total_localtax2"; $sql.= ", total_ttc"; + $sql.= ", date_start_fill"; + $sql.= ", date_end_fill"; $sql.= ", info_bits"; $sql.= ", rang"; $sql.= ", special_code"; @@ -730,6 +744,8 @@ class FactureRec extends CommonInvoice $sql.= ", ".price2num($total_localtax1); $sql.= ", ".price2num($total_localtax2); $sql.= ", ".price2num($total_ttc); + $sql.= ", ".(int) $date_start_fill; + $sql.= ", ".(int) $date_end_fill; $sql.= ", ".$info_bits; $sql.= ", ".$rang; $sql.= ", ".$special_code; @@ -781,9 +797,11 @@ class FactureRec extends CommonInvoice * @param string $fk_unit Unit * @param double $pu_ht_devise Unit price in currency * @param int $notrigger disable line update trigger + * @param int $date_start_fill 1=Flag to fill start date when generating invoice + * @param int $date_end_fill 1=Flag to fill end date when generating invoice * @return int <0 if KO, Id of line if OK */ - function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise = 0, $notrigger=0) + function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise = 0, $notrigger=0, $date_start_fill=0, $date_end_fill=0) { global $mysoc; @@ -886,6 +904,8 @@ class FactureRec extends CommonInvoice $sql.= ", total_localtax1='".price2num($total_localtax1)."'"; $sql.= ", total_localtax2='".price2num($total_localtax2)."'"; $sql.= ", total_ttc='".price2num($total_ttc)."'"; + $sql.= ", date_start_fill=".((int) $date_start_fill); + $sql.= ", date_end_fill=".((int) $date_end_fill); $sql.= ", info_bits=".$info_bits; $sql.= ", rang=".$rang; $sql.= ", special_code=".$special_code; @@ -951,15 +971,20 @@ class FactureRec extends CommonInvoice * Create all recurrents invoices (for all entities if multicompany is used). * A result may also be provided into this->output. * - * WARNING: This method change context $conf->entity to be in correct context for each recurring invoice found. + * WARNING: This method change temporarly context $conf->entity to be in correct context for each recurring invoice found. * - * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) + * @param int $restictoninvoiceid 0=All qualified template invoices found. > 0 = restrict action on invoice ID + * @param int $forcevalidation 1=Force validation of invoice whatever is template auto_validate flag. + * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK) */ - function createRecurringInvoices() + function createRecurringInvoices($restictoninvoiceid=0, $forcevalidation=0) { global $conf, $langs, $db, $user; + $error=0; + $langs->load("bills"); + $langs->load('main'); $nb_create=0; @@ -967,13 +992,15 @@ class FactureRec extends CommonInvoice $tmparray=dol_getdate($now); $today = dol_mktime(23,59,59,$tmparray['mon'],$tmparray['mday'],$tmparray['year']); // Today is last second of current day - dol_syslog("createRecurringInvoices"); + dol_syslog("createRecurringInvoices restictoninvoiceid=".$restictoninvoiceid." forcevalidation=".$forcevalidation); + $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec'; $sql.= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency $sql.= " AND (date_when IS NULL OR date_when <= '".$db->idate($today)."')"; $sql.= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)'; $sql.= ' AND suspended = 0'; $sql.= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here + if ($restictoninvoiceid > 0) $sql.=' AND rowid = '.$restictoninvoiceid; $sql.= $db->order('entity', 'ASC'); //print $sql;exit; @@ -990,11 +1017,13 @@ class FactureRec extends CommonInvoice while ($i < $num) // Loop on each template invoice. If $num = 0, test is false at first pass. { - $line = $db->fetch_object($resql); + $line = $db->fetch_object($resql); $db->begin(); - $facturerec = new FactureRec($db); + $invoiceidgenerated = 0; + + $facturerec = new FactureRec($db); $facturerec->fetch($line->rowid); if ($facturerec->id > 0) @@ -1004,8 +1033,6 @@ class FactureRec extends CommonInvoice dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity); - $error=0; - $facture = new Facture($db); $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice @@ -1022,7 +1049,7 @@ class FactureRec extends CommonInvoice $this->error = $facture->error; $error++; } - if (! $error && $facturerec->auto_validate) + if (! $error && ($facturerec->auto_validate || $forcevalidation)) { $result = $facture->validate($user); if ($result <= 0) @@ -1034,6 +1061,8 @@ class FactureRec extends CommonInvoice } if (! $error && $facturerec->generate_pdf) { + // We refresh the object in order to have all necessary data (like date_lim_reglement) + $facture->fetch($facture->id); $result = $facture->generateDocument($facturerec->modelpdf, $langs); if ($result <= 0) { @@ -1092,7 +1121,21 @@ class FactureRec extends CommonInvoice global $langs; $result=''; - $label=$langs->trans("ShowInvoice").': '.$this->ref; + + $label = '' . $langs->trans("ShowInvoice") . ''; + if (! empty($this->ref)) + $label .= '
'.$langs->trans('Ref') . ': ' . $this->ref; + if (! empty($this->date_last_gen)) + $label .= '
'.$langs->trans('DateLastGeneration') . ': ' . dol_print_date($this->date_last_gen, 'dayhour'); + if ($this->frequency > 0) + { + if (! empty($this->date_when)) + { + $label .= '
'.$langs->trans('NextDateToExecution') . ': '; + $label .= (empty($this->suspended)?'':''). dol_print_date($this->date_when, 'day').(empty($this->suspended)?'':''); // No hour for this property + if (! empty($this->suspended)) $label .= ' ('.$langs->trans("Disabled").')'; + } + } $url = DOL_URL_ROOT.'/compta/facture/fiche-rec.php?facid='.$this->id; @@ -1151,49 +1194,69 @@ class FactureRec extends CommonInvoice $prefix=''; if ($recur) { - if ($status == 1) return $langs->trans('Disabled'); // credit note + if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled'); else return $langs->trans('Active'); } - else return $langs->trans("Draft"); + else + { + if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled'); + else return $langs->trans("Draft"); + } } if ($mode == 1) { $prefix='Short'; if ($recur) { - if ($status == 1) return $langs->trans('Disabled'); + if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled'); else return $langs->trans('Active'); } - else return $langs->trans("Draft"); + else + { + if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled'); + else return $langs->trans("Draft"); + } } if ($mode == 2) { if ($recur) { - if ($status == 1) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled'); + if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled'); else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active'); } - else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft'); + else + { + if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled'); + else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft'); + } } if ($mode == 3) { if ($recur) { $prefix='Short'; - if ($status == 1) return img_picto($langs->trans('Disabled'),'statut6'); + if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6'); else return img_picto($langs->trans('Active'),'statut4'); } - else return img_picto($langs->trans('Draft'),'statut0'); + else + { + if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6'); + else return img_picto($langs->trans('Draft'),'statut0'); + } } if ($mode == 4) { $prefix=''; if ($recur) { - if ($status == 1) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled'); + if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled'); else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active'); } - else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft'); + else + { + if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled'); + else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft'); + } } if ($mode == 5 || $mode == 6) { @@ -1201,10 +1264,14 @@ class FactureRec extends CommonInvoice if ($mode == 5) $prefix='Short'; if ($recur) { - if ($status == 1) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut6'); + if ($status == self::STATUS_SUSPENDED) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut6'); else return ''.$langs->trans('Active').' '.img_picto($langs->trans('Active'),'statut4'); } - else return $langs->trans('Draft').' '.img_picto($langs->trans('Active'),'statut0'); + else + { + if ($status == self::STATUS_SUSPENDED) return ''.$langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut6'); + else return $langs->trans('Draft').' '.img_picto($langs->trans('Active'),'statut0'); + } } } @@ -1471,7 +1538,7 @@ class FactureRec extends CommonInvoice } /** - * Update the auto validate invoice + * Update the auto validate flag of invoice * * @param int $validate 0 to create in draft, 1 to create and validate invoice * @return int <0 if KO, >0 if OK @@ -1575,6 +1642,10 @@ class FactureLigneRec extends CommonInvoiceLine public $element='facturedetrec'; public $table_element='facturedet_rec'; + var $date_start_fill; + var $date_end_fill; + + /** * Delete line in database * @@ -1629,7 +1700,7 @@ class FactureLigneRec extends CommonInvoiceLine { $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,'; $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; + $sql.= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; $sql.= ' l.rang, l.special_code,'; $sql.= ' l.fk_unit, l.fk_contract_line,'; $sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; @@ -1669,6 +1740,8 @@ class FactureLigneRec extends CommonInvoiceLine $this->remise_percent = $objp->remise_percent; $this->fk_remise_except = $objp->fk_remise_except; $this->fk_product = $objp->fk_product; + $this->date_start_fill = $objp->date_start_fill; + $this->date_end_fill = $objp->date_end_fill; $this->info_bits = $objp->info_bits; $this->total_ht = $objp->total_ht; $this->total_tva = $objp->total_tva; @@ -1694,22 +1767,17 @@ class FactureLigneRec extends CommonInvoiceLine /** * Update a line to invoice_rec. * + * @param User $user User + * @param int $notrigger No trigger * @return int <0 if KO, Id of line if OK */ - function update() + function update(User $user, $notrigger=0) { - global $user; + global $conf; include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - if ($fk_product) - { - $product=new Product($this->db); - $result=$product->fetch($fk_product); - $product_type=$product->type; - } - - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET "; + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET"; $sql.= " fk_facture = ".$this->fk_facture; $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null"); $sql.= ", description='".$this->db->escape($this->desc)."'"; @@ -1725,16 +1793,21 @@ class FactureLigneRec extends CommonInvoiceLine $sql.= ", product_type=".$this->product_type; $sql.= ", remise_percent='".price2num($this->remise_percent)."'"; $sql.= ", subprice='".price2num($this->subprice)."'"; - $sql.= ", total_ht='".price2num($this->total_ht)."'"; - $sql.= ", total_tva='".price2num($this->total_tva)."'"; - $sql.= ", total_localtax1='".price2num($this->total_localtax1)."'"; - $sql.= ", total_localtax2='".price2num($this->total_localtax2)."'"; - $sql.= ", total_ttc='".price2num($this->total_ttc)."'"; + $sql.= ", info_bits='".price2num($this->info_bits)."'"; + $sql.= ", date_start_fill=".(int) $this->date_start_fill; + $sql.= ", date_end_fill=".(int) $this->date_end_fill; + if (empty($this->skip_update_total)) + { + $sql.= ", total_ht=".price2num($this->total_ht); + $sql.= ", total_tva=".price2num($this->total_tva); + $sql.= ", total_localtax1=".price2num($this->total_localtax1); + $sql.= ", total_localtax2=".price2num($this->total_localtax2); + $sql.= ", total_ttc=".price2num($this->total_ttc); + } $sql.= ", rang=".$this->rang; $sql.= ", special_code=".$this->special_code; $sql.= ", fk_unit=".($this->fk_unit ?"'".$this->db->escape($this->fk_unit )."'":"null"); $sql.= ", fk_contract_line=".($this->fk_contract_line?$this->fk_contract_line:"null"); - $sql.= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::updateline", LOG_DEBUG); @@ -1750,10 +1823,10 @@ class FactureLigneRec extends CommonInvoiceLine } } - if (! $notrigger) + if (! $error && ! $notrigger) { // Call trigger - $result=$this->call_trigger('LINEBILL_REC_UPDATE',$user); + $result=$this->call_trigger('LINEBILL_REC_UPDATE', $user); if ($result < 0) { $this->db->rollback(); @@ -1766,7 +1839,7 @@ class FactureLigneRec extends CommonInvoiceLine } else { - $this->error=$this->db->error(); + $this->error=$this->db->lasterror(); $this->db->rollback(); return -2; } diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index bc7a14c0c45..2329b1caeb0 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -13,8 +13,9 @@ * Copyright (C) 2012 Cédric Salvador * Copyright (C) 2012-2014 Raphaël Doursenaud * Copyright (C) 2013 Cedric Gross - * Copyright (C) 2013 Florian Henry - * Copyright (C) 2016 Ferran Marcet + * Copyright (C) 2013 Florian Henry + * Copyright (C) 2016 Ferran Marcet + * Copyright (C) 2018 Alexandre Spangaro * Copyright (C) 2018 Nicolas ZABOURI * * This program is free software; you can redistribute it and/or modify @@ -44,6 +45,9 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php'; require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; +if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; + /** * Class to manage invoices */ @@ -141,7 +145,7 @@ class Facture extends CommonInvoice public $situation_counter; /** - * @var bool Final situation flag + * @var int Final situation flag */ public $situation_final; @@ -240,7 +244,7 @@ class Facture extends CommonInvoice * @param int $forceduedate 1=Do not recalculate due date from payment condition but force it with value * @return int <0 if KO, >0 if OK */ - function create($user,$notrigger=0,$forceduedate=0) + function create(User $user, $notrigger=0, $forceduedate=0) { global $langs,$conf,$mysoc,$hookmanager; $error=0; @@ -266,13 +270,13 @@ class Facture extends CommonInvoice $this->multicurrency_tx = 1; } - dol_syslog(get_class($this)."::create user=".$user->id); + dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date); // Check parameters - if (empty($this->date) || empty($user->id)) + if (empty($this->date)) { - $this->error="ErrorBadParameter"; - dol_syslog(get_class($this)."::create Try to create an invoice with an empty parameter (user, date, ...)", LOG_ERR); + $this->error="Try to create an invoice with an empty parameter (date)"; + dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -3; } $soc = new Societe($this->db); @@ -288,6 +292,10 @@ class Facture extends CommonInvoice $this->db->begin(); + $originaldatewhen=null; + $nextdatewhen=null; + $previousdaynextdatewhen=null; + // Create invoice from a template invoice if ($this->fac_rec > 0) { @@ -298,19 +306,22 @@ class Facture extends CommonInvoice $result=$_facrec->fetch($this->fac_rec); $result=$_facrec->fetchObjectLinked(); // This load $_facrec->linkedObjectsIds + // Define some dates $originaldatewhen = $_facrec->date_when; + $nextdatewhen=dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency); + $previousdaynextdatewhen=dol_time_plus_duree($nextdatewhen, -1, 'd'); $this->socid = $_facrec->socid; // Invoice created on same thirdparty than template $this->entity = $_facrec->entity; // Invoice created in same entity than template // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI - $this->fk_project = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project; + $this->fk_project = GETPOST('projectid','int') > 0 ? ((int) GETPOST('projectid','int')) : $_facrec->fk_project; $this->note_public = GETPOST('note_public','none') ? GETPOST('note_public','none') : $_facrec->note_public; $this->note_private = GETPOST('note_private','none') ? GETPOST('note_private','none') : $_facrec->note_private; - $this->modelpdf = GETPOST('model') ? GETPOST('model') : $_facrec->modelpdf; - $this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id; - $this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id; - $this->fk_account = GETPOST('fk_account') > 0 ? GETPOST('fk_account') : $_facrec->fk_account; + $this->modelpdf = GETPOST('model','alpha') ? GETPOST('model','apha') : $_facrec->modelpdf; + $this->cond_reglement_id = GETPOST('cond_reglement_id','int') > 0 ? ((int) GETPOST('cond_reglement_id','int')) : $_facrec->cond_reglement_id; + $this->mode_reglement_id = GETPOST('mode_reglement_id','int') > 0 ? ((int) GETPOST('mode_reglement_id','int')) : $_facrec->mode_reglement_id; + $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account; // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result $this->total_ht = $_facrec->total_ht; @@ -375,7 +386,8 @@ class Facture extends CommonInvoice $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y'); // Only for tempalte invoice $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour'); - $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date(dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency), 'dayhour'); + $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($nextdatewhen, 'dayhour'); + $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($previousdaynextdatewhen, 'dayhour'); //var_dump($substitutionarray);exit; @@ -495,6 +507,7 @@ class Facture extends CommonInvoice } } + // Propagate contacts if (! $error && $this->id && ! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && ! empty($this->origin) && ! empty($this->origin_id)) // Get contact from origin object { $originforcontact = $this->origin; @@ -532,11 +545,10 @@ class Facture extends CommonInvoice else dol_print_error($resqlcontact); } - /* - * Insert lines of invoices into database + * Insert lines of invoices, if not from template invoice, into database */ - if (count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode) + if (! $error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode) { $fk_parent_line = 0; @@ -546,9 +558,18 @@ class Facture extends CommonInvoice $newinvoiceline=$this->lines[$i]; $newinvoiceline->fk_facture=$this->id; - // TODO This seems not used. Here we put origin 'facture' but after, we put an id of object ! - $newinvoiceline->origin = $this->element; - $newinvoiceline->origin_id = $this->lines[$i]->id; + $newinvoiceline->origin = $this->lines[$i]->element; + $newinvoiceline->origin_id = $this->lines[$i]->id; + + // Auto set date of service ? + if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only + { + $newinvoiceline->date_start = $originaldatewhen; + } + if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) // $previousdaynextdatewhen is defined when generating from recurring invoice only + { + $newinvoiceline->date_end = $previousdaynextdatewhen; + } if ($result >= 0) { @@ -582,7 +603,7 @@ class Facture extends CommonInvoice } } } - else // If this->lines is an array of invoice line arrays + elseif (! $error && empty($this->fac_rec)) // If this->lines is an array of invoice line arrays { $fk_parent_line = 0; @@ -593,7 +614,7 @@ class Facture extends CommonInvoice $line = $this->lines[$i]; // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array - //if (! is_object($line)) $line=json_decode(json_encode($line), FALSE); // convert recursively array into object. + //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. if (! is_object($line)) $line = (object) $line; if ($result >= 0) @@ -690,7 +711,9 @@ class Facture extends CommonInvoice $localtax2_tx, $_facrec->lines[$i]->fk_product, $_facrec->lines[$i]->remise_percent, - '','',0, + ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen)?$originaldatewhen:'', + ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen)?$previousdaynextdatewhen:'', + 0, $tva_npr, '', 'HT', @@ -728,35 +751,20 @@ class Facture extends CommonInvoice { $action='create'; - // Actions on extra fields (by external module or standard code) - // TODO le hook fait double emploi avec le trigger !! - /* - $hookmanager->initHooks(array('invoicedao')); - $parameters=array('invoiceid'=>$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 - {*/ + // Actions on extra fields if (! $error) { $result=$this->insertExtraFields(); if ($result < 0) $error++; } - /*} - } - else if ($reshook < 0) $error++;*/ - if (! $error) - { - if (! $notrigger) - { - // Call trigger - $result=$this->call_trigger('BILL_CREATE',$user); - if ($result < 0) $error++; - // End call triggers - } - } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BILL_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + } if (! $error) { @@ -806,14 +814,17 @@ class Facture extends CommonInvoice // Charge facture source $facture=new Facture($this->db); - $this->fetch_optionals(); - if(!empty($this->array_options)){ - $facture->array_options = $this->array_options; - } + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); - foreach($this->lines as &$line){ + if(!empty($this->array_options)){ + $facture->array_options = $this->array_options; + } + + foreach($this->lines as &$line){ $line->fetch_optionals();//fetch extrafields - } + } $facture->fk_facture_source = $this->fk_facture_source; $facture->type = $this->type; @@ -864,7 +875,7 @@ class Facture extends CommonInvoice } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) { - $this->fetchObjectLinked('', '', $object->id, 'facture'); + $this->fetchObjectLinked('', '', $facture->id, 'facture'); foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) { @@ -974,11 +985,6 @@ class Facture extends CommonInvoice $reshook=$hookmanager->executeHooks('createFrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) $error++; } - - // Call trigger - $result=$this->call_trigger('BILL_CLONE',$user); - if ($result < 0) $error++; - // End call triggers } unset($this->context['createfromclone']); @@ -1049,7 +1055,7 @@ class Facture extends CommonInvoice $line->pa_ht = $marginInfos[0]; // get extrafields from original line - $object->lines[$i]->fetch_optionals($object->lines[$i]->rowid); + $object->lines[$i]->fetch_optionals(); foreach($object->lines[$i]->array_options as $options_key => $value) $line->array_options[$options_key] = $value; @@ -1146,7 +1152,7 @@ class Facture extends CommonInvoice { global $langs, $conf, $user, $form; - if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips $result=''; @@ -1265,11 +1271,13 @@ class Facture extends CommonInvoice $sql.= ', f.fk_incoterms, f.location_incoterms'; $sql.= ", i.libelle as libelle_incoterms"; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid AND c.entity IN (' . getEntity('c_payment_term').')'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid'; - $sql.= ' WHERE f.entity IN ('.getEntity('facture').')'; - if ($rowid) $sql.= " AND f.rowid=".$rowid; + + if ($rowid) $sql.= " WHERE f.rowid=".$rowid; + else $sql.= ' WHERE f.entity IN ('.getEntity('facture').')'; // Dont't use entity if you use rowid + if ($ref) $sql.= " AND f.facnumber='".$this->db->escape($ref)."'"; if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'"; @@ -1344,23 +1352,20 @@ class Facture extends CommonInvoice $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if ($this->type == self::TYPE_SITUATION && $fetch_situation) + if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) { $this->fetchPreviousNextSituationInvoice(); } if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; - // Retrieve all extrafield for invoice + // Retreive all extrafield // fetch optionals attributes and labels - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + $this->fetch_optionals(); /* * Lines - */ + */ $this->lines = array(); @@ -1469,6 +1474,9 @@ class Facture extends CommonInvoice $line->fk_prev_id = $objp->fk_prev_id; $line->fk_unit = $objp->fk_unit; + // Accountancy + $line->fk_accounting_account = $objp->fk_code_ventilation; + // Multicurrency $line->fk_multicurrency = $objp->fk_multicurrency; $line->multicurrency_code = $objp->multicurrency_code; @@ -1516,8 +1524,16 @@ class Facture extends CommonInvoice $invoice = new Facture($this->db); if ($invoice->fetch($objp->rowid) > 0) { - if ($objp->situation_counter < $this->situation_counter) $this->tab_previous_situation_invoice[] = $invoice; - else $this->tab_next_situation_invoice[] = $invoice; + if ($objp->situation_counter < $this->situation_counter + || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes + ) + { + $this->tab_previous_situation_invoice[] = $invoice; + } + else + { + $this->tab_next_situation_invoice[] = $invoice; + } } } } @@ -1531,8 +1547,10 @@ class Facture extends CommonInvoice * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=null, $notrigger=0) + function update(User $user, $notrigger=0) { + global $conf; + $error=0; // Clean parameters @@ -1547,36 +1565,24 @@ class Facture extends CommonInvoice if (isset($this->note_public)) $this->note_public=trim($this->note_public); if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf); if (isset($this->import_key)) $this->import_key=trim($this->import_key); - if (empty($this->situation_cycle_ref)) { - $this->situation_cycle_ref = 'null'; - } - - if (empty($this->situation_counter)) { - $this->situation_counter = 'null'; - } - - if (empty($this->situation_final)) { - $this->situation_final = '0'; - } // Check parameters // Put here code to add control on parameters values // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET"; - $sql.= " facnumber=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").","; - $sql.= " type=".(isset($this->type)?$this->type:"null").","; + $sql.= " type=".(isset($this->type)?$this->db->escape($this->type):"null").","; $sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").","; $sql.= " increment=".(isset($this->increment)?"'".$this->db->escape($this->increment)."'":"null").","; - $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").","; + $sql.= " fk_soc=".(isset($this->socid)?$this->db->escape($this->socid):"null").","; $sql.= " datec=".(strval($this->date_creation)!='' ? "'".$this->db->idate($this->date_creation)."'" : 'null').","; $sql.= " datef=".(strval($this->date)!='' ? "'".$this->db->idate($this->date)."'" : 'null').","; $sql.= " date_pointoftax=".(strval($this->date_pointoftax)!='' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').","; $sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').","; - $sql.= " paye=".(isset($this->paye)?$this->paye:"null").","; - $sql.= " remise_percent=".(isset($this->remise_percent)?$this->remise_percent:"null").","; - $sql.= " remise_absolue=".(isset($this->remise_absolue)?$this->remise_absolue:"null").","; + $sql.= " paye=".(isset($this->paye)?$this->db->escape($this->paye):"null").","; + $sql.= " remise_percent=".(isset($this->remise_percent)?$this->db->escape($this->remise_percent):"null").","; + $sql.= " remise_absolue=".(isset($this->remise_absolue)?$this->db->escape($this->remise_absolue):"null").","; $sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").","; $sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").","; $sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").","; @@ -1584,23 +1590,22 @@ class Facture extends CommonInvoice $sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").","; $sql.= " total=".(isset($this->total_ht)?$this->total_ht:"null").","; $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").","; - $sql.= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '')?$this->revenuestamp:"null").","; - $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").","; - $sql.= " fk_user_author=".(isset($this->user_author)?$this->user_author:"null").","; - $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").","; - $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").","; - $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").","; - $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").","; - $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").","; + $sql.= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '')?$this->db->escape($this->revenuestamp):"null").","; + $sql.= " fk_statut=".(isset($this->statut)?$this->db->escape($this->statut):"null").","; + $sql.= " fk_user_author=".(isset($this->user_author)?$this->db->escape($this->user_author):"null").","; + $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->db->escape($this->fk_user_valid):"null").","; + $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->db->escape($this->fk_facture_source):"null").","; + $sql.= " fk_projet=".(isset($this->fk_project)?$this->db->escape($this->fk_project):"null").","; + $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->db->escape($this->cond_reglement_id):"null").","; + $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->db->escape($this->mode_reglement_id):"null").","; $sql.= " date_lim_reglement=".(strval($this->date_lim_reglement)!='' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').","; $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").","; $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").","; - $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); - $sql.= ", situation_cycle_ref=".$this->situation_cycle_ref; - $sql.= ", situation_counter=".$this->situation_counter; - $sql.= ", situation_final=".$this->situation_final; - + $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null").","; + $sql.= " situation_cycle_ref=".(empty($this->situation_cycle_ref)?"null":$this->db->escape($this->situation_cycle_ref)).","; + $sql.= " situation_counter=".(empty($this->situation_counter)?"null":$this->db->escape($this->situation_counter)).","; + $sql.= " situation_final=".(empty($this->situation_counter)?"0":$this->db->escape($this->situation_counter)); $sql.= " WHERE rowid=".$this->id; $this->db->begin(); @@ -1611,17 +1616,23 @@ class Facture extends CommonInvoice $error++; $this->errors[]="Error ".$this->db->lasterror(); } - if (! $error) + if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) { - if (! $notrigger) + $result=$this->insertExtraFields(); + if ($result < 0) { - // Call trigger - $result=$this->call_trigger('BILL_MODIFY',$user); - if ($result < 0) $error++; - // End call triggers + $error++; } } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BILL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + } + // Commit or rollback if ($error) { @@ -1822,9 +1833,9 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".$this->thirdparty->name, LOG_DEBUG); // Test to avoid invoice deletion (allowed if draft) - $test = $this->is_erasable(); + $result = $this->is_erasable(); - if ($test <= 0) return 0; + if ($result <= 0) return 0; $error=0; @@ -1992,6 +2003,7 @@ class Facture extends CommonInvoice $this->db->begin(); dol_syslog(get_class($this)."::set_paid rowid=".$this->id, LOG_DEBUG); + $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET'; $sql.= ' fk_statut='.self::STATUS_CLOSED; if (! $close_code) $sql.= ', paye=1'; @@ -1999,7 +2011,6 @@ class Facture extends CommonInvoice if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'"; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_paid", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -2254,7 +2265,7 @@ class Facture extends CommonInvoice // Validate $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture'; - $sql.= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; + $sql.= " SET facnumber='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".($user->id > 0 ? $user->id : "null").", date_valid = '".$this->db->idate($now)."'"; if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date { $sql.= ", datef='".$this->db->idate($this->date)."'"; @@ -2371,7 +2382,7 @@ class Facture extends CommonInvoice if (!empty($conf->global->INVOICE_USE_SITUATION)) { - $final = True; + $final = true; $nboflines = count($this->lines); while (($i < $nboflines) && $final) { $final = ($this->lines[$i]->situation_percent == 100); @@ -2545,8 +2556,8 @@ class Facture extends CommonInvoice * @param double $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside) * @param int $fk_product Id of predefined product/service * @param double $remise_percent Percent of discount on line - * @param int $date_start Date start of service - * @param int $date_end Date end of service + * @param int $date_start Date start of service + * @param int $date_end Date end of service * @param int $ventil Code of dispatching into accountancy * @param int $info_bits Bits de type de lignes * @param int $fk_remise_except Id discount used @@ -2568,11 +2579,12 @@ class Facture extends CommonInvoice * @param double $pu_ht_devise Unit price in currency * @return int <0 if KO, Id of line if OK */ - function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id='', $fk_unit = null, $pu_ht_devise = 0) + function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=self::TYPE_STANDARD, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0, $fk_fournprice=null, $pa_ht=0, $label='', $array_options=0, $situation_percent=100, $fk_prev_id=0, $fk_unit = null, $pu_ht_devise = 0) { // Deprecation warning if ($label) { dol_syslog(__METHOD__ . ": using line label is deprecated", LOG_WARNING); + //var_dump(debug_backtrace(false));exit; } global $mysoc, $conf, $langs; @@ -2739,14 +2751,15 @@ class Facture extends CommonInvoice // Mise a jour informations denormalisees au niveau de la facture meme $result=$this->update_price(1,'auto',0,$mysoc); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode. + if ($result > 0) { $this->db->commit(); - return $this->line->rowid; + return $this->line->id; } else { - $this->error=$this->db->error(); + $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } @@ -3075,7 +3088,7 @@ class Facture extends CommonInvoice // For triggers $result = $line->fetch($rowid); - if (! ($result > 0)) dol_print_error($db, $line->error, $line->errors); + if (! ($result > 0)) dol_print_error($this->db, $line->error, $line->errors); if ($line->delete($user) > 0) { @@ -3231,7 +3244,6 @@ class Facture extends CommonInvoice } } - /** * Return next reference of customer invoice not already used (or last reference) * according to numbering module defined into constant FACTURE_ADDON @@ -3502,6 +3514,7 @@ class Facture extends CommonInvoice $return = array(); + $sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut, f.type, f.paye, pf.fk_paiement"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture"; @@ -3513,6 +3526,23 @@ class Facture extends CommonInvoice // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement $sql.= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement $sql.= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir + + if($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE){ + // Select the last situation invoice + $sqlSit = 'SELECT MAX(fs.rowid)'; + $sqlSit.= " FROM ".MAIN_DB_PREFIX."facture as fs"; + $sqlSit.= " WHERE fs.entity = ".$conf->entity; + $sqlSit.= " AND fs.type = ".self::TYPE_SITUATION; + $sqlSit.= " AND fs.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")"; + $sqlSit.= " GROUP BY fs.situation_cycle_ref"; + $sqlSit.= " ORDER BY fs.situation_counter"; + $sql.= " AND ( f.type != ".self::TYPE_SITUATION . " OR f.rowid IN (".$sqlSit.") )"; // Type non 5 si facture non avoir + } + else + { + $sql.= " AND f.type != ".self::TYPE_SITUATION ; // Type non 5 si facture non avoir + } + if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid; $sql.= " ORDER BY f.facnumber"; @@ -4395,7 +4425,7 @@ class FactureLigne extends CommonInvoiceLine if (empty($this->subprice)) $this->subprice=0; if (empty($this->special_code)) $this->special_code=0; if (empty($this->fk_parent_line)) $this->fk_parent_line=0; - if (empty($this->fk_prev_id)) $this->fk_prev_id = 'null'; + if (empty($this->fk_prev_id)) $this->fk_prev_id = 0; if (! isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100; if (empty($this->pa_ht)) $this->pa_ht=0; @@ -4478,7 +4508,7 @@ class FactureLigne extends CommonInvoiceLine $sql.= " ".price2num($this->total_localtax1).","; $sql.= " ".price2num($this->total_localtax2); $sql.= ", " . $this->situation_percent; - $sql.= ", " . $this->fk_prev_id; + $sql.= ", " . (!empty($this->fk_prev_id)?$this->fk_prev_id:"null"); $sql.= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit); $sql.= ", ".$user->id; $sql.= ", ".$user->id; @@ -4494,11 +4524,11 @@ class FactureLigne extends CommonInvoiceLine $resql=$this->db->query($sql); if ($resql) { - $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet'); + $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet'); + $this->rowid=$this->id; // For backward compatibility if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used { - $this->id=$this->rowid; $result=$this->insertExtraFields(); if ($result < 0) { @@ -4570,12 +4600,12 @@ class FactureLigne extends CommonInvoiceLine } $this->db->commit(); - return $this->rowid; + return $this->id; } else { - $this->error=$this->db->error(); + $this->error=$this->db->lasterror(); $this->db->rollback(); return -2; } @@ -4658,11 +4688,11 @@ class FactureLigne extends CommonInvoiceLine $sql.= ", special_code='".$this->db->escape($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)."'"; @@ -4694,7 +4724,7 @@ class FactureLigne extends CommonInvoiceLine } } - if (! $notrigger) + if (! $error && ! $notrigger) { // Call trigger $result=$this->call_trigger('LINEBILL_UPDATE',$user); @@ -4755,6 +4785,7 @@ class FactureLigne extends CommonInvoiceLine /** * Mise a jour en base des champs total_xxx de ligne de facture + * TODO What is goal of this method ? * * @return int <0 if KO, >0 if OK */ diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index bc13b0d5876..3697a61672b 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -57,7 +57,6 @@ class PaymentTerm // extends CommonObject function __construct($db) { $this->db = $db; - return 1; } @@ -90,7 +89,6 @@ class PaymentTerm // extends CommonObject // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_payment_term("; - $sql.= "rowid,"; $sql.= "entity,"; $sql.= "code,"; $sql.= "sortorder,"; @@ -101,7 +99,6 @@ class PaymentTerm // extends CommonObject $sql.= "nbjour,"; $sql.= "decalage"; $sql.= ") VALUES ("; - $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").","; $sql.= " ".(! isset($this->entity)?getEntity('c_payment_term'):"'".$this->db->escape($this->entity)."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->sortorder)?'NULL':"'".$this->db->escape($this->sortorder)."'").","; @@ -181,7 +178,6 @@ class PaymentTerm // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.rowid = ".$id; - $sql.= " AND t.entity = " . getEntity('c_payment_term'); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); @@ -221,36 +217,36 @@ class PaymentTerm // extends CommonObject * * @return int <0 if KO, >0 if OK */ - function getDefaultId() - { - global $langs; + function getDefaultId() + { + global $langs; - $ret=0; + $ret=0; - $sql = "SELECT"; + $sql = "SELECT"; $sql.= " t.rowid"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql.= " WHERE t.code = 'RECEP'"; - $sql.= " AND t.entity = " . getEntity('c_payment_term'); + $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql.= " WHERE t.code = 'RECEP'"; + $sql.= " AND t.entity IN (".getEntity('c_payment_term').")"; - dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); - if ($obj) $ret=$obj->rowid; - } - $this->db->free($resql); - return $ret; - } - else - { - $this->error="Error ".$this->db->lasterror(); - return -1; - } - } + dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + if ($obj) $ret=$obj->rowid; + } + $this->db->free($resql); + return $ret; + } + else + { + $this->error="Error ".$this->db->lasterror(); + return -1; + } + } /** @@ -293,7 +289,6 @@ class PaymentTerm // extends CommonObject $sql.= " nbjour=".(isset($this->nbjour)?$this->nbjour:"null").","; $sql.= " decalage=".(isset($this->decalage)?$this->decalage:"null").""; $sql.= " WHERE rowid = " . $this->id; - $sql.= " AND entity = " . getEntity('c_payment_term'); $this->db->begin(); @@ -336,11 +331,11 @@ class PaymentTerm // extends CommonObject } - /** + /** * Delete object in database * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ function delete($user, $notrigger=0) @@ -350,7 +345,6 @@ class PaymentTerm // extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_payment_term"; $sql.= " WHERE rowid = " . $this->id; - $sql.= " AND t.entity = " . getEntity('c_payment_term'); $this->db->begin(); diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index 2c95366f9a9..af872a174ca 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -35,8 +35,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load("bills"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'companies')); $id = (GETPOST('id')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility $ref = GETPOST('ref','alpha'); @@ -155,7 +155,7 @@ if ($id > 0 || ! empty($ref)) $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); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index 8b76f9b167f..828c77f1178 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -38,11 +38,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load('propal'); -$langs->load('compta'); -$langs->load('other'); -$langs->load("bills"); -$langs->load('companies'); +// Load translation files required by the page +$langs->loadLangs(array('propal', 'compta', 'other', 'bills', 'companies')); $id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility @@ -125,7 +122,7 @@ if ($id > 0 || ! empty($ref)) $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); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { @@ -171,7 +168,7 @@ if ($id > 0 || ! empty($ref)) print ''; print ''; - print ''; + print ''; print "
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
\n"; print "
\n"; diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index 4519fd24f6a..fb70da42665 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -43,7 +43,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -$langs->loadLangs(array('bills','compta','admin','other','products')); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'compta', 'admin', 'other', 'products')); $action = GETPOST('action','alpha'); $massaction = GETPOST('massaction','alpha'); @@ -63,24 +64,10 @@ if ($action == "create" || $action == "add") $objecttype = ''; $result = restrictedArea($user, 'facture', $id, $objecttype); $projectid = GETPOST('projectid','int'); -$search_ref=GETPOST('search_ref'); -$search_societe=GETPOST('search_societe'); -$search_montant_ht=GETPOST('search_montant_ht'); -$search_montant_vat=GETPOST('search_montant_vat'); -$search_montant_ttc=GETPOST('search_montant_ttc'); -$search_payment_mode=GETPOST('search_payment_mode'); -$search_payment_term=GETPOST('search_payment_term'); -$day=GETPOST('day'); -$year=GETPOST('year'); -$month=GETPOST('month'); -$day_date_when=GETPOST('day_date_when'); $year_date_when=GETPOST('year_date_when'); $month_date_when=GETPOST('month_date_when'); -$search_recurring=GETPOST('search_recurring','int'); -$search_frequency=GETPOST('search_frequency','alpha'); -$search_unit_frequency=GETPOST('search_unit_frequency','alpha'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -141,28 +128,6 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - // Do we click on purge search criteria ? - if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All test are required to be compatible with all browsers - { - $search_ref=''; - $search_societe=''; - $search_montant_ht=''; - $search_montant_vat=''; - $search_montant_ttc=''; - $search_montant_mode=''; - $search_montant_term=''; - $day=''; - $year=''; - $month=''; - $day_date_when=''; - $year_date_when=''; - $month_date_when=''; - $search_recurring=''; - $search_frequency=''; - $search_unit_frequency=''; - $search_array_options=array(); - } - // Mass actions /*$objectclass='MyObject'; $objectlabel='MyObject'; @@ -443,13 +408,16 @@ if (empty($reshook)) } else if ($action == 'update_extras') { + $object->oldcopy = dol_clone($object); + // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none')); if ($ret < 0) $error++; - if (! $error) { - $result = $object->insertExtraFields(); + if (! $error) + { + $result = $object->insertExtraFields('BILLREC_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -681,6 +649,9 @@ if (empty($reshook)) $fk_unit= GETPOST('units', 'alpha'); } + $date_start_fill = GETPOST('date_start_fill','int'); + $date_end_fill = GETPOST('date_end_fill','int'); + // 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 @@ -701,7 +672,7 @@ if (empty($reshook)) else { // Insert line - $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit); + $result = $object->addline($desc, $pu_ht, $qty, $tva_tx,$localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $info_bits, '', $pu_ttc, $type, - 1, $special_code, $label, $fk_unit, 0, $date_start_fill, $date_end_fill); if ($result > 0) { @@ -757,6 +728,9 @@ if (empty($reshook)) unset($_POST['date_endmonth']); unset($_POST['date_endyear']); + unset($_POST['date_start_fill']); + unset($_POST['date_end_fill']); + unset($_POST['situations']); unset($_POST['progress']); } @@ -878,6 +852,9 @@ if (empty($reshook)) $error ++; } + $date_start_fill = GETPOST('date_start_fill','int'); + $date_end_fill = GETPOST('date_end_fill','int'); + // Update line if (! $error) { @@ -900,7 +877,10 @@ if (empty($reshook)) $special_code, $label, GETPOST('units'), - $pu_ht_devise + $pu_ht_devise, + 0, + $date_start_fill, + $date_end_fill ); if ($result >= 0) @@ -1184,7 +1164,7 @@ if ($action == 'create') $disableedit=1; $disablemove=1; $disableremove=1; - $ret = $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice + $object->printObjectLines('', $mysoc, $object->thirdparty, $lineid, 0); // No date selector for template invoice } print "\n"; @@ -1533,7 +1513,7 @@ else //var_dump(dol_print_date($object->date_when+60, 'dayhour').' - '.dol_print_date($now, 'dayhour')); if (! $object->isMaxNbGenReached()) { - if ($action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late")); + if (! $object->suspended && $action != 'editdate_when' && $object->frequency > 0 && $object->date_when && $object->date_when < $now) print img_warning($langs->trans("Late")); } else { diff --git a/htdocs/compta/facture/info.php b/htdocs/compta/facture/info.php index 00272fee9b3..8964b85203b 100644 --- a/htdocs/compta/facture/info.php +++ b/htdocs/compta/facture/info.php @@ -32,8 +32,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load("companies"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'bills')); $id = GETPOST("facid","int"); $ref=GETPOST("ref",'alpha'); @@ -69,7 +69,7 @@ $morehtmlref='
'; $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); +$morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index 306106d4889..b7b985dd73c 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -42,10 +42,8 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -$langs->load('bills'); -$langs->load('compta'); -$langs->load('admin'); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'compta', 'admin', 'other')); $action = GETPOST('action','alpha'); $massaction = GETPOST('massaction','alpha'); @@ -83,7 +81,7 @@ $search_frequency=GETPOST('search_frequency','alpha'); $search_unit_frequency=GETPOST('search_unit_frequency','alpha'); $search_status=GETPOST('search_status','int'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -273,14 +271,20 @@ else if ($search_year_date_when > 0) $sql.= " AND f.date_when BETWEEN '".$db->idate(dol_get_first_day($search_year_date_when,1,false))."' AND '".$db->idate(dol_get_last_day($search_year_date_when,12,false))."'"; } +$sql.= $db->order($sortfield, $sortorder); + $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } -$sql.= $db->order($sortfield, $sortorder); $sql.= $db->plimit($limit+1,$offset); $resql = $db->query($sql); @@ -419,19 +423,19 @@ if ($resql) // Date invoice if (! empty($arrayfields['f.date_last_gen']['checked'])) { - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5); + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5, 0, 0, '', 'witdhauto valignmiddle'); print ''; } // Date next generation if (! empty($arrayfields['f.date_when']['checked'])) { - print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_year_date_when?$search_year_date_when:-1,'search_year_date_when',1, 20, 5); + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year_date_when?$search_year_date_when:-1,'search_year_date_when',1, 20, 5, 0, 0, '', 'witdhauto valignmiddle'); print ''; } // Extra fields @@ -599,15 +603,17 @@ if ($resql) if (! empty($arrayfields['f.date_when']['checked'])) { print ''; + print '
'; print ($objp->frequency ? ($invoicerectmp->isMaxNbGenReached()?'':'').dol_print_date($db->jdate($objp->date_when),'day').($invoicerectmp->isMaxNbGenReached()?'':'') : ''.$langs->trans('NA').''); if (! $invoicerectmp->isMaxNbGenReached()) { - if ($objp->frequency > 0 && $db->jdate($objp->date_when) && $db->jdate($objp->date_when) < $now) print img_warning($langs->trans("Late")); + if (! $objp->suspended && $objp->frequency > 0 && $db->jdate($objp->date_when) && $db->jdate($objp->date_when) < $now) print img_warning($langs->trans("Late")); } else { print img_info($langs->trans("MaxNumberOfGenerationReached")); } + print '
'; print ''; if (! $i) $totalarray['nbfield']++; } @@ -647,7 +653,7 @@ if ($resql) } else { - print $langs->trans("DateIsNotEnough"); + print $form->textwithpicto('', $langs->trans("DateIsNotEnough")); } } else diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index b813ed7c6da..6c39c0cd0a9 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -49,10 +49,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - -$langs->load('bills'); -$langs->load('companies'); -$langs->load('products'); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'companies', 'products')); $sall=trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); $projectid=(GETPOST('projectid')?GETPOST('projectid','int'):0); @@ -66,6 +64,7 @@ $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'invoicelist'; $lineid=GETPOST('lineid','int'); $userid=GETPOST('userid','int'); @@ -80,7 +79,7 @@ $search_montant_vat=GETPOST('search_montant_vat','alpha'); $search_montant_localtax1=GETPOST('search_montant_localtax1','alpha'); $search_montant_localtax2=GETPOST('search_montant_localtax2','alpha'); $search_montant_ttc=GETPOST('search_montant_ttc','alpha'); -$search_status=GETPOST('search_status','int'); +$search_status=GETPOST('search_status','intcomma'); $search_paymentmode=GETPOST('search_paymentmode','int'); $search_town=GETPOST('search_town','alpha'); $search_zip=GETPOST('search_zip','alpha'); @@ -95,30 +94,28 @@ $search_year = GETPOST('search_year','int'); $search_day_lim = GETPOST('search_day_lim','int'); $search_month_lim = GETPOST('search_month_lim','int'); $search_year_lim = GETPOST('search_year_lim','int'); +$search_categ_cus=trim(GETPOST("search_categ_cus",'int')); $search_btn=GETPOST('button_search','alpha'); $search_remove_btn=GETPOST('button_removefilter','alpha'); -$option = GETPOST('option'); +$option = GETPOST('search_option'); if ($option == 'late') { $search_status = '1'; } $filtre = GETPOST('filtre','alpha'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; -if (! $sortorder && ! empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == 1) $sortorder=$conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER; +if (! $sortorder && ! empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == '1') $sortorder=$conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER; if (! $sortorder) $sortorder='DESC'; if (! $sortfield) $sortfield='f.datef'; $pageprev = $page - 1; $pagenext = $page + 1; -// Initialize technical object to manage context to save list fields -$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'invoicelist'; - // Security check $fieldid = (! empty($ref)?'facnumber':'rowid'); if (! empty($user->societe_id)) $socid=$user->societe_id; @@ -131,6 +128,7 @@ $object=new Facture($db); $now=dol_now(); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$object = new Facture($db); $hookmanager->initHooks(array('invoicelist')); $extrafields = new ExtraFields($db); @@ -231,6 +229,8 @@ if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter','a $search_month_lim=''; $toselect=''; $search_array_options=array(); + $search_categ_cus=0; + } if (empty($reshook)) @@ -278,7 +278,7 @@ if ($massaction == 'withdrawrequest') $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("AmountMustBePositive"), $objecttmp->errors, 'errors'); } - if(!($objecttmp->statut > Facture::STATUS_DRAFT)){ + if (!($objecttmp->statut > Facture::STATUS_DRAFT)){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("Draft"), $objecttmp->errors, 'errors'); } @@ -300,11 +300,11 @@ if ($massaction == 'withdrawrequest') $numprlv = $db->num_rows($result_sql); } - if($numprlv>0){ + if ($numprlv>0){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'errors'); } - if(!empty($objecttmp->mode_reglement_id ) && $objecttmp->mode_reglement_id != 3){ + if (!empty($objecttmp->mode_reglement_code ) && $objecttmp->mode_reglement_code != 'PRE'){ $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); } @@ -368,10 +368,12 @@ $sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.c $sql.= " typent.code as typent_code,"; $sql.= " state.code_departement as state_code, state.nom as state_name,"; $sql.= " country.code as country_code,"; -$sql.= " p.rowid as project_id, p.ref as project_ref"; +$sql.= " p.rowid as project_id, p.ref as project_ref, p.title as project_label"; // We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0) // TODO Better solution to be able to sort on already payed or remain to pay is to store amount_payed in a denormalized field. if (! $sall) $sql.= ', SUM(pf.amount) as dynamount_payed'; +if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; + // 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 @@ -382,6 +384,8 @@ $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; +if (! empty($search_categ_cus)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ + $sql.= ', '.MAIN_DB_PREFIX.'facture as f'; if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture_extrafields as ef on (f.rowid = ef.fk_object)"; if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; @@ -438,12 +442,21 @@ if ($search_montant_vat != '') $sql.= natural_search('f.tva', $search_montant_va if ($search_montant_localtax1 != '') $sql.= natural_search('f.localtax1', $search_montant_localtax1, 1); if ($search_montant_localtax2 != '') $sql.= natural_search('f.localtax2', $search_montant_localtax2, 1); if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1); -if ($search_status != '' && $search_status >= 0) +if ($search_categ_cus > 0) $sql.= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +if ($search_categ_cus == -2) $sql.= " AND cc.fk_categorie IS NULL"; +if ($search_status != '-1' && $search_status != '') { - if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft - if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed - if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) - if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned + if (is_numeric($search_status) && $search_status >= 0) + { + if ($search_status == '0') $sql.=" AND f.fk_statut = 0"; // draft + if ($search_status == '1') $sql.=" AND f.fk_statut = 1"; // unpayed + if ($search_status == '2') $sql.=" AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) + if ($search_status == '3') $sql.=" AND f.fk_statut = 3"; // abandonned + } + else + { + $sql.= " AND f.fk_statut IN (".$search_status.")"; // When search_status is '1,2' for example + } } if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$db->escape($search_paymentmode); if ($search_month > 0) @@ -453,7 +466,7 @@ if ($search_month > 0) else if ($search_year > 0 && ! empty($search_day)) $sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $serch_year))."'"; else - $sql.= " AND date_format(f.datef, '%m') = '".$month."'"; + $sql.= " AND date_format(f.datef, '%m') = '".$search_month."'"; } else if ($search_year > 0) { @@ -510,7 +523,8 @@ else $sql.= ' ORDER BY '; $listfield=explode(',',$sortfield); -foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.','; +$listorder=explode(',',$sortorder); +foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.($listorder[$key]?$listorder[$key]:'DESC').','; $sql.= ' f.rowid DESC '; $nbtotalofrecords = ''; @@ -518,6 +532,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1,$offset); @@ -538,8 +557,8 @@ if ($resql) } $param='&socid='.$socid; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); if ($sall) $param.='&sall='.urlencode($sall); if ($search_day) $param.='&search_day='.urlencode($search_day); if ($search_month) $param.='&search_month='.urlencode($search_month); @@ -563,9 +582,11 @@ if ($resql) if ($search_montant_ttc != '') $param.='&search_montant_ttc='.urlencode($search_montant_ttc); if ($search_status != '') $param.='&search_status='.urlencode($search_status); if ($search_paymentmode > 0) $param.='search_paymentmode='.urlencode($search_paymentmode); - if ($show_files) $param.='&show_files=' .urlencode($show_files); - if ($option) $param.="&option=".urlencode($option); + if ($show_files) $param.='&show_files='.urlencode($show_files); + if ($option) $param.="&search_option=".urlencode($option); if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + if ($search_categ_cus > 0) $param.='&search_categ_cus='.urlencode($search_categ_cus); + // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -574,26 +595,29 @@ if ($resql) 'presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"), ); - if ($conf->prelevement->enabled) - { - $langs->load("withdrawals"); - $arrayofmassactions['withdrawrequest']=$langs->trans("MakeWithdrawRequest"); + if ($conf->prelevement->enabled) { + $langs->load("withdrawals"); + $arrayofmassactions['withdrawrequest'] = $langs->trans("MakeWithdrawRequest"); } - if ($user->rights->facture->supprimer) - { - //if (! empty($conf->global->STOCK_CALCULATE_ON_BILL) || empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) - { - // mass deletion never possible on invoices on such situation + if ($user->rights->facture->supprimer) { + if (!empty($conf->global->INVOICE_CAN_REMOVE_DRAFT_ONLY)) { + $arrayofmassactions['predeletedraft'] = $langs->trans("Deletedraft"); } - else - { - $arrayofmassactions['predelete']=$langs->trans("Delete"); - } - } - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); + elseif (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED)) { // mass deletion never possible on invoices on such situation + $arrayofmassactions['predelete'] = $langs->trans("Delete"); + } + } + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + $newcardbutton=''; + if($user->rights->facture->creer) + { + $newcardbutton=''.$langs->trans('NewBill').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } + $i = 0; print ''."\n"; @@ -607,7 +631,7 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, '', '', $limit); + print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_accountancy.png', 0, $newcardbutton, '', $limit); $topicmail="SendBillRef"; $modelmail="facture_send"; @@ -618,7 +642,7 @@ if ($resql) if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + print '
'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'
'; } // If the user can view prospects other than his' @@ -649,6 +673,14 @@ if ($resql) $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter.='
'; } + if (! empty($conf->categorie->enabled)) + { + require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter.=$formother->select_categories('customer',$search_categ_cus,'search_categ_cus',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; @@ -706,19 +738,19 @@ if ($resql) if (! empty($arrayfields['f.date']['checked'])) { print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5, 0, 0, '', 'width75'); + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year?$search_year:-1,'search_year',1, 20, 5, 0, 0, '', 'widthauto valignmiddle'); print ''; } // Date due if (! empty($arrayfields['f.date_lim_reglement']['checked'])) { print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($search_year_lim?$search_year_lim:-1,'search_year_lim',1, 20, 5, 0, 0, '', 'width75'); - print '
'.$langs->trans("Late"); + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year_lim?$search_year_lim:-1,'search_year_lim',1, 20, 5, 0, 0, '', 'widthauto valignmiddle'); + print '
'.$langs->trans("Late"); print ''; } // Project @@ -760,7 +792,7 @@ if ($resql) if (! empty($arrayfields['f.fk_mode_reglement']['checked'])) { print ''; - $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10); + $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 10); print ''; } if (! empty($arrayfields['f.total_ht']['checked'])) @@ -779,14 +811,14 @@ if ($resql) } if (! empty($arrayfields['f.total_localtax1']['checked'])) { - // Amount + // Localtax1 print ''; print ''; print ''; } if (! empty($arrayfields['f.total_localtax2']['checked'])) { - // Amount + // Localtax2 print ''; print ''; print ''; @@ -831,7 +863,7 @@ if ($resql) if (! empty($arrayfields['f.fk_statut']['checked'])) { print ''; - $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); + $liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '1,2'=>$langs->trans("BillShortStatusNotPaid").'+'.$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); print $form->selectarray('search_status', $liststatus, $search_status, 1); print ''; } @@ -871,7 +903,7 @@ if ($resql) print $hookmanager->resPrint; if (! empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'],$_SERVER["PHP_SELF"],"f.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); if (! empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'],$_SERVER["PHP_SELF"],"f.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"fk_statut,paye,type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); + if (! empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'],$_SERVER["PHP_SELF"],"f.fk_statut,f.paye,f.type,dynamount_payed","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); print "\n"; @@ -983,6 +1015,7 @@ if ($resql) { $projectstatic->id=$obj->project_id; $projectstatic->ref=$obj->project_ref; + $projectstatic->title=$obj->project_label; print $projectstatic->getNomUrl(1); } print ''; @@ -1196,22 +1229,18 @@ if ($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); + $hidegeneratedfilelistifempty=1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; - $filedir=$diroutputmassaction; - $genallowed=$user->rights->facture->lire; - $delallowed=$user->rights->facture->creer; + // Show list of available documents + $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource.=str_replace('&','&',$param); - print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
'.$langs->trans("ShowTempMassFilesArea").''; - } + $filedir=$diroutputmassaction; + $genallowed=$user->rights->facture->lire; + $delallowed=$user->rights->facture->creer; + + print $formfile->showdocuments('massfilesarea_invoices','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty); } else { diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php index 755ac413743..58fc26030b7 100644 --- a/htdocs/compta/facture/note.php +++ b/htdocs/compta/facture/note.php @@ -33,8 +33,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load("companies"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'bills')); $id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility $ref=GETPOST('ref','alpha'); @@ -92,7 +92,7 @@ if ($id > 0 || ! empty($ref)) $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); + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1,'customer'); // Project if (! empty($conf->projet->enabled)) { diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 989e742afee..ecde973bd3b 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -37,10 +37,8 @@ if (! empty($conf->projet->enabled)) { if (!$user->rights->facture->lire) accessforbidden(); -$langs->load("bills"); -$langs->load("banks"); -$langs->load("withdrawals"); -$langs->load('companies'); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'banks', 'withdrawals', 'companies')); $id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility $ref=GETPOST('ref','alpha'); @@ -140,8 +138,16 @@ if ($object->id > 0) if ($object->paye) $resteapayer=0; $resteapayeraffiche=$resteapayer; - $absolute_discount=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NULL'); - $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('','fk_facture_source IS NOT NULL'); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice + } else { + $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')"; + $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')"; + } + + $absolute_discount=$object->thirdparty->getAvailableDiscounts('',$filterabsolutediscount); + $absolute_creditnote=$object->thirdparty->getAvailableDiscounts('',$filtercreditnote); $absolute_discount=price2num($absolute_discount,'MT'); $absolute_creditnote=price2num($absolute_creditnote,'MT'); @@ -253,61 +259,13 @@ if ($object->id > 0) // Discounts print ''.$langs->trans('Discounts').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); - print '. '; - if ($absolute_discount > 0) - { - if ($object->statut > Facture::STATUS_DRAFT || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) - { - if ($object->statut == Facture::STATUS_DRAFT) - { - print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)).'. '; - } - else - { - if ($object->statut < Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) - { - $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - print '
'.$text.'.
'; - } - else - { - $text=$langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency)); - $text2=$langs->trans("AbsoluteDiscountUse"); - print $form->textwithpicto($text,$text2); - } - } - } - else - { - // Remise dispo de type non avoir - $filter='fk_facture_source IS NULL'; - print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$object->thirdparty->id,$absolute_discount,$filter,$resteapayer,'',1); - } - } - if ($absolute_creditnote > 0) - { - // If validated, we show link "add credit note to payment" - if ($object->statut != Facture::STATUS_VALIDATED || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_CREDIT_NOTE) - { - if ($object->statut == Facture::STATUS_DRAFT && $object->type != Facture::TYPE_DEPOSIT) - { - $text=$langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)); - print $form->textwithpicto($text,$langs->trans("CreditNoteDepositUse")); - } - else print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'.'; - } - else - { - // Remise dispo de type avoir - $filter='fk_facture_source IS NOT NULL'; - if (! $absolute_discount) print '
'; - $form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id_for_payment',$object->thirdparty->id,$absolute_creditnote,$filter,$resteapayer,'',1); - } - } - if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.'; + + $thirdparty = $object->thirdparty; + $discount_type = 0; + $backtopage = urlencode($_SERVER["PHP_SELF"] . '?facid=' . $object->id); + $cannotApplyDiscount = 1; + include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php'; + print ''; // Date invoice diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index d85255fbf4e..0416e04f7b0 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -3,7 +3,7 @@ * Copyright (c) 2004-2012 Laurent Destailleur * Copyright (C) 2012 Marcos García * Copyright (C) 2013 Juanjo Menent - * Copyright (C) 2015 Jean-François Ferry + * 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 @@ -57,10 +57,8 @@ $endyear=$year; /* * View */ - -$langs->load('bills'); -$langs->load('companies'); -$langs->load('other'); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'companies', 'other')); $form=new Form($db); @@ -331,7 +329,7 @@ print '
'; // Show graphs -print '"; print "\n"; - $coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'sell'); + $coll_list = tax_by_thirdparty('localtax'.$local, $db, 0, $date_start, $date_end, $modetax, 'sell'); $action = "tvaclient"; $object = &$coll_list; @@ -176,12 +181,11 @@ if($calc ==0 || $calc == 2) if (is_array($coll_list)) { - $var=true; $total = 0; $totalamount = 0; $i = 1; foreach($coll_list as $coll) { - if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) !=0) + if(($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) !=0) { $intra = str_replace($find,$replace,$coll->tva_intra); @@ -244,19 +248,18 @@ if($calc ==0 || $calc == 1){ $company_static=new Societe($db); - $coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'buy'); + $coll_list = tax_by_thirdparty('localtax'.$local, $db, 0, $date_start, $date_end,$modetax, 'buy'); $parameters["direction"] = 'buy'; $parameters["type"] = 'localtax'.$local; $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks if (is_array($coll_list)) { - $var=true; $total = 0; $totalamount = 0; $i = 1; foreach($coll_list as $coll) { - if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) != 0) + if(($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) != 0) { $intra = str_replace($find,$replace,$coll->tva_intra); diff --git a/htdocs/compta/localtax/index.php b/htdocs/compta/localtax/index.php index 6286bfaa4e4..c62034ee65c 100644 --- a/htdocs/compta/localtax/index.php +++ b/htdocs/compta/localtax/index.php @@ -1,6 +1,7 @@ * Copyright (C) 2014 Ferran Marcet + * Copyright (C) 2018 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,48 +23,71 @@ * \brief Index page of IRPF reports */ require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; -$langs->load("other"); -$langs->load("compta"); -$langs->load("banks"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin")); $localTaxType=GETPOST('localTaxType', 'int'); +// Date range $year=GETPOST("year","int"); -if ($year == 0) +if (empty($year)) { - $year_current = strftime("%Y",time()); - $year_start = $year_current; + $year_current = strftime("%Y",dol_now()); + $year_start = $year_current; } else { - $year_current = $year; - $year_start = $year; + $year_current = $year; + $year_start = $year; +} +$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear")); +$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear")); +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $q=GETPOST("q","int"); + if (empty($q)) + { + if (GETPOST("month","int")) { $date_start=dol_get_first_day($year_start,GETPOST("month","int"),false); $date_end=dol_get_last_day($year_start,GETPOST("month","int"),false); } + else + { + $date_start=dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START,false); + $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1; + } + } + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + } } +// Define modetax (0 or 1) +// 0=normal, 1=option vat for services is on debit, 2=option on payments for products +$modetax = $conf->global->TAX_MODE; +if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int'); +if (empty($modetax)) $modetax=0; + // Security check -$socid = isset($_GET["socid"])?$_GET["socid"]:''; -if ($user->societe_id) - $socid=$user->societe_id; +$socid = GETPOST('socid','int'); +if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); -// Define modetax (0 or 1) -// 0=normal, 1=option vat for services is on debit -$modetax = $conf->global->TAX_MODE; -if (isset($_GET["modetax"])) - $modetax=$_GET["modetax"]; /** * print function * - * @param DoliDB $db Database - * @param string $sql sql - * @param string $date date - * @return void + * @param DoliDB $db Database handler + * @param string $sql SQL Request + * @param string $date Date + * @return void */ -function pt ($db, $sql, $date) +function pt($db, $sql, $date) { global $conf, $bc,$langs; @@ -73,29 +97,92 @@ function pt ($db, $sql, $date) $i = 0; $total = 0; print '
'; +print ' - - - - - + + + + - - + + 1) } ?> - \ No newline at end of file + diff --git a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php index e0f132e2ad5..5f224bc2026 100644 --- a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php +++ b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php @@ -39,15 +39,14 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $langs->load("bills"); $total=0; $ilink=0; -$var=true; foreach($linkedObjectBlock as $key => $objectlink) { $ilink++; - $trclass=($var?'pair':'impair'); + $trclass='oddeven'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total'; ?> - > + @@ -62,7 +61,7 @@ foreach($linkedObjectBlock as $key => $objectlink) print $objectlink->getLibStatut(3); ?> - + tax->enabled)) //if (!$user->rights->compta->general->lire) // accessforbidden(); -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); if (! empty($conf->commande->enabled)) $langs->load("orders"); @@ -199,7 +199,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) print $facturestatic->getNomUrl(1,''); print ''; print ''; print ''; print ''; @@ -234,7 +234,8 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $sql.= ", s.nom as name"; $sql.= ", s.rowid as socid, s.email"; $sql.= ", s.code_fournisseur, s.code_compta_fournisseur"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", cc.rowid as country_id, cc.code as country_code"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.rowid = f.fk_soc AND f.fk_statut = 0"; $sql.= " AND f.entity = ".$conf->entity; @@ -274,6 +275,8 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $companystatic->id=$obj->socid; $companystatic->name=$obj->name; $companystatic->email=$obj->email; + $companystatic->country_id=$obj->country_id; + $companystatic->country_code=$obj->country_code; $companystatic->fournisseur = 1; $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; @@ -313,7 +316,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- print '
'; -// Last modified customer invoices +// Latest modified customer invoices if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { $langs->load("boxes"); @@ -323,9 +326,10 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $sql.= ", f.date_lim_reglement as datelimite"; $sql.= ", s.nom as name"; $sql.= ", s.rowid as socid"; - $sql.= ", s.code_client, s.code_compta"; - $sql.= ", sum(pf.amount) as am"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; + $sql.= ", s.code_client, s.code_compta, s.email"; + $sql.= ", cc.rowid as country_id, cc.code as country_code"; + $sql.= ", sum(pf.amount) as am"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays, ".MAIN_DB_PREFIX."facture as f"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.rowid = f.fk_soc"; @@ -338,7 +342,8 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $sql.=$hookmanager->resPrint; $sql.= " GROUP BY f.rowid, f.facnumber, f.fk_statut, f.type, f.total, f.tva, f.total_ttc, f.paye, f.tms, f.date_lim_reglement,"; - $sql.= " s.nom, s.rowid, s.code_client, s.code_compta"; + $sql.= " s.nom, s.rowid, s.code_client, s.code_compta, s.email,"; + $sql.= " cc.rowid, cc.code"; $sql.= " ORDER BY f.tms DESC "; $sql.= $db->plimit($max, 0); @@ -374,6 +379,10 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $thirdpartystatic->id=$obj->socid; $thirdpartystatic->name=$obj->name; + $thirdpartystatic->email=$obj->email; + $thirdpartystatic->country_id=$obj->country_id; + $thirdpartystatic->country_code=$obj->country_code; + $thirdpartystatic->email=$obj->email; $thirdpartystatic->client=1; $thirdpartystatic->code_client = $obj->code_client; //$thirdpartystatic->code_fournisseur = $obj->code_fournisseur; @@ -567,10 +576,8 @@ if (! empty($conf->don->enabled) && $user->rights->societe->lire) print ''; if ($num) { - $var = true; $total_ttc = $totalam = $total = 0; - $var=true; while ($i < $num && $i < $max) { $objp = $db->fetch_object($result); @@ -631,7 +638,6 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $resql = $db->query($sql); if ( $resql ) { - $var = false; $num = $db->num_rows($resql); print '
'; if ($mesg) { print $mesg; } else { print $px1->show(); diff --git a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php index ca3ec7c89c0..1a55771b963 100644 --- a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php +++ b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php @@ -39,20 +39,19 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $langs->load("bills"); $total=0; $ilink=0; -$var=true; foreach($linkedObjectBlock as $key => $objectlink) { $ilink++; - $trclass=($var?'pair':'impair'); + $trclass='oddeven'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total'; ?> -
trans("CustomerInvoice"); ?>getNomUrl(1); ?>ref_client; ?>date,'day'); ?>" data-element="element; ?>" data-id="id; ?>" > + trans("CustomerInvoice"); ?>getNomUrl(1); ?>ref_client; ?>date,'day'); ?>rights->facture->lire) { $sign = 1; if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = -1; @@ -66,8 +65,8 @@ foreach($linkedObjectBlock as $key => $objectlink) echo ''.price($objectlink->total_ht).''; } } ?>getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink")); ?>getLibStatut(3); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
trans("RepeatableInvoice"); ?> getNomUrl(1); ?> ">transnoentitiesnoconv("RemoveLink")); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
'; - print $companystatic->getNomUrl(1,'',16); + print $companystatic->getNomUrl(1,'customer',16); print ''.price($obj->total_ttc).'
'; @@ -663,7 +669,6 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print ''; print ''; $tot_ttc+=$obj->amount; - $var = !$var; $i++; } @@ -699,8 +704,9 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us $sql.= ", s.nom as name, s.email"; $sql.= ", s.rowid as socid"; $sql.= ", s.code_client, s.code_compta"; - $sql.= ", c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.tva as total_tva, c.total_ttc"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.tva as total_tva, c.total_ttc,"; + $sql.= " cc.rowid as country_id, cc.code as country_code"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= ", ".MAIN_DB_PREFIX."commande as c"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_source = c.rowid AND el.sourcetype = 'commande'"; @@ -716,12 +722,11 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us $reshook=$hookmanager->executeHooks('printFieldListWhereCustomerOrderToBill',$parameters); $sql.=$hookmanager->resPrint; - $sql.= " GROUP BY s.nom, s.rowid, s.email, s.code_client, s.code_compta, c.rowid, c.ref, c.facture, c.fk_statut, c.tva, c.total_ht, c.total_ttc"; + $sql.= " GROUP BY s.nom, s.email, s.rowid, s.code_client, s.code_compta, c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.tva, c.total_ttc, cc.rowid, cc.code"; $resql = $db->query($sql); if ( $resql ) { - $var=false; $num = $db->num_rows($resql); if ($num) @@ -745,6 +750,8 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us $societestatic->id=$obj->socid; $societestatic->name=$obj->name; $societestatic->email=$obj->email; + $societestatic->country_id=$obj->country_id; + $societestatic->country_code=$obj->country_code; $societestatic->client=1; $societestatic->code_client = $obj->code_client; //$societestatic->code_fournisseur = $obj->code_fournisseur; @@ -817,8 +824,9 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $sql.= ", s.nom as name"; $sql.= ", s.rowid as socid, s.email"; $sql.= ", s.code_client, s.code_compta"; - $sql.= ", sum(pf.amount) as am"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; + $sql.= ", cc.rowid as country_id, cc.code as country_code"; + $sql.= ", sum(pf.amount) as am"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays,".MAIN_DB_PREFIX."facture as f"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.rowid = f.fk_soc AND f.paye = 0 AND f.fk_statut = 1"; @@ -831,13 +839,12 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $sql.=$hookmanager->resPrint; $sql.= " GROUP BY f.rowid, f.facnumber, f.fk_statut, f.datef, f.type, f.total, f.tva, f.total_ttc, f.paye, f.tms, f.date_lim_reglement,"; - $sql.= " s.nom, s.rowid, s.email, s.code_client, s.code_compta"; + $sql.= " s.nom, s.rowid, s.email, s.code_client, s.code_compta, cc.rowid, cc.code"; $sql.= " ORDER BY f.datef ASC, f.facnumber ASC"; $resql = $db->query($sql); if ($resql) { - $var=false; $num = $db->num_rows($resql); $i = 0; @@ -870,6 +877,8 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $societestatic->id=$obj->socid; $societestatic->name=$obj->name; $societestatic->email=$obj->email; + $societestatic->country_id=$obj->country_id; + $societestatic->country_code=$obj->country_code; $societestatic->client=1; $societestatic->code_client = $obj->code_client; $societestatic->code_fournisseur = $obj->code_fournisseur; @@ -971,7 +980,6 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $resql=$db->query($sql); if ($resql) { - $var=false; $num = $db->num_rows($resql); print '
'; @@ -1022,7 +1030,6 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $total_ttc += $obj->total_ttc; $totalam += $obj->am; $i++; - $var = !$var; } print '
'; @@ -1056,7 +1063,6 @@ if ($resql) print '
'.$chargestatic->getLibStatut(3).'
'.$langs->trans("Total").'   ('.$langs->trans("RemainderToPay").': '.price($total_ttc-$totalam).')
'; print ''.$langs->trans("TasksToDo").''; print "\n"; - $var = true; $i = 0; while ($i < $db->num_rows($resql)) { diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php index 5934ca71afb..2bc754ccf11 100644 --- a/htdocs/compta/journal/purchasesjournal.php +++ b/htdocs/compta/journal/purchasesjournal.php @@ -33,9 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; -$langs->load("companies"); -$langs->load("other"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadlangs(array('companies', 'other', 'compta')); $date_startmonth=GETPOST('date_startmonth'); $date_startday=GETPOST('date_startday'); diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index f4b027b5016..24b36cf76c0 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -35,10 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; - -$langs->load("companies"); -$langs->load("other"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'other', 'compta')); $date_startmonth=GETPOST('date_startmonth'); $date_startday=GETPOST('date_startday'); diff --git a/htdocs/compta/localtax/card.php b/htdocs/compta/localtax/card.php index f3dfbf05a05..e8a84fcc9e1 100644 --- a/htdocs/compta/localtax/card.php +++ b/htdocs/compta/localtax/card.php @@ -25,10 +25,10 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php'; -$langs->load("compta"); -$langs->load("banks"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'banks', 'bills')); $id=GETPOST("id",'int'); $action=GETPOST("action","alpha"); @@ -38,11 +38,11 @@ if (empty($refund)) $refund=0; $lttype=GETPOST('localTaxType', 'int'); // Security check -$socid = isset($_GET["socid"])?$_GET["socid"]:''; +$socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); -$localtax = new Localtax($db); +$object = new Localtax($db); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('localtaxvatcard','globalcard')); @@ -52,9 +52,9 @@ $hookmanager->initHooks(array('localtaxvatcard','globalcard')); * Actions */ -//add payment of localtax -if($_POST["cancel"] == $langs->trans("Cancel")){ - header("Location: reglement.php?localTaxType=".$lttype); +if ($_POST["cancel"] == $langs->trans("Cancel") && ! $id) +{ + header("Location: list.php?localTaxType=".$lttype); exit; } @@ -66,25 +66,25 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $datev=dol_mktime(12,0,0, $_POST["datevmonth"], $_POST["datevday"], $_POST["datevyear"]); $datep=dol_mktime(12,0,0, $_POST["datepmonth"], $_POST["datepday"], $_POST["datepyear"]); - $localtax->accountid=GETPOST("accountid"); - $localtax->paymenttype=GETPOST("paiementtype"); - $localtax->datev=$datev; - $localtax->datep=$datep; - $localtax->amount=price2num(GETPOST("amount")); - $localtax->label=GETPOST("label"); - $localtax->ltt=$lttype; + $object->accountid=GETPOST("accountid"); + $object->paymenttype=GETPOST("paiementtype"); + $object->datev=$datev; + $object->datep=$datep; + $object->amount=price2num(GETPOST("amount")); + $object->label=GETPOST("label"); + $object->ltt=$lttype; - $ret=$localtax->addPayment($user); + $ret=$object->addPayment($user); if ($ret > 0) { $db->commit(); - header("Location: reglement.php?localTaxType=".$lttype); + header("Location: list.php?localTaxType=".$lttype); exit; } else { $db->rollback(); - setEventMessages($localtax->error, $localtax->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $_GET["action"]="create"; } } @@ -92,39 +92,39 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) //delete payment of localtax if ($action == 'delete') { - $result=$localtax->fetch($id); + $result=$object->fetch($id); - if ($localtax->rappro == 0) + if ($object->rappro == 0) { $db->begin(); - $ret=$localtax->delete($user); + $ret=$object->delete($user); if ($ret > 0) { - if ($localtax->fk_bank) + if ($object->fk_bank) { $accountline=new AccountLine($db); - $result=$accountline->fetch($localtax->fk_bank); + $result=$accountline->fetch($object->fk_bank); if ($result > 0) $result=$accountline->delete($user); // $result may be 0 if not found (when bank entry was deleted manually and fk_bank point to nothing) } if ($result >= 0) { $db->commit(); - header("Location: ".DOL_URL_ROOT.'/compta/localtax/reglement.php?localTaxType='.$localtax->ltt); + header("Location: ".DOL_URL_ROOT.'/compta/localtax/list.php?localTaxType='.$object->ltt); exit; } else { - $localtax->error=$accountline->error; + $object->error=$accountline->error; $db->rollback(); - setEventMessages($localtax->error, $localtax->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } else { $db->rollback(); - setEventMessages($localtax->error, $localtax->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } else @@ -136,17 +136,12 @@ if ($action == 'delete') /* -* View -*/ - -llxHeader(); - -$form = new Form($db); + * View + */ if ($id) { - $vatpayment = new Localtax($db); - $result = $vatpayment->fetch($id); + $result = $object->fetch($id); if ($result <= 0) { dol_print_error($db); @@ -154,6 +149,13 @@ if ($id) } } +$form = new Form($db); + +$title=$langs->trans("LT".$object->ltt) . " - " . $langs->trans("Card"); +$help_url=''; +llxHeader("",$title,$helpurl); + + if ($action == 'create') { @@ -173,7 +175,7 @@ if ($action == 'create') print $form->select_date($datep,"datep",'','','','add',1,1); print ''; - print ''; @@ -218,47 +220,48 @@ if ($action == 'create') } -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ - +// View mode if ($id) { $h = 0; - $head[$h][0] = DOL_URL_ROOT.'/compta/localtax/card.php?id='.$vatpayment->id; + $head[$h][0] = DOL_URL_ROOT.'/compta/localtax/card.php?id='.$object->id; $head[$h][1] = $langs->trans('Card'); $head[$h][2] = 'card'; $h++; - dol_fiche_head($head, 'card', $langs->trans("VATPayment"), 0, 'payment'); + dol_fiche_head($head, 'card', $langs->transcountry("LT".$object->ltt, $mysoc->country_code), -1, 'payment'); + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', ''); + + print '
'; + print '
'; print '
'.$langs->trans("DateValue").''; + print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; print $form->select_date($datev,"datev",'','','','add',1,1); print '
'; print ""; - print ''; print ""; print ''; - print ''; - print ''; + print ''; if (! empty($conf->banque->enabled)) { - if ($vatpayment->fk_account > 0) + if ($object->fk_account > 0) { $bankline=new AccountLine($db); - $bankline->fetch($vatpayment->fk_bank); + $bankline->fetch($object->fk_bank); print ''; print ''; @@ -271,22 +274,28 @@ if ($id) // Other attributes $parameters=array(); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$vatpayment,$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 print $hookmanager->resPrint; print '
'.$langs->trans("Ref").''; - print $vatpayment->ref; + print ''.$langs->trans("Ref").''; + print $object->ref; print '
'.$langs->trans("DatePayment").''; - print dol_print_date($vatpayment->datep,'day'); + print dol_print_date($object->datep,'day'); print '
'.$langs->trans("DateValue").''; - print dol_print_date($vatpayment->datev,'day'); + print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; + print dol_print_date($object->datev,'day'); print '
'.$langs->trans("Amount").''.price($vatpayment->amount).'
'.$langs->trans("Amount").''.price($object->amount).'
'.$langs->trans('BankTransactionLine').'
'; - dol_fiche_end(); + print ''; + + dol_fiche_end(); /* - * Boutons d'actions - */ + * Action buttons + */ print "
\n"; - if ($vatpayment->rappro == 0) - print ''.$langs->trans("Delete").''; + if ($object->rappro == 0) + { + print ''.$langs->trans("Delete").''; + } else + { print ''.$langs->trans("Delete").''; + } print "
"; } diff --git a/htdocs/compta/localtax/class/localtax.class.php b/htdocs/compta/localtax/class/localtax.class.php index 570942590c2..a75de537724 100644 --- a/htdocs/compta/localtax/class/localtax.class.php +++ b/htdocs/compta/localtax/class/localtax.class.php @@ -29,7 +29,11 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; */ class Localtax extends CommonObject { - var $ltt; + public $element='localtax'; //!< Id that identify managed objects + public $table_element='localtax'; //!< Name of table without prefix where object is stored + public $picto='payment'; + + var $ltt; var $tms; var $datep; var $datev; @@ -132,7 +136,7 @@ class Localtax extends CommonObject * @param int $notrigger 0=no, 1=yes (no update trigger) * @return int <0 if KO, >0 if OK */ - function update($user=null, $notrigger=0) + function update(User $user, $notrigger=0) { global $conf, $langs; @@ -149,8 +153,8 @@ class Localtax extends CommonObject $this->db->begin(); // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."localtax SET"; - $sql.= " localtaxtype=".$this->ltt.","; + $sql = "UPDATE ".MAIN_DB_PREFIX."localtax SET"; + $sql.= " localtaxtype=".$this->ltt.","; $sql.= " tms='".$this->db->idate($this->tms)."',"; $sql.= " datep='".$this->db->idate($this->datep)."',"; $sql.= " datev='".$this->db->idate($this->datev)."',"; @@ -160,7 +164,7 @@ class Localtax extends CommonObject $sql.= " fk_bank=".$this->fk_bank.","; $sql.= " fk_user_creat=".$this->fk_user_creat.","; $sql.= " fk_user_modif=".$this->fk_user_modif; - $sql.= " WHERE rowid=".$this->id; + $sql.= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); @@ -255,12 +259,12 @@ class Localtax extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that delete - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that delete + * @return int <0 if KO, >0 if OK + */ function delete($user) { // Call trigger @@ -285,11 +289,11 @@ class Localtax extends CommonObject /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ function initAsSpecimen() { @@ -607,4 +611,29 @@ class Localtax extends CommonObject return $result; } + /** + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @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 + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status 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 + */ + function LibStatut($status,$mode=0) + { + global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage + + return ''; + } + } diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php index 70d52c3d9d3..9502ff46d2d 100644 --- a/htdocs/compta/localtax/clients.php +++ b/htdocs/compta/localtax/clients.php @@ -26,17 +26,16 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; -$langs->load("bills"); -$langs->load("compta"); -$langs->load("companies"); -$langs->load("products"); +// Load translation files required by the page +$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin")); $local=GETPOST('localTaxType', 'int'); // Date range -$year=GETPOST("year"); +$year=GETPOST("year","int"); if (empty($year)) { $year_current = strftime("%Y",dol_now()); @@ -45,43 +44,48 @@ if (empty($year)) $year_current = $year; $year_start = $year; } -$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]); -$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]); +$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear")); +$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear")); // Quarter if (empty($date_start) || empty($date_end)) // We define date_start and date_end { $q=GETPOST("q"); if (empty($q)) { - if (isset($_REQUEST["month"])) { $date_start=dol_get_first_day($year_start,$_REQUEST["month"],false); $date_end=dol_get_last_day($year_start,$_REQUEST["month"],false); } + if (GETPOST("month")) { $date_start=dol_get_first_day($year_start,GETPOST("month"),false); $date_end=dol_get_last_day($year_start,GETPOST("month"),false); } else { - $month_current = strftime("%m",dol_now()); - if ($month_current >= 10) $q=4; - elseif ($month_current >= 7) $q=3; - elseif ($month_current >= 4) $q=2; - else $q=1; + $date_start=dol_get_first_day($year_start,empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START,false); + if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end=dol_time_plus_duree($date_start, 3, 'm') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end=dol_time_plus_duree($date_start, 1, 'm') - 1; } } - if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } - if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } - if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } - if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + } } -$min = GETPOST("min"); +$min = price2num(GETPOST("min","alpha")); if (empty($min)) $min = 0; // Define modetax (0 or 1) -// 0=normal, 1=option vat for services is on debit +// 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (isset($_REQUEST["modetax"])) $modetax=$_REQUEST["modetax"]; +if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int'); +if (empty($modetax)) $modetax=0; // Security check $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); + + /* * View */ @@ -98,6 +102,9 @@ foreach($listofparams as $param) llxHeader('','','','',0,0,'','',$morequerystring); + +$name=$langs->transcountry($local==1?"LT1ReportByCustomers":"LT2ReportByCustomers", $mysoc->country_code); + $fsearch.='
'; $fsearch.=' '; $fsearch.=' '; @@ -108,7 +115,6 @@ $calc=$conf->global->MAIN_INFO_LOCALTAX_CALC.$local; // Affiche en-tete du rapport if ($calc==0 || $calc==1) // Calculate on invoice for goods and services { - $nom=$langs->transcountry($local==1?"LT1ReportByCustomersInInputOutputMode":"LT2ReportByCustomersInInputOutputMode",$mysoc->country_code); $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT".$local."Rec"); $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; $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); @@ -126,7 +132,6 @@ if ($calc==0 || $calc==1) // Calculate on invoice for goods and services } if ($calc==2) // Invoice for goods, payment for services { - $nom=$langs->transcountry($local==1?"LT1ReportByCustomersInInputOutputMode":"LT2ReportByCustomersInInputOutputMode",$mysoc->country_code); $calcmode=$langs->trans("CalcModeLT2Debt"); $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; $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); @@ -160,7 +165,7 @@ if($calc ==0 || $calc == 2) print "
".$vatcust."
'; + print ''; - print ''; - print ''; - print ''."\n"; + print ''; + print ''; + print ''; print "\n"; - $var=True; + + $totalclaimed = 0; + $totalpaid = 0; + $amountclaimed = 0; + $amountpaid = 0; + $previousmonth = ''; + $previousmode = ''; + $mode = ''; + while ($i < $num) { $obj = $db->fetch_object($result); + $mode = $obj->mode; - print ''; - print '\n"; - $total = $total + $obj->mm; + //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; + if ($obj->mode == 'claimed' && ! empty($previousmode)) + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - print '\n"; - print "\n"; + $amountclaimed = 0; + $amountpaid = 0; + } + + if ($obj->mode == 'claimed') + { + $amountclaimed = $obj->mm; + $totalclaimed = $totalclaimed + $amountclaimed; + } + if ($obj->mode == 'paid') + { + $amountpaid = $obj->mm; + $totalpaid = $totalpaid + $amountpaid; + } + + if ($obj->mode == 'paid') + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; + $amountclaimed = 0; + $amountpaid = 0; + $previousmode = ''; + $previousmonth = ''; + } + else + { + $previousmode = $obj->mode; + $previousmonth = $obj->dm; + } $i++; } - print '"; + + if ($mode == 'claimed' && ! empty($previousmode)) + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; + + $amountclaimed = 0; + $amountpaid = 0; + } + + print ''; + print ''; + print ''; + print ''; + print ""; print "
'.$date.''.$langs->trans("Amount").' '.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").'
'.$obj->dm."
'.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
'.price($obj->mm)." 
'.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
'.$langs->trans("Total")." :".price($total)." 
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
"; $db->free($result); - } else { + } + else { dol_print_error($db); } } @@ -105,7 +192,9 @@ function pt ($db, $sql, $date) * View */ -llxHeader(); +$form=new Form($db); +$company_static=new Societe($db); +$tva = new Tva($db); if($localTaxType==1) { $LT='LT1'; @@ -123,24 +212,37 @@ if($localTaxType==1) { $CalcLT= $conf->global->MAIN_INFO_LOCALTAX_CALC2; } +$fsearch.=' '; +$description = $fsearch; -$textprevyear="".img_previous().""; -$textnextyear=" ".img_next().""; +// Show report header +$name = $langs->trans("ReportByMonth"); +$description .= $langs->trans($LT); +$calcmode = $langs->trans("LTReportBuildWithOptionDefinedInModule").' '; +$calcmode.= '('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')
'; + +//if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue"); + +$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); + +$builddate=dol_now(); + + +llxHeader('', $name); + +//$textprevyear="".img_previous().""; +//$textnextyear=" ".img_next().""; +//print load_fiche_titre($langs->transcountry($LT,$mysoc->country_code),"$textprevyear ".$langs->trans("Year")." $year_start $textnextyear", 'title_accountancy.png'); + +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +//report_header($name,'',$textprevyear.$langs->trans("Year")." ".$year_start.$textnextyear,'',$description,$builddate,$exportlink,array(),$calcmode); -print load_fiche_titre($langs->transcountry($LT,$mysoc->country_code),"$textprevyear ".$langs->trans("Year")." $year_start $textnextyear", 'title_accountancy.png'); -print $langs->trans("LTReportBuildWithOptionDefinedInModule").'
'; -print '('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')
'; print '
'; -print ''; -print ''; +print '
'; -print '
'; -print load_fiche_titre($langs->transcountry($LTSummary,$mysoc->country_code), '', ''); -print ' '; -print load_fiche_titre($langs->transcountry($LTPaid,$mysoc->country_code), '', ''); -print '
'; +print load_fiche_titre($langs->transcountry($LTSummary,$mysoc->country_code), '', ''); print ''; print ''; @@ -155,22 +257,156 @@ if($CalcLT==1) { if($CalcLT==2) { print ""; } - print ""; print "\n"; print "\n"; -$y = $year_current ; +$tmp=dol_getdate($date_start); +$y = $tmp['year']; +$m = $tmp['mon']; +$tmp=dol_getdate($date_end); +$yend = $tmp['year']; +$mend = $tmp['mon']; -$var=True; $total=0; $subtotalcoll=0; $subtotalpaye=0; $subtotal=0; -$i=0; -for ($m = 1 ; $m < 13 ; $m++ ) { - $coll_listsell = tax_by_date('vat', $db, $y, 0, 0, 0, $modetax, 'sell', $m); - $coll_listbuy = tax_by_date('vat', $db, $y, 0, 0, 0, $modetax, 'buy', $m); +$i=0; $mcursor=0; +while ((($y < $yend) || ($y == $yend && $m < $mend)) && $mcursor < 1000) // $mcursor is to avoid too large loop +{ + //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12); + if ($m == 13) $y++; + if ($m > 12) $m -= 12; + $mcursor++; + + // Get array with details of each line + $x_coll = tax_by_rate(($localTaxType==1?'localtax1':'localtax2'), $db, $y, 0, 0, 0, $modetax, 'sell', $m); + $x_paye = tax_by_rate(($localTaxType==1?'localtax1':'localtax2'), $db, $y, 0, 0, 0, $modetax, 'buy', $m); + + $x_both = array(); + //now, from these two arrays, get another array with one rate per line + foreach(array_keys($x_coll) as $my_coll_rate) + { + $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; + $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; + $x_both[$my_coll_rate]['coll']['localtax1'] = $x_coll[$my_coll_rate]['localtax1']; + $x_both[$my_coll_rate]['coll']['localtax2'] = $x_coll[$my_coll_rate]['localtax2']; + $x_both[$my_coll_rate]['paye']['totalht'] = 0; + $x_both[$my_coll_rate]['paye']['vat'] = 0; + $x_both[$my_coll_rate]['paye']['localtax1'] = 0; + $x_both[$my_coll_rate]['paye']['localtax2'] = 0; + $x_both[$my_coll_rate]['coll']['links'] = ''; + $x_both[$my_coll_rate]['coll']['detail'] = array(); + foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) { + //$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; + //$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; + //$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; + //$company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]); + $x_both[$my_coll_rate]['coll']['detail'][] = array( + 'id' =>$x_coll[$my_coll_rate]['facid'][$id], + 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], + 'pid' =>$x_coll[$my_coll_rate]['pid'][$id], + 'pref' =>$x_coll[$my_coll_rate]['pref'][$id], + 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id], + 'payment_id'=>$x_coll[$my_coll_rate]['payment_id'][$id], + 'payment_amount'=>$x_coll[$my_coll_rate]['payment_amount'][$id], + 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], + 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], + 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], + 'datef' =>$x_coll[$my_coll_rate]['datef'][$id], + 'datep' =>$x_coll[$my_coll_rate]['datep'][$id], + //'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id], + 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], + + 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], + 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], + 'localtax1' =>$x_coll[$my_coll_rate]['localtax1_list'][$id], + 'localtax2' =>$x_coll[$my_coll_rate]['localtax2_list'][$id], + //'link' =>$invoice_customer->getNomUrl(1,'',12) + ); + } + } + + // tva paid + foreach (array_keys($x_paye) as $my_paye_rate) { + $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; + $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; + $x_both[$my_paye_rate]['paye']['localtax1'] = $x_paye[$my_paye_rate]['localtax1']; + $x_both[$my_paye_rate]['paye']['localtax2'] = $x_paye[$my_paye_rate]['localtax2']; + if (!isset($x_both[$my_paye_rate]['coll']['totalht'])) { + $x_both[$my_paye_rate]['coll']['totalht'] = 0; + $x_both[$my_paye_rate]['coll']['vat'] = 0; + $x_both[$my_paye_rate]['coll']['localtax1'] = 0; + $x_both[$my_paye_rate]['coll']['localtax2'] = 0; + } + $x_both[$my_paye_rate]['paye']['links'] = ''; + $x_both[$my_paye_rate]['paye']['detail'] = array(); + + foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) + { + // ExpenseReport + if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') + { + //$expensereport->id=$x_paye[$my_paye_rate]['facid'][$id]; + //$expensereport->ref=$x_paye[$my_paye_rate]['facnum'][$id]; + //$expensereport->type=$x_paye[$my_paye_rate]['type'][$id]; + + $x_both[$my_paye_rate]['paye']['detail'][] = array( + 'id' =>$x_paye[$my_paye_rate]['facid'][$id], + 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], + 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], + 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id' =>$x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount' =>$x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc' =>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc' =>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'ddate_start' =>$x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], + + 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], + 'localtax1' =>$x_paye[$my_paye_rate]['localtax1_list'][$id], + 'localtax2' =>$x_paye[$my_paye_rate]['localtax2_list'][$id], + //'link' =>$expensereport->getNomUrl(1) + ); + } + else + { + //$invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; + //$invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; + //$invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; + //$company_static->fetch($x_paye[$my_paye_rate]['company_id'][$id]); + $x_both[$my_paye_rate]['paye']['detail'][] = array( + 'id' =>$x_paye[$my_paye_rate]['facid'][$id], + 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], + 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], + 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id'=>$x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount'=>$x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'datef' =>$x_paye[$my_paye_rate]['datef'][$id], + 'datep' =>$x_paye[$my_paye_rate]['datep'][$id], + //'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], + + 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], + 'localtax1' =>$x_paye[$my_paye_rate]['localtax1_list'][$id], + 'localtax2' =>$x_paye[$my_paye_rate]['localtax2_list'][$id], + //'link' =>$invoice_supplier->getNomUrl(1,'',12) + ); + } + } + } + //now we have an array (x_both) indexed by rates for coll and paye $action = "tva"; - $object = array(&$coll_listsell, &$coll_listbuy); + $object = array(&$x_coll, &$x_paye, &$x_both); $parameters["mode"] = $modetax; $parameters["year"] = $y; $parameters["month"] = $m; @@ -180,112 +416,176 @@ for ($m = 1 ; $m < 13 ; $m++ ) { $hookmanager->initHooks(array('externalbalance')); $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - if (! is_array($coll_listbuy) && $coll_listbuy == -1) { + if (! is_array($x_coll) && $coll_listbuy == -1) + { $langs->load("errors"); print ''; break; } - if (! is_array($coll_listbuy) && $coll_listbuy == -2) { + if (! is_array($x_paye) && $coll_listbuy == -2) + { print ''; break; } print ''; - print ''; - if($CalcLT==0) { - $x_coll = 0; - foreach($coll_listsell as $vatrate=>$val) { - $x_coll+=$val[$localTaxType==1?'localtax1':'localtax2']; - } - $subtotalcoll = $subtotalcoll + $x_coll; - print ""; + print ''; - $x_paye = 0; - foreach($coll_listbuy as $vatrate=>$val) { - $x_paye+=$val[$localTaxType==1?'localtax1':'localtax2']; - } - $subtotalpaye = $subtotalpaye + $x_paye; - print ""; - } elseif($CalcLT==1) { - $x_paye = 0; - foreach($coll_listbuy as $vatrate=>$val) { - $x_paye+=$val[$localTaxType==1?'localtax1':'localtax2']; + $x_coll_sum = 0; + foreach (array_keys($x_coll) as $rate) + { + $subtot_coll_total_ht = 0; + $subtot_coll_vat = 0; + + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) + { + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } + + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) + { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + $temp_vat=$fields['localtax'.$localTaxType]*$ratiopaymentinvoice; + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; } - $subtotalpaye = $subtotalpaye + $x_paye; - print ""; - } elseif($CalcLT==2) { - $x_coll = 0; - foreach($coll_listsell as $vatrate=>$val) { - $x_coll+=$val[$localTaxType==1?'localtax1':'localtax2']; + } + print ""; + + $x_paye_sum = 0; + foreach (array_keys($x_paye) as $rate) + { + $subtot_paye_total_ht = 0; + $subtot_paye_vat = 0; + + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) + { + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } + + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) + { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + $temp_vat=$fields['localtax'.$localTaxType]*$ratiopaymentinvoice; + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; } - $subtotalcoll = $subtotalcoll + $x_coll; - print ""; - } + print ""; - if($CalcLT==0) { - $diff= $x_coll - $x_paye; - } elseif($CalcLT==1) { - $diff= $x_paye; - } elseif($CalcLT==2) { - $diff= $x_coll; - } + $subtotalcoll = $subtotalcoll + $x_coll_sum; + $subtotalpaye = $subtotalpaye + $x_paye_sum; + $diff = $x_coll_sum - $x_paye_sum; $total = $total + $diff; - $subtotal = $subtotal + $diff; + $subtotal = price2num($subtotal + $diff, 'MT'); - print "\n"; + print "\n"; print "\n"; print "\n"; - $i++; - if ($i > 2) { - print ''; - print ''; - if($CalcLT==0) { - print ''; - print ''; - print ''; - } elseif($CalcLT==1) { - print ''; - print ''; - } elseif($CalcLT==2) { - print ''; - print ''; - } - print ''; - $i = 0; - $subtotalcoll=0; $subtotalpaye=0; $subtotal=0; + $i++; $m++; + if ($i > 2) + { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i = 0; + $subtotalcoll=0; $subtotalpaye=0; $subtotal=0; } } -print ''; +print ''; print "\n"; print ''; print '
".$langs->transcountry($LTCustomer,$mysoc->country_code)."".$langs->trans("TotalToPay")." 
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.dol_print_date(dol_mktime(0,0,0,$m,1,$y),"%b %Y").'".price($x_coll)."'.dol_print_date(dol_mktime(0,0,0,$m,1,$y),"%b %Y").'".price($x_paye)."".price($x_paye)."".price(price2num($x_coll_sum,'MT'))."".price($x_coll)."".price(price2num($x_paye_sum,'MT'))."".price($diff)."".price(price2num($diff,'MT'))." 
'.$langs->trans("SubTotal").':'.price($subtotalcoll).''.price($subtotalpaye).''.price($subtotal).''.price($subtotalpaye).''.price($subtotal).''.price($subtotalcoll).''.price($subtotal).' 
'.$langs->trans("SubTotal").':'.price(price2num($subtotalcoll,'MT')).''.price(price2num($subtotalpaye,'MT')).''.price(price2num($subtotal,'MT')).' 
'.$langs->trans("TotalToPay").':'.price($total).'
'.$langs->trans("TotalToPay").':'.price(price2num($total, 'MT')).' 
'; -print '
 '; + +print '
'; + + /* * Payed */ -$sql = "SELECT SUM(amount) as mm, date_format(f.datev,'%Y-%m') as dm"; +print load_fiche_titre($langs->transcountry($LTPaid,$mysoc->country_code), '', ''); + +$sql=''; + +$sql.= "SELECT SUM(amount) as mm, date_format(f.datev,'%Y-%m') as dm, 'claimed' as mode"; $sql.= " FROM ".MAIN_DB_PREFIX."localtax as f"; $sql.= " WHERE f.entity = ".$conf->entity; -$sql.= " AND f.datev >= '".$db->idate(dol_get_first_day($y,1,false))."'"; -$sql.= " AND f.datev <= '".$db->idate(dol_get_last_day($y,12,false))."'"; +$sql.= " AND (f.datev >= '".$db->idate($date_start)."' AND f.datev <= '".$db->idate($date_end)."')"; $sql.= " AND localtaxtype=".$localTaxType; $sql.= " GROUP BY dm"; -$sql.= " ORDER BY dm ASC"; -pt($db, $sql,$langs->trans("Year")." $y"); +$sql.= " UNION "; -print '
'; +$sql.= "SELECT SUM(amount) as mm, date_format(f.datep,'%Y-%m') as dm, 'paid' as mode"; +$sql.= " FROM ".MAIN_DB_PREFIX."localtax as f"; +$sql.= " WHERE f.entity = ".$conf->entity; +$sql.= " AND (f.datep >= '".$db->idate($date_start)."' AND f.datep <= '".$db->idate($date_end)."')"; +$sql.= " AND localtaxtype=".$localTaxType; +$sql.= " GROUP BY dm"; -print ''; -print ''; +$sql.= " ORDER BY dm ASC, mode ASC"; +//print $sql; + +pt($db, $sql, $langs->trans("Month")); + + +print '
'; llxFooter(); $db->close(); diff --git a/htdocs/compta/localtax/reglement.php b/htdocs/compta/localtax/list.php similarity index 72% rename from htdocs/compta/localtax/reglement.php rename to htdocs/compta/localtax/list.php index 54183ef72b9..0e32a249f17 100644 --- a/htdocs/compta/localtax/reglement.php +++ b/htdocs/compta/localtax/list.php @@ -16,7 +16,7 @@ */ /** - * \file htdocs/compta/localtax/reglement.php + * \file htdocs/compta/localtax/list.php * \ingroup tax * \brief List of IRPF payments */ @@ -24,15 +24,16 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; -$langs->load("compta"); +// Load translation files required by the page $langs->load("compta"); // Security check -$socid = isset($_GET["socid"])?$_GET["socid"]:''; +$socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); $ltt=GETPOST("localTaxType"); + /* * View */ @@ -41,12 +42,20 @@ llxHeader(); $localtax_static = new Localtax($db); -print load_fiche_titre($langs->transcountry($ltt==2?"LT2Payments":"LT1Payments",$mysoc->country_code)); +$newcardbutton=''; +if ($user->rights->tax->charges->creer) +{ + $newcardbutton=''.$langs->trans('NewLocalTaxPayment', ($ltt+1)).''; + $newcardbutton.= ''; + $newcardbutton.= ''; +} -$sql = "SELECT rowid, amount, label, f.datev as dm"; +print load_fiche_titre($langs->transcountry($ltt==2?"LT2Payments":"LT1Payments",$mysoc->country_code), $newcardbutton); + +$sql = "SELECT rowid, amount, label, f.datev, f.datep"; $sql.= " FROM ".MAIN_DB_PREFIX."localtax as f "; $sql.= " WHERE f.entity = ".$conf->entity." AND localtaxtype=".$db->escape($ltt); -$sql.= " ORDER BY dm DESC"; +$sql.= " ORDER BY datev DESC"; $result = $db->query($sql); if ($result) @@ -59,6 +68,7 @@ if ($result) print ''; print ''.$langs->trans("Ref").''; print "".$langs->trans("Label").""; + print "".$langs->trans("PeriodEndDate").""; print ''.$langs->trans("DatePayment").''; print "".$langs->trans("PayedByThisPayment").""; print "\n"; @@ -66,14 +76,15 @@ if ($result) while ($i < $num) { $obj = $db->fetch_object($result); - + print ''; $localtax_static->id=$obj->rowid; $localtax_static->ref=$obj->rowid; print "".$localtax_static->getNomUrl(1)."\n"; print "".dol_trunc($obj->label,40)."\n"; - print ''.dol_print_date($db->jdate($obj->dm),'day')."\n"; + print ''.dol_print_date($db->jdate($obj->datev),'day')."\n"; + print ''.dol_print_date($db->jdate($obj->datep),'day')."\n"; $total = $total + $obj->amount; print "".price($obj->amount).""; @@ -81,8 +92,8 @@ if ($result) $i++; } - print ''.$langs->trans("Total").''; - print "".price($total).""; + print ''.$langs->trans("Total").''; + print ''.price($total).''; print ""; $db->free($result); diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php index 5e18c786c18..31729693f37 100644 --- a/htdocs/compta/localtax/quadri_detail.php +++ b/htdocs/compta/localtax/quadri_detail.php @@ -22,8 +22,7 @@ /** * \file htdocs/compta/tva/quadri_detail.php * \ingroup tax - * \brief Trimestrial page - detailed version - * TODO Deal with recurrent invoices as well + * \brief Local tax by rate */ global $mysoc; @@ -31,21 +30,22 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php'; -$langs->load("bills"); -$langs->load("compta"); -$langs->load("companies"); -$langs->load("products"); +// Load translation files required by the page +$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin")); $local=GETPOST('localTaxType', 'int'); // Date range -$year=GETPOST("year"); +$year=GETPOST("year","int"); if (empty($year)) { $year_current = strftime("%Y",dol_now()); @@ -54,38 +54,41 @@ if (empty($year)) $year_current = $year; $year_start = $year; } - -$date_start = dol_mktime( 0, 0, 0, GETPOST( "date_startmonth" ), GETPOST( "date_startday" ), GETPOST( "date_startyear" ) ); -$date_end = dol_mktime( 23, 59, 59, GETPOST( "date_endmonth" ), GETPOST( "date_endday" ), GETPOST( "date_endyear" ) ); +$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear")); +$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear")); // Quarter if (empty($date_start) || empty($date_end)) // We define date_start and date_end { - $q=GETPOST("q"); + $q=GETPOST("q","int"); if (empty($q)) { - if (isset($_REQUEST["month"])) { $date_start=dol_get_first_day($year_start,$_REQUEST["month"],false); $date_end=dol_get_last_day($year_start,$_REQUEST["month"],false); } + if (GETPOST("month","int")) { $date_start=dol_get_first_day($year_start,GETPOST("month","int"),false); $date_end=dol_get_last_day($year_start,GETPOST("month","int"),false); } else { - $month_current = strftime("%m",dol_now()); - if ($month_current >= 10) $q=4; - elseif ($month_current >= 7) $q=3; - elseif ($month_current >= 4) $q=2; - else $q=1; + $date_start=dol_get_first_day($year_start,empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START,false); + if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end=dol_time_plus_duree($date_start, 3, 'm') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end=dol_time_plus_duree($date_start, 1, 'm') - 1; } } - if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } - if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } - if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } - if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + } } -$min = GETPOST("min"); +$min = price2num(GETPOST("min","alpha")); if (empty($min)) $min = 0; // Define modetax (0 or 1) -// 0=normal, 1=option vat for services is on debit -$modetax = $conf->global->TAX_MODE; -if (isset($_REQUEST["modetax"])) $modetax=$_REQUEST["modetax"]; +// 0=normal, 1=option vat for services is on debit, 2=option on payments for products +//$modetax = $conf->global->TAX_MODE; +$calc=$conf->global->MAIN_INFO_LOCALTAX_CALC.$local; +$modetax=$conf->global->$calc; +if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int'); if (empty($modetax)) $modetax=0; // Security check @@ -93,122 +96,123 @@ $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); -/** + + +/* * View */ + +$form=new Form($db); +$company_static=new Societe($db); +$invoice_customer=new Facture($db); +$invoice_supplier=new FactureFournisseur($db); +$expensereport=new ExpenseReport($db); +$product_static=new Product($db); +$payment_static=new Paiement($db); +$paymentfourn_static=new PaiementFourn($db); +$paymentexpensereport_static=new PaymentExpenseReport($db); + $morequerystring=''; $listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday'); -foreach($listofparams as $param) +foreach ($listofparams as $param) { if (GETPOST($param)!='') $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); } -llxHeader('','','','',0,0,'','',$morequerystring); - -$form=new Form($db); - -$company_static=new Societe($db); -$invoice_customer=new Facture($db); -$invoice_supplier=new FactureFournisseur($db); -$product_static=new Product($db); -$payment_static=new Paiement($db); -$paymentfourn_static=new PaiementFourn($db); +llxHeader('',$langs->trans("LocalTaxReport"),'','',0,0,'','',$morequerystring); $fsearch.=' '; $fsearch.=' '; $fsearch.=' '; -$calc=$conf->global->MAIN_INFO_LOCALTAX_CALC.$local; - -if ($conf->global->$calc==0 || $conf->global->$calc==1) // Calculate on invoice for goods and services -{ - $nom=$langs->trans($local==1?"LT1ReportByQuartersInDueDebtMode":"LT2ReportByQuartersInDueDebtMode"); - $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT".$local."Rec"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; - $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); - $prevyear=$year_start; $prevquarter=$q; - if ($prevquarter > 1) $prevquarter--; - else { $prevquarter=4; $prevyear--; } - $nextyear=$year_start; $nextquarter=$q; - if ($nextquarter < 4) $nextquarter++; - else { $nextquarter=1; $nextyear++; } - - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.='
'.$langs->trans("DepositsAreNotIncluded"); - else $description.='
'.$langs->trans("DepositsAreIncluded"); - $description.=$fsearch; - $builddate=dol_now(); - - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("ProductOrService"); - $amountcust=$langs->trans("AmountHT"); - $vatcust=$langs->trans("VATReceived"); - if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')'; - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$langs->trans("ProductOrService"); - $amountsup=$langs->trans("AmountHT"); - $vatsup=$langs->trans("VATPaid"); - if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; +$name=$langs->transcountry($local==1?"LT1ReportByQuarters":"LT2ReportByQuarters", $mysoc->country_code); +$calcmode=''; +if ($modetax == 0) $calcmode=$langs->trans('OptionVATDefault'); +if ($modetax == 1) $calcmode=$langs->trans('OptionVATDebitOption'); +if ($modetax == 2) $calcmode=$langs->trans('OptionPaymentForProductAndServices'); +$calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; +// Set period +$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); +$prevyear=$year_start; $prevquarter=$q; +if ($prevquarter > 1) { + $prevquarter--; +} else { + $prevquarter=4; $prevyear--; } -if ($conf->global->$calc==2) // Invoice for goods, payment for services -{ - $nom=$langs->trans($local==1?"LT1ReportByQuartersInInputOutputMode":"LT2ReportByQuartersInInputOutputMode"); - $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT".$local."Rec"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; - $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); - $prevyear=$year_start; $prevquarter=$q; - if ($prevquarter > 1) $prevquarter--; - else { $prevquarter=4; $prevyear--; } - $nextyear=$year_start; $nextquarter=$q; - if ($nextquarter < 4) $nextquarter++; - else { $nextquarter=1; $nextyear++; } - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.=' '.$langs->trans("DepositsAreNotIncluded"); - else $description.=' '.$langs->trans("DepositsAreIncluded"); - $description.=$fsearch; - $builddate=dol_now(); - - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("ProductOrService"); - $amountcust=$langs->trans("AmountHT"); - $vatcust=$langs->trans("VATReceived"); - if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')'; - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$langs->trans("ProductOrService"); - $amountsup=$langs->trans("AmountHT"); - $vatsup=$langs->trans("VATPaid"); - if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; +$nextyear=$year_start; $nextquarter=$q; +if ($nextquarter < 4) { + $nextquarter++; +} else { + $nextquarter=1; $nextyear++; } +$description.=$fsearch; +$builddate=dol_now(); + +/*if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description.=$langs->trans("RulesVATDueProducts"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description.=$langs->trans("RulesVATInProducts"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description.='
'.$langs->trans("RulesVATDueServices"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description.='
'.$langs->trans("RulesVATInServices"); +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description.='
'.$langs->trans("DepositsAreNotIncluded"); +} +*/ +if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue"); + +// Customers invoices +$elementcust=$langs->trans("CustomersInvoices"); +$productcust=$langs->trans("ProductOrService"); +$amountcust=$langs->trans("AmountHT"); +$vatcust=$langs->trans("VATReceived"); +$namecust=$langs->trans("Name"); +if ($mysoc->tva_assuj) { + $vatcust.=' ('.$langs->trans("ToPay").')'; +} + +// Suppliers invoices +$elementsup=$langs->trans("SuppliersInvoices"); +$productsup=$productcust; +$amountsup=$amountcust; +$vatsup=$langs->trans("VATPaid"); +$namesup=$namecust; +if ($mysoc->tva_assuj) { + $vatsup.=' ('.$langs->trans("ToGetBack").')'; +} + + report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); if($local==1){ $vatcust=$langs->transcountry("LocalTax1", $mysoc->country_code); $vatsup=$langs->transcountry("LocalTax1", $mysoc->country_code); + $vatexpensereport=$langs->transcountry("LocalTax1", $mysoc->country_code); }else{ $vatcust=$langs->transcountry("LocalTax2", $mysoc->country_code); $vatsup=$langs->transcountry("LocalTax2", $mysoc->country_code); + $vatexpensereport=$langs->transcountry("LocalTax2", $mysoc->country_code); } // VAT Received and paid +echo ''; $y = $year_current; $total = 0; $i=0; +$columns = 5; // Load arrays of datas -$x_coll = tax_by_date('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); -$x_paye = tax_by_date('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); - -echo '
'; +$x_coll = tax_by_rate('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); +$x_paye = tax_by_rate('localtax' . $local, $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); if (! is_array($x_coll) || ! is_array($x_paye)) { $langs->load("errors"); if ($x_coll == -1) - print ''; + print ''; else if ($x_coll == -2) - print ''; + print ''; else - print ''; + print ''; } else { @@ -228,6 +232,7 @@ else $invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; $invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; $invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; + $company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]); $x_both[$my_coll_rate]['coll']['detail'][] = array( 'id' =>$x_coll[$my_coll_rate]['facid'][$id], 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], @@ -239,20 +244,24 @@ else 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], + 'datef' =>$x_coll[$my_coll_rate]['datef'][$id], + 'datep' =>$x_coll[$my_coll_rate]['datep'][$id], + 'company_link'=>$company_static->getNomUrl(1,'',20), 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id], 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], 'localtax1'=> $x_coll[$my_coll_rate]['localtax1_list'][$id], 'localtax2'=> $x_coll[$my_coll_rate]['localtax2_list'][$id], 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], - 'link' =>$invoice_customer->getNomUrl(1,'',12)); + 'link' =>$invoice_customer->getNomUrl(1,'',12) + ); } } // tva paid - foreach(array_keys($x_paye) as $my_paye_rate){ + foreach(array_keys($x_paye) as $my_paye_rate) { $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; - if(!isset($x_both[$my_paye_rate]['coll']['totalht'])){ + if(!isset($x_both[$my_paye_rate]['coll']['totalht'])) { $x_both[$my_paye_rate]['coll']['totalht'] = 0; $x_both[$my_paye_rate]['coll']['vat'] = 0; } @@ -275,35 +284,39 @@ else 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'datef' =>$x_paye[$my_paye_rate]['datef'][$id], + 'datep' =>$x_paye[$my_paye_rate]['datep'][$id], + 'company_link'=>$company_static->getNomUrl(1,'',20), 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id], 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), 'localtax1'=> $x_paye[$my_paye_rate]['localtax1_list'][$id], 'localtax2'=> $x_paye[$my_paye_rate]['localtax2_list'][$id], 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], - 'link' =>$invoice_supplier->getNomUrl(1,'',12)); + 'link' =>$invoice_supplier->getNomUrl(1,'',12) + ); } } //now we have an array (x_both) indexed by rates for coll and paye + //print table headers for this quadri - incomes first + $x_coll_sum = 0; $x_coll_ht = 0; $x_paye_sum = 0; $x_paye_ht = 0; - $span=3; - if ($modetax == 0) $span+=2; + $span=$columns; + if ($modetax != 1) $span+=2; - if($conf->global->$calc ==0 || $conf->global->$calc == 2){ + //if ($modetax == 0 || $modetax == 2) + //{ // Customers invoices print ''; print ''; print ''; - if ($modetax == 0) - { - print ''; - print ''; - } + if ($modetax != 2) print ''; + if ($modetax != 1) print ''; print ''; print ''; print ''; @@ -319,8 +332,6 @@ else if (is_array($x_both[$rate]['coll']['detail'])) { // VAT Rate - $var=true; - if($rate!=0){ print ""; print ''; @@ -328,116 +339,116 @@ else } foreach($x_both[$rate]['coll']['detail'] as $index => $fields) { - if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)){ - // Define type - $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (! empty($fields['ddate_start'])) $type=1; - if (! empty($fields['ddate_end'])) $type=1; - - - print ''; - - // Ref - print ''; - - // Description - print ''; - // Total HT - if ($modetax == 0) - { - print ''; + + // Ref + print ''; + + // Description + print ''; - } - // Payment - $ratiopaymentinvoice=1; - if ($modetax == 0) - { - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + // Total HT + if ($modetax != 2) + { + print ''; + } + + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + print ''; + } + + // Total collected print ''; + + // Localtax + print ''; + print ''; + + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; } - - // Total collected - print ''; - - // Localtax - print ''; - print ''; - - $subtot_coll_total_ht += $temp_ht; - $subtot_coll_vat += $temp_vat; - $x_coll_sum += $temp_vat; } } - } - if($rate!=0){ - // Total customers for this vat rate - print ''; - print ''; - print ''; - if ($modetax == 0) - { - print ''; - print ''; - } - print ''; - print ''; - print ''; - } + + // Total customers for this vat rate + print ''; + print ''; + print ''; + if ($modetax != 1) + { + print ''; + print ''; + } + print ''; + print ''; + print ''; } if (count($x_coll) == 0) // Show a total ine if nothing shown @@ -459,15 +470,15 @@ else print ''; print '
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
'.$langs->trans("Error").'
'.$elementcust.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("BI").''.$vatcust.'
'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].''; - if ($fields['pid']) + if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)) { - $product_static->id=$fields['pid']; - $product_static->ref=$fields['pref']; - $product_static->type=$fields['ptype']; - print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); - } - else - { - if ($type) $text = img_object($langs->trans('Service'),'service'); - else $text = img_object($langs->trans('Product'),'product'); - if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) - { - if ($reg[1]=='DEPOSIT') $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); - elseif ($reg[1]=='CREDIT_NOTE') $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); - else $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); - } - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + // Define type + $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (! empty($fields['ddate_start'])) $type=1; + if (! empty($fields['ddate_end'])) $type=1; - // Show range - print_date_range($fields['ddate_start'],$fields['ddate_end']); - } - print ''; - print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) + print '
'.$fields['link'].''; + if ($fields['pid']) { - $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); + $product_static->id=$fields['pid']; + $product_static->ref=$fields['pref']; + $product_static->type=$fields['ptype']; + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + } + else + { + if ($type) $text = img_object($langs->trans('Service'),'service'); + else $text = img_object($langs->trans('Product'),'product'); + if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) + { + if ($reg[1]=='DEPOSIT') $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); + elseif ($reg[1]=='CREDIT_NOTE') $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); + else $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); + } + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + + // Show range + print_date_range($fields['ddate_start'],$fields['ddate_end']); } print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) + { + $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); + } + print ''; + if ($fields['payment_amount'] && $fields['ftotal_ttc']) + { + $payment_static->id=$fields['payment_id']; + print $payment_static->getNomUrl(2); + } + if ($type == 0) + { + print $langs->trans("NotUsedForGoods"); + } + else { + print price($fields['payment_amount']); + if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } + print ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { - $payment_static->id=$fields['payment_id']; - print $payment_static->getNomUrl(2); - } - if ($type == 0) - { - print $langs->trans("NotUsedForGoods"); - } - else { - print price($fields['payment_amount']); - if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)'; - } + $temp_ht=$fields['totalht']; + if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + print price(price2num($temp_ht,'MT')); print ''; + $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2']; + print price(price2num($temp_vat,'MT')); + //print price($fields['vat']); + print '
'; - $temp_ht=$fields['totalht']; - if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice; - print price(price2num($temp_ht,'MT')); - print ''; - $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2']; - print price(price2num($temp_vat,'MT')); - //print price($fields['vat']); - print '
'.$langs->trans("Total").':  '.price(price2num($subtot_coll_total_ht,'MT')).''.price(price2num($subtot_coll_vat,'MT')).'
'.$langs->trans("Total").':  '.price(price2num($subtot_coll_total_ht,'MT')).''.price(price2num($subtot_coll_vat,'MT')).'
 
'; $diff=$x_coll_sum; - } + //} - if($conf->global->$calc ==0 || $conf->global->$calc == 1){ + //if($conf->global->$calc ==0 || $conf->global->$calc == 1){ echo ''; //print table headers for this quadri - expenses now print ''; print ''; print ''; - if ($modetax == 0) + if ($modetax != 1) { print ''; print ''; @@ -481,9 +492,8 @@ else $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; - if(is_array($x_both[$rate]['paye']['detail'])) + if (is_array($x_both[$rate]['paye']['detail'])) { - $var=true; if($rate!=0){ print ""; print ''; @@ -491,149 +501,144 @@ else } foreach($x_both[$rate]['paye']['detail'] as $index=>$fields) { - if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)){ - // Define type - $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (! empty($fields['ddate_start'])) $type=1; - if (! empty($fields['ddate_end'])) $type=1; - - - print ''; - - // Ref - print ''; - - // Description - print ''; - // Total HT - if ($modetax == 0) - { - print ''; + + // Ref + print ''; + + // Description + print ''; - } - - // Payment - $ratiopaymentinvoice=1; - if ($modetax == 0) - { - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); - print ''; + + // Total HT + if ($modetax != 2) + { + print ''; + } + + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + print ''; + } + + // VAT paid + print ''; + + // Localtax + print ''; + print ''; + + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; } - - // VAT paid - print ''; - - // Localtax - print ''; - print ''; - - $subtot_paye_total_ht += $temp_ht; - $subtot_paye_vat += $temp_vat; - $x_paye_sum += $temp_vat; } } - } - if($rate!=0){ - // Total suppliers for this vat rate - print ''; - print ''; - print ''; - if ($modetax == 0) - { - print ''; - print ''; - } - print ''; - print ''; - print ''; - } + + // Total suppliers for this vat rate + print ''; + print ''; + print ''; + if ($modetax != 1) + { + print ''; + print ''; + } + print ''; + print ''; + print ''; } - if (count($x_paye) == 0) // Show a total ine if nothing shown - { - print ''; - print ''; - print ''; - if ($modetax == 0) - { - print ''; - print ''; - } - print ''; - print ''; - print ''; + if (count($x_paye) == 0) { // Show a total line if nothing shown + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; } print '
'.$elementsup.''.$productsup.''.$amountsup.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')
'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].''; - if ($fields['pid']) + if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)) { - $product_static->id=$fields['pid']; - $product_static->ref=$fields['pref']; - $product_static->type=$fields['ptype']; - print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); - } - else - { - if ($type) $text = img_object($langs->trans('Service'),'service'); - else $text = img_object($langs->trans('Product'),'product'); - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + // Define type + $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (! empty($fields['ddate_start'])) $type=1; + if (! empty($fields['ddate_end'])) $type=1; - // Show range - print_date_range($fields['ddate_start'],$fields['ddate_end']); - } - print ''; - print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) + print '
'.$fields['link'].''; + if ($fields['pid']) { - //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; - $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); - //print ' ('.round($ratiolineinvoice*100,2).'%)'; - } - print ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { - $paymentfourn_static->id=$fields['payment_id']; - print $paymentfourn_static->getNomUrl(2); - } - if ($type == 0) - { - print $langs->trans("NotUsedForGoods"); + $product_static->id=$fields['pid']; + $product_static->ref=$fields['pref']; + $product_static->type=$fields['ptype']; + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); } else { - print price($fields['payment_amount']); - if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + if ($type) $text = img_object($langs->trans('Service'),'service'); + else $text = img_object($langs->trans('Product'),'product'); + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + + // Show range + print_date_range($fields['ddate_start'],$fields['ddate_end']); } print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) + { + //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; + $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); + //print ' ('.round($ratiolineinvoice*100,2).'%)'; + } + print ''; + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + if ($fields['payment_amount'] && $fields['ftotal_ttc']) + { + $paymentfourn_static->id=$fields['payment_id']; + print $paymentfourn_static->getNomUrl(2); + } + if ($type == 0) + { + print $langs->trans("NA"); + } + else + { + print price(price2num($fields['payment_amount'],'MT')); + if (isset($fields['payment_amount'])) { + print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } + } + print ''; + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + print price(price2num($temp_ht,'MT'),1); + print ''; + $temp_vat=($local==1?$fields['localtax1']:$fields['localtax2'])*$ratiopaymentinvoice;; + print price(price2num($temp_vat,'MT'),1); + //print price($fields['vat']); + print '
'; - $temp_ht=$fields['totalht']; - if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice; - print price(price2num($temp_ht,'MT')); - print ''; - $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2']; - print price(price2num($temp_vat,'MT')); - //print price($fields['vat']); - print '
 '.$langs->trans("Total").':  '.price(price2num($subtot_paye_total_ht,'MT')).''.price(price2num($subtot_paye_vat,'MT')).'
 '.$langs->trans("Total").':  '.price(price2num($subtot_paye_total_ht,'MT')).''.price(price2num($subtot_paye_vat,'MT')).'
 '.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
 '.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
'; - $diff=$x_paye_sum; - } + //} - if($conf->global->$calc ==0){$diff=$x_coll_sum - $x_paye_sum;} - echo ''; - // Total to pay - print '

'; - print '
'; - //$diff = $local==1?$x_coll_sum:$x_paye_sum; - print ''; - print ''; - print '\n"; - print "\n"; - - echo '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
'; + // Total to pay + print '

'; + print ''; + $diff = $x_coll_sum - $x_paye_sum; + print ''; + print ''; + print '\n"; + print "\n"; $i++; } +print '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
'; llxFooter(); $db->close(); diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 11751fe258b..c2ce95dd827 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -35,10 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; -$langs->load('companies'); -$langs->load('bills'); -$langs->load('banks'); -$langs->load('multicurrency'); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'bills', 'banks', 'multicurrency')); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm'); @@ -88,11 +86,11 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm=='yes')) + if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) { $error = 0; - $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth','int'), GETPOST('reday','int'), GETPOST('reyear','int')); $paiement_id = 0; $totalpayment = 0; $multicurrency_totalpayment = 0; @@ -504,18 +502,18 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print ''.$langs->trans('CheckTransmitter'); print ' ('.$langs->trans("ChequeMaker").')'; print ''; - print ''; + print ''; // Bank name print ''.$langs->trans('Bank'); print ' ('.$langs->trans("ChequeBank").')'; print ''; - print ''; + print ''; // Comments print ''.$langs->trans('Comments').''; print ''; - print ''; + print ''; print ''; @@ -591,7 +589,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print ' '; print "\n"; - $var=true; $total=0; $totalrecu=0; $totalrecucreditnote=0; @@ -601,7 +598,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie { $objp = $db->fetch_object($resql); - $soc = new Societe($db); $soc->fetch($objp->socid); @@ -819,7 +815,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie if (! GETPOST('action','aZ09')) { if ($page == -1) $page = 0 ; - $limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; + $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $offset = $limit * $page ; if (! $sortorder) $sortorder='DESC'; @@ -827,7 +823,7 @@ if (! GETPOST('action','aZ09')) $sql = 'SELECT p.datep as dp, p.amount, f.amount as fa_amount, f.facnumber'; $sql.=', f.rowid as facid, c.libelle as paiement_type, p.num_paiement'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (' . getEntity('c_paiement').')'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql.= ', '.MAIN_DB_PREFIX.'facture as f'; $sql.= ' WHERE p.fk_facture = f.rowid'; $sql.= ' AND f.entity IN (' . getEntity('facture').')'; @@ -844,7 +840,6 @@ if (! GETPOST('action','aZ09')) { $num = $db->num_rows($resql); $i = 0; - $var=true; print_barre_liste($langs->trans('Payments'), $page, $_SERVER["PHP_SELF"],'',$sortfield,$sortorder,'',$num); print ''; diff --git a/htdocs/compta/paiement/card.php b/htdocs/compta/paiement/card.php index 3a6727b4299..656d6c673f2 100644 --- a/htdocs/compta/paiement/card.php +++ b/htdocs/compta/paiement/card.php @@ -34,9 +34,8 @@ require_once DOL_DOCUMENT_ROOT .'/core/modules/facture/modules_facture.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; if (! empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load('bills'); -$langs->load('banks'); -$langs->load('companies'); +// Load translation files required by the page +$langs->loadLangs(array('bills','banks','companies')); $id=GETPOST('id','int'); $ref=GETPOST('ref', 'alpha'); @@ -222,57 +221,64 @@ print '
'; print '
'."\n"; // Date payment -print ''; // Payment type (VIR, LIQ, ...) $labeltype=$langs->trans("PaymentType".$object->type_code)!=("PaymentType".$object->type_code)?$langs->trans("PaymentType".$object->type_code):$object->type_libelle; -print ''; - -// Payment numero -print ''; - -// Amount -print ''; - -// Note -print ''; +print ''; $disable_delete = 0; // Bank account if (! empty($conf->banque->enabled)) { - if ($object->fk_account > 0) - { - $bankline=new AccountLine($db); - $bankline->fetch($object->bank_line); - if ($bankline->rappro) - { - $disable_delete = 1; - $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); - } + if ($object->fk_account > 0) + { + $bankline=new AccountLine($db); + $bankline->fetch($object->bank_line); + if ($bankline->rappro) + { + $disable_delete = 1; + $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); + } - print ''; - print ''; - print ''; - print ''; - - print ''; - print ''; - print ''; + print ''; + print ''; - print ''; + print $accountstatic->getNomUrl(1); + print ''; + print ''; + } +} +// Payment numero +/* +$titlefield=$langs->trans('Numero').' ('.$langs->trans("ChequeOrTransferNumber").')'; +print ''; + +// Check transmitter +$titlefield=$langs->trans('CheckTransmitter').' ('.$langs->trans("ChequeMaker").')'; +print ''; + +// Bank name +$titlefield=$langs->trans('Bank').' ('.$langs->trans("ChequeBank").')'; +print ''; +*/ + +// Bank account +if (! empty($conf->banque->enabled)) +{ + if ($object->fk_account > 0) + { if ($object->type_code == 'CHQ' && $bankline->fk_bordereau > 0) { dol_include_once('/compta/paiement/cheque/class/remisecheque.class.php'); @@ -280,15 +286,30 @@ if (! empty($conf->banque->enabled)) $bordereau->fetch($bankline->fk_bordereau); print ''; - print ''; - print ''; + print ''; - print ''; + print ''; + print ''; } - } + } + + print ''; + print ''; + print ''; + print ''; } +// Comments +print ''; + +// Amount +print ''; + print '
'.$form->editfieldkey("Date",'datep',$object->date,$object,$user->rights->facture->paiement).''; +print '
'.$form->editfieldkey("Date",'datep',$object->date,$object,$user->rights->facture->paiement).''; print $form->editfieldval("Date",'datep',$object->date,$object,$user->rights->facture->paiement,'datepicker','',null,$langs->trans('PaymentDateUpdateSucceeded')); print '
'.$langs->trans('PaymentMode').''.$labeltype.'
'.$form->editfieldkey("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; -print $form->editfieldval("Numero",'num_paiement',$object->numero,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded')); -print '
'.$langs->trans('Amount').''.price($object->amount,'',$langs,0,-1,-1,$conf->currency).'
'.$form->editfieldkey("Note",'note',$object->note,$object,$user->rights->facture->paiement).''; -print $form->editfieldval("Note",'note',$object->note,$object,$user->rights->facture->paiement,'textarea'); -print '
'.$langs->trans('PaymentMode').''.$labeltype.'
'.$langs->trans('BankTransactionLine').''; - print $bankline->getNomUrl(1,0,'showconciliated'); - print '
'.$langs->trans('BankAccount').''; + print '
'.$langs->trans('BankAccount').''; $accountstatic=new Account($db); $accountstatic->fetch($bankline->fk_account); - print $accountstatic->getNomUrl(1); - print '
'.$form->editfieldkey($titlefield,'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; +print $form->editfieldval($titlefield,'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded')); +print '
'.$form->editfieldkey($titlefield,'chqemetteur',$object->,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; +print $form->editfieldval($titlefield,'chqemetteur',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('ChequeMakeUpdateSucceeded')); +print '
'.$form->editfieldkey($titlefield,'chqbank',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).''; +print $form->editfieldval($titlefield,'chqbank',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('ChequeBankUpdateSucceeded')); +print '
'.$langs->trans('CheckReceipt').''; + print ''.$langs->trans('CheckReceipt').''; print $bordereau->getNomUrl(1); - print '
'.$langs->trans('BankTransactionLine').''; + print $bankline->getNomUrl(1,0,'showconciliated'); + print '
'.$form->editfieldkey("Comments",'note',$object->note,$object,$user->rights->facture->paiement).''; +print $form->editfieldval("Note",'note',$object->note,$object,$user->rights->facture->paiement,'textarea:'.ROWS_3.':90%'); +print '
'.$langs->trans('Amount').''.price($object->amount,'',$langs,0,-1,-1,$conf->currency).'
'; print ''; @@ -332,8 +353,6 @@ if ($resql) if ($num > 0) { - $var=True; - while ($i < $num) { $objp = $db->fetch_object($resql); diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php index 8a165ebe811..69f3bd102df 100644 --- a/htdocs/compta/paiement/cheque/card.php +++ b/htdocs/compta/paiement/cheque/card.php @@ -32,11 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.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('compta'); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'bills', 'companies', 'compta')); $id =GETPOST('id','int'); $ref=GETPOST('ref', 'alpha'); @@ -54,7 +51,7 @@ $page=GETPOST('page', 'int'); if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="b.dateo,b.rowid"; if (empty($page) || $page == -1) { $page = 0; } -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $offset = $limit * $page ; $dir=$conf->bank->dir_output.'/checkdeposits/'; diff --git a/htdocs/compta/paiement/cheque/index.php b/htdocs/compta/paiement/cheque/index.php index 74fe9ea9455..527bd05e3a1 100644 --- a/htdocs/compta/paiement/cheque/index.php +++ b/htdocs/compta/paiement/cheque/index.php @@ -28,10 +28,8 @@ require('../../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'compta', 'bills')); // Security check if ($user->societe_id) $socid=$user->societe_id; @@ -70,7 +68,6 @@ print "\n"; if ($resql) { - $var=false; if ($row = $db->fetch_row($resql) ) { $num = $row[0]; @@ -116,7 +113,6 @@ if ($resql) print ''.$langs->trans("Status").''; print "\n"; - $var=true; while ( $objp = $db->fetch_object($resql) ) { $checkdepositstatic->id=$objp->rowid; diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php index 76c52215281..800f40b9694 100644 --- a/htdocs/compta/paiement/cheque/list.php +++ b/htdocs/compta/paiement/cheque/list.php @@ -31,9 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'bills')); // Security check if ($user->societe_id) $socid=$user->societe_id; @@ -43,7 +42,7 @@ $search_ref = GETPOST('search_ref','alpha'); $search_account = GETPOST('search_account','int'); $search_amount = GETPOST('search_amount','alpha'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -117,6 +116,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); @@ -131,6 +135,14 @@ if ($resql) if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; + $newcardbutton=''; + if ($user->rights->banque->cheque) + { + $newcardbutton = ''.$langs->trans('NewCheckDeposit').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } + print '
'; if ($optioncss != '') print ''; print ''; @@ -140,7 +152,7 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("MenuChequeDeposits"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_bank.png', '', '', $limit); + print_barre_liste($langs->trans("MenuChequeDeposits"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_bank.png', 0, $newcardbutton, '', $limit); $moreforfilter=''; @@ -183,7 +195,6 @@ if ($resql) if ($num > 0) { - $var=true; while ($i < min($num,$limit)) { $objp = $db->fetch_object($resql); diff --git a/htdocs/compta/paiement/class/cpaiement.class.php b/htdocs/compta/paiement/class/cpaiement.class.php index b089cac6aab..59f13023b24 100644 --- a/htdocs/compta/paiement/class/cpaiement.class.php +++ b/htdocs/compta/paiement/class/cpaiement.class.php @@ -107,7 +107,7 @@ class Cpaiement // Insert request $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '('; - $sql.= 'id,'; + $sql.= 'entity,'; $sql.= 'code,'; $sql.= 'libelle,'; $sql.= 'type,'; @@ -118,7 +118,7 @@ class Cpaiement $sql .= ') VALUES ('; - $sql .= ' '.(! isset($this->id)?'NULL':$this->id).','; + $sql .= ' '.(! isset($this->entity)?getEntity('c_paiement'):$this->entity).','; $sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").','; $sql .= ' '.(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").','; $sql .= ' '.(! isset($this->type)?'NULL':$this->type).','; @@ -186,7 +186,8 @@ class Cpaiement $sql .= " t.module"; $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; if (null !== $ref) { - $sql .= ' WHERE t.code = ' . '\'' . $ref . '\''; + $sql .= ' WHERE t.entity IN ('.getEntity('c_paiement').')'; + $sql .= ' AND t.code = ' . '\'' . $ref . '\''; } else { $sql .= ' WHERE t.id = ' . $id; } diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index 088e14c5543..539c70f591b 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -60,6 +60,7 @@ class Paiement extends CommonObject // de llx_paiement qui est lie aux types de //paiement de llx_c_paiement var $num_paiement; // Numero du CHQ, VIR, etc... + var $num_payment; // Numero du CHQ, VIR, etc... var $bank_account; // Id compte bancaire du paiement var $bank_line; // Id de la ligne d'ecriture bancaire // fk_paiement dans llx_paiement est l'id du type de paiement (7 pour CHQ, ...) @@ -89,7 +90,7 @@ class Paiement extends CommonObject { $sql = 'SELECT p.rowid, p.ref, p.datep as dp, p.amount, p.statut, p.fk_bank,'; $sql.= ' c.code as type_code, c.libelle as type_libelle,'; - $sql.= ' p.num_paiement, p.note,'; + $sql.= ' p.num_paiement as num_payment, p.note,'; $sql.= ' b.fk_account'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; @@ -111,7 +112,9 @@ class Paiement extends CommonObject $this->ref = $obj->ref?$obj->ref:$obj->rowid; $this->date = $this->db->jdate($obj->dp); $this->datepaye = $this->db->jdate($obj->dp); - $this->numero = $obj->num_paiement; + $this->numero = $obj->num_payment; // deprecated + $this->num_paiement = $obj->num_payment; // deprecated + $this->num_payment = $obj->num_payment; $this->montant = $obj->amount; // deprecated $this->amount = $obj->amount; $this->note = $obj->note; @@ -210,9 +213,10 @@ class Paiement extends CommonObject $total = $totalamount_converted; // Maybe use price2num with MT for the converted value $mtotal = $totalamount; } + $note = ($this->note_public?$this->note_public:$this->note); $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, ref, datec, datep, amount, multicurrency_amount, fk_paiement, num_paiement, note, fk_user_creat)"; - $sql.= " VALUES (".$conf->entity.", '".$this->ref."', '". $this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($this->note)."', ".$user->id.")"; + $sql.= " VALUES (".$conf->entity.", '".$this->ref."', '". $this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($note)."', ".$user->id.")"; dol_syslog(get_class($this)."::Create insert paiement", LOG_DEBUG); $resql = $this->db->query($sql); @@ -532,7 +536,7 @@ class Paiement extends CommonObject { if ($accountid <= 0) { - $this->error='Bad value for parameter accountid'; + $this->error='Bad value for parameter accountid='.$accountid; dol_syslog(get_class($this).'::addPaymentToBank '.$this->error, LOG_ERR); return -1; } diff --git a/htdocs/compta/paiement/info.php b/htdocs/compta/paiement/info.php index d0bda152b21..9f55761dba0 100644 --- a/htdocs/compta/paiement/info.php +++ b/htdocs/compta/paiement/info.php @@ -28,8 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; -$langs->load("bills"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'companies')); $id=GETPOST('id'); $ref=GETPOST('ref', 'alpha'); diff --git a/htdocs/compta/paiement/list.php b/htdocs/compta/paiement/list.php index 595c9e868dc..064ca877c3f 100644 --- a/htdocs/compta/paiement/list.php +++ b/htdocs/compta/paiement/list.php @@ -6,6 +6,7 @@ * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2015 Juanjo Menent * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -34,8 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; -$langs->load("bills"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'compta')); // Security check $facid = GETPOST('facid','int'); @@ -59,7 +60,7 @@ $search_amount=GETPOST("search_amount",'alpha'); // alpha because we must be $search_company=GETPOST("search_company",'alpha'); $search_payment_num=GETPOST('search_payment_num','alpha'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -138,7 +139,7 @@ else $reshook=$hookmanager->executeHooks('printFieldListSelect',$parameters); // Note that $action and $object may have been modified by hook $sql.=$hookmanager->resPrint; $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id AND c.entity IN (" . getEntity('c_paiement') . ")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON p.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement"; @@ -191,6 +192,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); @@ -229,21 +235,21 @@ if ($resql) // Lines for filters fields print ''; print ''; - print ''; + print ''; print ''; print ''; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; $formother->select_year($year?$year:-1,'year',1, 20, 5); print ''; print ''; - print ''; + print ''; print ''; print ''; $form->select_types_paiements($search_paymenttype,'search_paymenttype','',2,1,1); print ''; print ''; - print ''; + print ''; print ''; if (! empty($conf->banque->enabled)) { @@ -252,7 +258,7 @@ if ($resql) print ''; } print ''; - print ''; + print ''; print ''; print ''; $searchpicto=$form->showFilterAndCheckAddButtons(0); @@ -278,7 +284,7 @@ if ($resql) print_liste_field_titre("Amount",$_SERVER["PHP_SELF"],"p.amount","",$param,'align="right"',$sortfield,$sortorder); //print_liste_field_titre("Invoices"),"","","",$param,'align="left"',$sortfield,$sortorder); - $parameters=array(); + $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; diff --git a/htdocs/compta/paiement/avalider.php b/htdocs/compta/paiement/tovalidate.php similarity index 89% rename from htdocs/compta/paiement/avalider.php rename to htdocs/compta/paiement/tovalidate.php index beb2fb77ecd..e60f65f924e 100644 --- a/htdocs/compta/paiement/avalider.php +++ b/htdocs/compta/paiement/tovalidate.php @@ -17,13 +17,14 @@ */ /** - * \file htdocs/compta/paiement/avalider.php + * \file htdocs/compta/paiement/tovalidate.php * \ingroup compta - * \brief Page liste des paiements a valider des factures clients + * \brief Page list payment to validate. Visible in menu when option BILL_ADD_PAYMENT_VALIDATION is on. */ require '../../main.inc.php'; +// Load translation files required by the page $langs->load("bills"); // Security check @@ -38,7 +39,7 @@ if ($user->societe_id > 0) } -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST('sortfield','alpha'); $sortorder = GETPOST('sortorder','alpha'); $page = GETPOST('page','int'); @@ -85,6 +86,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1,$offset); @@ -94,7 +100,6 @@ if ($resql) { $num = $db->num_rows($resql); $i = 0; - $var=True; print_barre_liste($langs->trans("ReceivedCustomersPaymentsToValid"), $page, $_SERVER["PHP_SELF"],"",$sortfield,$sortorder,'',$num); diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index e966eba4a47..fba8723d818 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php' require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +// Load translation files required by the page $langs->load("bills"); $chid=GETPOST("id", 'int'); @@ -271,7 +272,6 @@ if ($action == 'create') print ''.$langs->trans("Amount").''; print "\n"; - $var=true; $total=0; $totalrecu=0; @@ -279,8 +279,6 @@ if ($action == 'create') { $objp = $charge; - - print ''; if ($objp->date_ech > 0) @@ -324,7 +322,7 @@ if ($action == 'create') if ($i > 1) { // Print total - print ""; + print ''; print ''.$langs->trans("Total").':'; print "".price($total_ttc).""; print "".price($totalrecu).""; diff --git a/htdocs/compta/payment_sc/card.php b/htdocs/compta/payment_sc/card.php index ea9bc5af42a..b395016aeed 100644 --- a/htdocs/compta/payment_sc/card.php +++ b/htdocs/compta/payment_sc/card.php @@ -32,9 +32,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; if (! empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load('bills'); -$langs->load('banks'); -$langs->load('companies'); +// Load translation files required by the page +$langs->loadLangs(array('bills', 'banks', 'companies')); // Security check $id=GETPOST("id",'int'); @@ -245,13 +244,10 @@ if ($resql) if ($num > 0) { - $var=True; - while ($i < $num) { $objp = $db->fetch_object($resql); - print ''; // Ref print ''; diff --git a/htdocs/compta/prelevement/bons.php b/htdocs/compta/prelevement/bons.php index 9d3da39e5c3..0cbaa9ce55e 100644 --- a/htdocs/compta/prelevement/bons.php +++ b/htdocs/compta/prelevement/bons.php @@ -28,16 +28,15 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("widthdrawals"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'widthdrawals')); // Security check $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'prelevement','','','bons'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST('sortfield','alpha'); $sortorder = GETPOST('sortorder','alpha'); $page = GETPOST('page','int'); @@ -87,6 +86,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1,$offset); @@ -101,6 +105,14 @@ if ($result) $selectedfields=''; + $newcardbutton=''; + if ($user->rights->prelevement->bons->creer) + { + $newcardbutton = ''.$langs->trans('NewStandingOrder').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } + // Lines of title fields print ''; if ($optioncss != '') print ''; @@ -112,7 +124,7 @@ if ($result) print ''; print ''; - print_barre_liste($langs->trans("WithdrawalsReceipts"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic', 0, '', '', $limit); + print_barre_liste($langs->trans("WithdrawalsReceipts"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_generic', 0, $newcardbutton, '', $limit); $moreforfilter=''; diff --git a/htdocs/compta/prelevement/card.php b/htdocs/compta/prelevement/card.php index ed0977ebabf..343a45472b6 100644 --- a/htdocs/compta/prelevement/card.php +++ b/htdocs/compta/prelevement/card.php @@ -29,8 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories')); if (!$user->rights->prelevement->bons->lire) accessforbidden(); @@ -322,6 +322,11 @@ if ($id > 0 || $ref) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index d0aa788fe48..245b25be3b6 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -4,6 +4,7 @@ * Copyright (C) 2010-2015 Juanjo Menent * Copyright (C) 2010-2014 Laurent Destailleur * Copyright (C) 2014-2016 Ferran Marcet + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -98,14 +99,6 @@ class BonPrelevement extends CommonObject $this->methodes_trans[0] = "Internet"; $this->_fetched = 0; - - - $langs->load("withdrawals"); - $this->labelstatut[0]=$langs->trans("StatusWaiting"); - $this->labelstatut[1]=$langs->trans("StatusTrans"); - $this->labelstatut[2]=$langs->trans("StatusCredited"); - - return 1; } /** @@ -726,16 +719,12 @@ class BonPrelevement extends CommonObject $sql = "SELECT count(f.rowid) as nb"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.=", ".MAIN_DB_PREFIX."societe_rib as sr"; $sql.= " WHERE f.fk_statut = 1"; $sql.= " AND f.entity = ".$conf->entity; $sql.= " AND f.rowid = pfd.fk_facture"; $sql.= " AND f.paye = 0"; $sql.= " AND pfd.traite = 0"; $sql.= " AND f.total_ttc > 0"; - //if ($banque || $agence) $sql.= " AND f.fk_soc = sr.rowid"; - //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; - //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; dol_syslog(get_class($this)."::SommeAPrelever"); $resql = $this->db->query($sql); @@ -764,9 +753,10 @@ class BonPrelevement extends CommonObject * @param int $agence dolibarr mysoc bank office (guichet) * @param string $mode real=do action, simu=test only * @param string $format FRST, RCUR or ALL + * @param string $executiondate Date to execute the transfer * @return int <0 if KO, nbre of invoice withdrawed if OK */ - function Create($banque=0, $agence=0, $mode='real', $format='ALL') + function Create($banque=0, $agence=0, $mode='real', $format='ALL',$executiondate='') { global $conf,$langs; @@ -780,6 +770,8 @@ class BonPrelevement extends CommonObject $error = 0; $datetimeprev = time(); + //Choice the date of the execution direct debit + if(!empty($executiondate)) $datetimeprev = $executiondate; $month = strftime("%m", $datetimeprev); $year = strftime("%Y", $datetimeprev); @@ -805,9 +797,8 @@ class BonPrelevement extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; - //if ($banque || $agence) $sql.= ", ".MAIN_DB_PREFIX."societe_rib as sr"; $sql.= " WHERE f.rowid = pfd.fk_facture"; - $sql.= " AND f.entity = ".$conf->entity; + $sql.= " AND f.entity IN (".getEntity('facture').')'; $sql.= " AND s.rowid = f.fk_soc"; //if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc"; $sql.= " AND f.fk_statut = 1"; @@ -1082,7 +1073,7 @@ class BonPrelevement extends CommonObject $this->factures = $factures_prev_id; // Generation of SEPA file $this->filename - $this->generate($format); + $this->generate($format,$executiondate); } dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG); } @@ -1279,9 +1270,10 @@ class BonPrelevement extends CommonObject * File is generated with name this->filename * * @param string $format FRST, RCUR or ALL + * @param string $executiondate Date to execute transfer * @return int 0 if OK, <0 if KO */ - function generate($format='ALL') + function generate($format='ALL',$executiondate='') { global $conf,$langs,$mysoc; @@ -1310,10 +1302,16 @@ class BonPrelevement extends CommonObject */ // SEPA Initialisation $CrLf = "\n"; - $date_actu = dol_now(); + + $now = dol_now(); + + $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S'); + + $date_actu = $now; + if (!empty($executiondate)) $date_actu=$executiondate; + $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d'); $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S'); - $dateTime_ECMA = dol_print_date($date_actu, '%Y-%m-%dT%H:%M:%S'); $fileDebiteurSection = ''; $fileEmetteurSection = ''; $i = 0; @@ -1340,6 +1338,7 @@ class BonPrelevement extends CommonObject $sql.= " AND soc.rowid = f.fk_soc"; $sql.= " AND rib.fk_soc = f.fk_soc"; $sql.= " AND rib.default_rib = 1"; + $sql.= " AND rib.type = 'ban'"; //print $sql; // Define $fileDebiteurSection. One section DrctDbtTxInf per invoice. @@ -1883,48 +1882,52 @@ class BonPrelevement extends CommonObject */ function LibStatut($statut,$mode=0) { - global $langs; + if (empty($this->labelstatut)) + { + global $langs; + $langs->load("withdrawals"); + $this->labelstatut[0]=$langs->trans("StatusWaiting"); + $this->labelstatut[1]=$langs->trans("StatusTrans"); + $this->labelstatut[2]=$langs->trans("StatusCredited"); + } if ($mode == 0) { - return $langs->trans($this->labelstatut[$statut]); + return $this->labelstatut[$statut]; } - if ($mode == 1) { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + return $this->labelstatut[$statut]; } if ($mode == 2) { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1').' '.$this->labelstatut[$statut]; + if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3').' '.$this->labelstatut[$statut]; + if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6').' '.$this->labelstatut[$statut]; } if ($mode == 3) { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1'); + if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3'); + if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6'); } if ($mode == 4) { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==0) return img_picto($this->labelstatut[$statut],'statut1').' '.$this->labelstatut[$statut]; + if ($statut==1) return img_picto($this->labelstatut[$statut],'statut3').' '.$this->labelstatut[$statut]; + if ($statut==2) return img_picto($this->labelstatut[$statut],'statut6').' '.$this->labelstatut[$statut]; } if ($mode == 5) { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + if ($statut==0) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut1'); + if ($statut==1) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut3'); + if ($statut==2) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut6'); } if ($mode == 6) { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); - if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); + if ($statut==0) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut1'); + if ($statut==1) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut3'); + if ($statut==2) return $this->labelstatut[$statut].' '.img_picto($this->labelstatut[$statut],'statut6'); } } diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index af49e849e9f..9cc2cf77867 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -3,6 +3,7 @@ * Copyright (C) 2010-2015 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2010-2012 Juanjo Menent + * Copyright (C) 2018 Nicolas ZABOURI * * 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,11 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("widthdrawals"); -$langs->load("companies"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'widthdrawals', 'companies', 'bills')); // Security check if ($user->societe_id) $socid=$user->societe_id; @@ -68,7 +66,9 @@ if ($action == 'create') { // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty $bprev = new BonPrelevement($db); - $result=$bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format); + $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + + $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format,$executiondate); if ($result < 0) { setEventMessages($bprev->error, $bprev->errors, 'errors'); @@ -93,6 +93,7 @@ if ($action == 'create') /* * View */ +$form = new Form($db); $thirdpartystatic=new Societe($db); $invoicestatic=new Facture($db); @@ -147,23 +148,22 @@ print ''; if ($mesg) print $mesg; print "
\n"; +print ''; +print ''; +if ($nb) { + if ($pricetowithdraw) { + print $langs->trans('ExecutionDate').' '; + print $form->select_date(); + if ($mysoc->isInEEC()) { + print ''; + print ''; + } else { + print '' . $langs->trans("CreateAll") . "\n"; + } -if ($nb) -{ - if ($pricetowithdraw) - { - if ($mysoc->isInEEC()) - { - print ''.$langs->trans("CreateForSepaFRST")."\n"; - print ''.$langs->trans("CreateForSepaRCUR")."\n"; } else { - print ''.$langs->trans("CreateAll")."\n"; - } - } - else - { if ($mysoc->isInEEC()) { print ''.$langs->trans("CreateForSepaFRST")."\n"; @@ -319,8 +319,6 @@ if ($result) print ''.$langs->trans("Date").''.$langs->trans("Amount").''; print ''; - $var=True; - while ($i < min($num,$limit)) { $obj = $db->fetch_object($result); diff --git a/htdocs/compta/prelevement/demandes.php b/htdocs/compta/prelevement/demandes.php index 04ec746d7f6..d20f92cb188 100644 --- a/htdocs/compta/prelevement/demandes.php +++ b/htdocs/compta/prelevement/demandes.php @@ -30,10 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("withdrawals"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies')); // Security check $socid = GETPOST('socid','int'); @@ -129,8 +127,6 @@ if ($resql) print ''; print ''; - $var = True; - $users = array(); while ($i < min($num,$limit)) diff --git a/htdocs/compta/prelevement/factures.php b/htdocs/compta/prelevement/factures.php index 64811c7604a..2eabd64873d 100644 --- a/htdocs/compta/prelevement/factures.php +++ b/htdocs/compta/prelevement/factures.php @@ -31,11 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/rejetprelevement.class require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("companies"); -$langs->load('withdrawals'); -$langs->load('bills'); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'companies', 'withdrawals', 'bills')); // Securite acces client if ($user->societe_id > 0) accessforbidden(); @@ -170,6 +167,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1,$offset); diff --git a/htdocs/compta/prelevement/fiche-rejet.php b/htdocs/compta/prelevement/fiche-rejet.php index 82431e3bdd2..113153bc896 100644 --- a/htdocs/compta/prelevement/fiche-rejet.php +++ b/htdocs/compta/prelevement/fiche-rejet.php @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/rejetprelevement.class require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +// Load translation files required by the page $langs->loadLangs(array("banks","categories",'withdrawals','bills')); // Securite acces client @@ -169,6 +170,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); diff --git a/htdocs/compta/prelevement/fiche-stat.php b/htdocs/compta/prelevement/fiche-stat.php index f0e335da5cf..c126212f17c 100644 --- a/htdocs/compta/prelevement/fiche-stat.php +++ b/htdocs/compta/prelevement/fiche-stat.php @@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.p require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +// Load translation files required by the page $langs->loadLangs(array("banks","categories",'withdrawals','bills')); // Security check diff --git a/htdocs/compta/prelevement/index.php b/htdocs/compta/prelevement/index.php index 271ce4da7fe..de99b56eb19 100644 --- a/htdocs/compta/prelevement/index.php +++ b/htdocs/compta/prelevement/index.php @@ -33,9 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("withdrawals"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'withdrawals')); // Security check $socid = GETPOST('socid','int'); @@ -71,7 +70,6 @@ print '
'; $thirdpartystatic=new Societe($db); $invoicestatic=new Facture($db); $bprev = new BonPrelevement($db); -$var=true; print ''; print ''; @@ -117,7 +115,6 @@ if ($resql) print ''; if ($num) { - $var = True; while ($i < $num && $i < 20) { $obj = $db->fetch_object($resql); @@ -184,7 +181,6 @@ if ($result) { $num = $db->num_rows($result); $i = 0; - $var=True; print"\n\n"; print '
'.$langs->trans("Statistics").'
'.$langs->trans("InvoiceWaitingWithdraw").' ('.$num.')
'; diff --git a/htdocs/compta/prelevement/ligne.php b/htdocs/compta/prelevement/ligne.php index 20ac3d18082..721cf62bcd7 100644 --- a/htdocs/compta/prelevement/ligne.php +++ b/htdocs/compta/prelevement/ligne.php @@ -31,15 +31,12 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/rejetprelevement.class require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadlangs(array('banks', 'categories', 'bills', 'withdrawals')); // Security check if ($user->societe_id > 0) accessforbidden(); -$langs->load("bills"); -$langs->load("withdrawals"); - // Get supervariables $action = GETPOST('action','alpha'); $id = GETPOST('id','int'); diff --git a/htdocs/compta/prelevement/list.php b/htdocs/compta/prelevement/list.php index ff6fe4e109c..8d657f00221 100644 --- a/htdocs/compta/prelevement/list.php +++ b/htdocs/compta/prelevement/list.php @@ -29,10 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.p require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("withdrawals"); -$langs->load("companies"); -$langs->load("categories"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'withdrawals', 'companies', 'categories')); // Security check $socid = GETPOST('socid','int'); @@ -40,7 +38,7 @@ if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'prelevement','','','bons'); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST('sortfield','alpha'); $sortorder = GETPOST('sortorder','alpha'); $page = GETPOST('page','int'); @@ -111,6 +109,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1,$offset); diff --git a/htdocs/compta/prelevement/rejets.php b/htdocs/compta/prelevement/rejets.php index 3c18207f451..c8812bba1a9 100644 --- a/htdocs/compta/prelevement/rejets.php +++ b/htdocs/compta/prelevement/rejets.php @@ -30,10 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("withdrawals"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies')); // Security check $socid = GETPOST('socid','int'); diff --git a/htdocs/compta/prelevement/stats.php b/htdocs/compta/prelevement/stats.php index 406c2303b6a..20d213e820b 100644 --- a/htdocs/compta/prelevement/stats.php +++ b/htdocs/compta/prelevement/stats.php @@ -28,10 +28,8 @@ require('../../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; -$langs->load("banks"); -$langs->load("categories"); -$langs->load("withdrawals"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies')); // Security check $socid = GETPOST('socid','int'); diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php index dd320ebbeec..3a22666e2f7 100644 --- a/htdocs/compta/recap-compta.php +++ b/htdocs/compta/recap-compta.php @@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +// Load translation files required by the page $langs->load("companies"); if (! empty($conf->facture->enabled)) $langs->load("bills"); @@ -128,7 +129,6 @@ if ($id > 0) $resql=$db->query($sql); if ($resql) { - $var=true; $num = $db->num_rows($resql); // Boucle sur chaque facture diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index b717b58edd2..c9e32b9a97f 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -36,6 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; +// Load translation files required by the page $langs->loadLangs(array('compta','bills','donation','salaries','accountancy')); $date_startmonth=GETPOST('date_startmonth','int'); @@ -822,7 +823,7 @@ else $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('expensereport').")"; $sql.= " AND p.fk_statut>=5"; @@ -906,7 +907,7 @@ 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.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('donation').")"; $sql.= " AND fk_statut >= 2"; } diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index 1bbb8eca2cf..fbbc7a36eef 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -30,6 +30,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +// Load translation files required by the page $langs->loadLangs(array('compta','bills','donation','salaries')); $date_startmonth=GETPOST('date_startmonth','int'); @@ -90,7 +91,7 @@ $tmps=dol_getdate($date_start); $year_start = $tmps['year']; $tmpe=dol_getdate($date_end); $year_end = $tmpe['year']; -$nbofyear = ($year_end - $start_year) + 1; +$nbofyear = ($year_end - $year_start) + 1; //var_dump("year_start=".$year_start." year_end=".$year_end." nbofyear=".$nbofyear." date_start=".dol_print_date($date_start, 'dayhour')." date_end=".dol_print_date($date_end, 'dayhour')); @@ -692,7 +693,7 @@ if (! empty($conf->expensereport->enabled) && ($modecompta == 'CREANCES-DETTES' $sql.= " FROM ".MAIN_DB_PREFIX."expensereport as p"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user_author"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."payment_expensereport as pe ON pe.fk_expensereport = p.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('expensereport').")"; $sql.= " AND p.fk_statut>=5"; @@ -755,7 +756,7 @@ if (! empty($conf->don->enabled) && ($modecompta == 'CREANCES-DETTES' || $modeco $sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(pe.datep,'%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.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id AND c.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON pe.fk_typepayment = c.id"; $sql.= " WHERE p.entity IN (".getEntity('donation').")"; $sql.= " AND fk_statut >= 2"; if (! empty($date_start) && ! empty($date_end)) @@ -840,9 +841,13 @@ if (! empty($conf->accounting->enabled) && ($modecompta == 'BOOKKEEPING')) $obj = $db->fetch_object($result); if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0; - $encaiss[$obj->dm] += $obj->debit; + if (! isset($decaiss[$obj->dm])) $decaiss[$obj->dm]=0; + $encaiss[$obj->dm] += $obj->credit; + $decaiss[$obj->dm] += $obj->debit; if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0; + if (! isset($decaiss_ttc[$obj->dm])) $decaiss_ttc[$obj->dm]=0; $encaiss_ttc[$obj->dm] += 0; + $decaiss_ttc[$obj->dm] += 0; $i++; } diff --git a/htdocs/compta/resultat/result.php b/htdocs/compta/resultat/result.php index 7854f6656ed..23c7e91b989 100644 --- a/htdocs/compta/resultat/result.php +++ b/htdocs/compta/resultat/result.php @@ -30,6 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancycategory.class.php'; +// Load translation files required by the page $langs->loadLangs(array('compta','bills','donation','salaries','accountancy')); $error = 0; @@ -537,4 +538,4 @@ print "
"; print '
'; llxFooter(); -$db->close(); \ No newline at end of file +$db->close(); diff --git a/htdocs/compta/salaries/card.php b/htdocs/compta/salaries/card.php index 608b5a737b0..45fee127642 100644 --- a/htdocs/compta/salaries/card.php +++ b/htdocs/compta/salaries/card.php @@ -1,8 +1,8 @@ * Copyright (C) 2014 Laurent Destailleur - * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2015 Charlie BENKE + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2015 Charlie BENKE * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,9 +19,9 @@ */ /** - * \file htdocs/compta/salaries/card.php - * \ingroup salaries - * \brief Page of salaries payments + * \file htdocs/compta/salaries/card.php + * \ingroup salaries + * \brief Page of salaries payments */ require '../../main.inc.php'; @@ -30,13 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php'; - -$langs->load("compta"); -$langs->load("banks"); -$langs->load("bills"); -$langs->load("users"); -$langs->load("salaries"); -$langs->load('hrm'); +// Load translation files required by the page +$langs->loadLangs(array("compta","banks","bills","users","salaries","hrm")); $id=GETPOST("id",'int'); $action=GETPOST('action','aZ09'); @@ -73,7 +68,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $dateep=dol_mktime(12,0,0, $_POST["dateepmonth"], $_POST["dateepday"], $_POST["dateepyear"]); if (empty($datev)) $datev=$datep; - $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement'); + $type_payment = dol_getIdFromCode($db, GETPOST("paymenttype", 'alpha'), 'c_paiement', 'code', 'id', 1); $object->accountid=GETPOST("accountid") > 0 ? GETPOST("accountid","int") : 0; $object->fk_user=GETPOST("fk_user") > 0 ? GETPOST("fk_user","int") : 0; diff --git a/htdocs/compta/salaries/class/paymentsalary.class.php b/htdocs/compta/salaries/class/paymentsalary.class.php index eab661c6614..3a3f34b85b4 100644 --- a/htdocs/compta/salaries/class/paymentsalary.class.php +++ b/htdocs/compta/salaries/class/paymentsalary.class.php @@ -31,9 +31,9 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; */ class PaymentSalary extends CommonObject { - //public $element='payment_salary'; //!< Id that identify managed objects - //public $table_element='payment_salary'; //!< Name of table without prefix where object is stored - public $picto='payment'; + public $element='payment_salary'; //!< Id that identify managed objects + public $table_element='payment_salary'; //!< Name of table without prefix where object is stored + public $picto='payment'; public $tms; public $fk_user; @@ -388,7 +388,11 @@ class PaymentSalary extends CommonObject -abs($this->amount), $this->num_payment, '', - $user + $user, + '', + '', + '', + $this->datev ); // Update fk_bank into llx_paiement. diff --git a/htdocs/compta/salaries/class/salariesstats.class.php b/htdocs/compta/salaries/class/salariesstats.class.php new file mode 100644 index 00000000000..647dc27f4a5 --- /dev/null +++ b/htdocs/compta/salaries/class/salariesstats.class.php @@ -0,0 +1,164 @@ + + * Copyright (c) 2018 Fidesio + * + * 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/salaries/class/salariesstats.class.php + * \ingroup salaries + * \brief Fichier de la classe de gestion des stats des salaires + */ +include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; +include_once DOL_DOCUMENT_ROOT . '/compta/salaries/class/paymentsalary.class.php'; + +/** + * Classe permettant la gestion des stats des salaires + */ +class SalariesStats extends Stats +{ + public $table_element; + + var $socid; + var $userid; + + var $from; + var $field; + var $where; + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param int $socid Id third party + * @param mixed $userid Id user for filter or array of user ids + * @return void + */ + function __construct($db, $socid=0, $userid=0) + { + global $conf; + + $this->db = $db; + $this->socid = $socid; + $this->userid = $userid; + + $object=new PaymentSalary($this->db); + $this->from = MAIN_DB_PREFIX.$object->table_element; + $this->field='amount'; + + $this->where.= " entity = ".$conf->entity; + if ($this->socid) + { + $this->where.=" AND fk_soc = ".$this->socid; + } + if (is_array($this->userid) && count($this->userid) > 0) $this->where.=' AND fk_user IN ('.join(',',$this->userid).')'; + else if ($this->userid > 0) $this->where.=' AND fk_user = '.$this->userid; + } + + + /** + * Return the number of salary by year + * + * @return array Array of values + */ + function getNbByYear() + { + $sql = "SELECT YEAR(datep) as dm, count(*)"; + $sql.= " FROM ".$this->from; + $sql.= " GROUP BY dm DESC"; + $sql.= " WHERE ".$this->where; + + return $this->_getNbByYear($sql); + } + + + /** + * Return the number of salary by month, for a given year + * + * @param string $year Year to scan + * @param int $format 0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month + * @return array Array of values + */ + function getNbByMonth($year, $format=0) + { + $sql = "SELECT MONTH(datep) as dm, count(*)"; + $sql.= " FROM ".$this->from; + $sql.= " WHERE YEAR(datep) = ".$year; + $sql.= " AND ".$this->where; + $sql.= " GROUP BY dm"; + $sql.= $this->db->order('dm','DESC'); + + $res=$this->_getNbByMonth($year, $sql, $format); + //var_dump($res);print '
'; + return $res; + } + + + /** + * Return amount of salaries by month for a given year + * + * @param int $year Year to scan + * @param int $format 0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month + * @return array Array of values + */ + function getAmountByMonth($year, $format=0) + { + $sql = "SELECT date_format(datep,'%m') as dm, sum(".$this->field.")"; + $sql.= " FROM ".$this->from; + $sql.= " WHERE date_format(datep,'%Y') = '".$year."'"; + $sql.= " AND ".$this->where; + $sql.= " GROUP BY dm"; + $sql.= $this->db->order('dm','DESC'); + + $res=$this->_getAmountByMonth($year, $sql, $format); + //var_dump($res);print '
'; + return $res; + } + + /** + * Return average amount + * + * @param int $year Year to scan + * @return array Array of values + */ + function getAverageByMonth($year) + { + $sql = "SELECT date_format(datep,'%m') as dm, avg(".$this->field.")"; + $sql.= " FROM ".$this->from; + $sql.= " WHERE date_format(datep,'%Y') = '".$year."'"; + $sql.= " AND ".$this->where; + $sql.= " GROUP BY dm"; + $sql.= $this->db->order('dm','DESC'); + + return $this->_getAverageByMonth($year, $sql); + } + + /** + * Return nb, total and average + * + * @return array Array of values + */ + function getAllByYear() + { + $sql = "SELECT date_format(datep,'%Y') as year, count(*) as nb, sum(".$this->field.") as total, avg(".$this->field.") as avg"; + $sql.= " FROM ".$this->from; + $sql.= " WHERE ".$this->where; + $sql.= " GROUP BY year"; + $sql.= $this->db->order('year','DESC'); + + return $this->_getAllByYear($sql); + } +} + diff --git a/htdocs/compta/salaries/document.php b/htdocs/compta/salaries/document.php index 03cef9c07e8..99c34f60815 100644 --- a/htdocs/compta/salaries/document.php +++ b/htdocs/compta/salaries/document.php @@ -35,11 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; -$langs->load("other"); -$langs->load("users"); -$langs->load("salaries"); -$langs->load('hrm'); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","users","salaries","hrm")); $id = GETPOST('id','int'); $ref = GETPOST('ref', 'alpha'); @@ -118,7 +115,7 @@ if ($object->id) print ''; print ''; - print ''; + print ''; print '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
'; print '
'; diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php index 47cafad0f0a..0b70275654f 100644 --- a/htdocs/compta/salaries/index.php +++ b/htdocs/compta/salaries/index.php @@ -28,17 +28,15 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; -$langs->load("compta"); -$langs->load("salaries"); -$langs->load("bills"); -$langs->load("hrm"); +// Load translation files required by the page +$langs->loadLangs(array("compta","salaries","bills","hrm")); // Security check $socid = GETPOST("socid","int"); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'salaries', '', '', ''); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $search_ref = GETPOST('search_ref','int'); $search_user = GETPOST('search_user','alpha'); $search_label = GETPOST('search_label','alpha'); @@ -52,8 +50,8 @@ if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="s.datep"; -if (! $sortorder) $sortorder="DESC"; +if (! $sortfield) $sortfield="s.datep,s.rowid"; +if (! $sortorder) $sortorder="DESC,DESC"; $optioncss = GETPOST('optioncss','alpha'); $filtre=$_GET["filtre"]; @@ -105,7 +103,7 @@ $sql.= " s.rowid, s.fk_user, s.amount, s.salary, s.label, s.datep as datep, s.da $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel,"; $sql.= " pst.code as payment_code"; $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id AND pst.entity IN (".getEntity('c_paiement').")"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid,"; $sql.= " ".MAIN_DB_PREFIX."user as u"; @@ -142,7 +140,6 @@ if ($result) $num = $db->num_rows($result); $i = 0; $total = 0 ; - $var=true; $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; @@ -150,7 +147,15 @@ if ($result) if ($typeid) $param.='&typeid='.$typeid; if ($optioncss != '') $param.='&optioncss='.$optioncss; - print ''; + $newcardbutton=''; + if ($user->rights->salaries->payment->write) + { + $newcardbutton=''.$langs->trans('NewSalaryPayment').''; + $newcardbutton.= ''; + $newcardbutton.= ''; + } + + print ''; if ($optioncss != '') print ''; print ''; print ''; @@ -159,7 +164,7 @@ if ($result) print ''; print ''; - print_barre_liste($langs->trans("SalariesPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); + print_barre_liste($langs->trans("SalariesPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, $newcardbutton, '', $limit); print '
'; print ''."\n"; @@ -179,7 +184,7 @@ if ($result) print ''; // Type print ''; // Account if (! empty($conf->banque->enabled)) @@ -200,7 +205,7 @@ if ($result) print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"s.rowid","",$param,"",$sortfield,$sortorder); print_liste_field_titre("Employee",$_SERVER["PHP_SELF"],"u.rowid","",$param,"",$sortfield,$sortorder); print_liste_field_titre("Label",$_SERVER["PHP_SELF"],"s.label","",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"s.datep","",$param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"s.datep,s.rowid","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("PaymentMode",$_SERVER["PHP_SELF"],"type","",$param,'align="left"',$sortfield,$sortorder); if (! empty($conf->banque->enabled)) print_liste_field_titre("BankAccount",$_SERVER["PHP_SELF"],"ba.label","",$param,"",$sortfield,$sortorder); print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"s.amount","",$param,'align="right"',$sortfield,$sortorder); diff --git a/htdocs/compta/salaries/info.php b/htdocs/compta/salaries/info.php index ddb79845748..467abe3618c 100644 --- a/htdocs/compta/salaries/info.php +++ b/htdocs/compta/salaries/info.php @@ -28,11 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -$langs->load("compta"); -$langs->load("bills"); -$langs->load("users"); -$langs->load("salaries"); -$langs->load('hrm'); +// Load translation files required by the page +$langs->loadLangs(array("compta","bills","users","salaries","hrm")); $id=GETPOST('id','int'); $action=GETPOST('action','aZ09'); diff --git a/htdocs/compta/salaries/stats/index.php b/htdocs/compta/salaries/stats/index.php new file mode 100644 index 00000000000..3e6fd56a266 --- /dev/null +++ b/htdocs/compta/salaries/stats/index.php @@ -0,0 +1,294 @@ + + * Copyright (C) 2018 Fidesio + * + * 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/salaries/stats/index.php + * \ingroup salaries + * \brief Page for statistics of module salaries + */ + +require '../../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/salariesstats.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("salaries","companies")); + +$WIDTH=DolGraph::getDefaultGraphSizeForStats('width'); +$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height'); + +$userid=GETPOST('userid','int'); if ($userid < 0) $userid=0; +$socid=GETPOST('socid','int'); if ($socid < 0) $socid=0; +$id = GETPOST('id','int'); + +// Security check +$socid = GETPOST("socid","int"); +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'salaries', '', '', ''); + +// Other security check +$childids = $user->getAllChildIds(); +$childids[]=$user->id; +if ($userid > 0) +{ + if (empty($user->rights->salaries->payment->readall) && ! in_array($userid, $childids)) + { + accessforbidden(); + exit; + } +} + +$nowyear=strftime("%Y", dol_now()); +$year = GETPOST('year')>0?GETPOST('year'):$nowyear; +//$startyear=$year-2; +$startyear=$year-1; +$endyear=$year; + + +/* + * View + */ + +$form=new Form($db); + + +llxHeader(); + +$title=$langs->trans("SalariesStatistics"); +$dir=$conf->salaries->dir_temp; + +print load_fiche_titre($title, $mesg); + +dol_mkdir($dir); + +$useridtofilter=$userid; // Filter from parameters +if (empty($useridtofilter)) +{ + $useridtofilter=$childids; + if (! empty($user->rights->salaries->payment->readall)) $useridtofilter=0; +} + +$stats = new SalariesStats($db, $socid, $useridtofilter); + + +// Build graphic number of object +// $data = array(array('Lib',val1,val2,val3),...) +//print "$endyear, $startyear"; +$data = $stats->getNbByMonthWithPrevYear($endyear,$startyear); +//var_dump($data); + +$filenamenb = $dir."/salariesnbinyear-".$year.".png"; +$fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&file=salariesnbinyear-'.$year.'.png'; + +$px1 = new DolGraph(); +$mesg = $px1->isGraphKo(); +if (! $mesg) +{ + $px1->SetData($data); + $px1->SetPrecisionY(0); + $i=$startyear;$legend=array(); + while ($i <= $endyear) + { + $legend[]=$i; + $i++; + } + $px1->SetLegend($legend); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + $px1->SetWidth($WIDTH); + $px1->SetHeight($HEIGHT); + $px1->SetYLabel($langs->trans("Number")); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetPrecisionY(0); + $px1->mode='depth'; + $px1->SetTitle($langs->trans("NumberByMonth")); + + $px1->draw($filenamenb,$fileurlnb); +} + +// Build graphic amount of object +$data = $stats->getAmountByMonthWithPrevYear($endyear,$startyear); +//var_dump($data); +// $data = array(array('Lib',val1,val2,val3),...) + +$filenameamount = $dir."/salariesamountinyear-".$year.".png"; +$fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&file=salariesamountinyear-'.$year.'.png'; + +$px2 = new DolGraph(); +$mesg = $px2->isGraphKo(); +if (! $mesg) +{ + $px2->SetData($data); + $i=$startyear;$legend=array(); + while ($i <= $endyear) + { + $legend[]=$i; + $i++; + } + $px2->SetLegend($legend); + $px2->SetMaxValue($px2->GetCeilMaxValue()); + $px2->SetMinValue(min(0,$px2->GetFloorMinValue())); + $px2->SetWidth($WIDTH); + $px2->SetHeight($HEIGHT); + $px2->SetYLabel($langs->trans("Amount")); + $px2->SetShading(3); + $px2->SetHorizTickIncrement(1); + $px2->SetPrecisionY(0); + $px2->mode='depth'; + $px2->SetTitle($langs->trans("AmountTotal")); + + $px2->draw($filenameamount,$fileurlamount); +} + + +$data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); + +$filename_avg = $dir."/salariesaverageinyear-".$year.".png"; +$fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=salariesstats&file=salariesaverageinyear-'.$year.'.png'; + +$px3 = new DolGraph(); +$mesg = $px3->isGraphKo(); +if (! $mesg) +{ + $px3->SetData($data); + $i = $startyear;$legend=array(); + while ($i <= $endyear) + { + $legend[]=$i; + $i++; + } + $px3->SetLegend($legend); + $px3->SetYLabel($langs->trans("AmountAverage")); + $px3->SetMaxValue($px3->GetCeilMaxValue()); + $px3->SetMinValue($px3->GetFloorMinValue()); + $px3->SetWidth($WIDTH); + $px3->SetHeight($HEIGHT); + $px3->SetShading(3); + $px3->SetHorizTickIncrement(1); + $px3->SetPrecisionY(0); + $px3->mode='depth'; + $px3->SetTitle($langs->trans("AmountAverage")); + + $px3->draw($filename_avg,$fileurl_avg); +} + + +// Show array +$data = $stats->getAllByYear(); +$arrayyears=array(); +foreach($data as $val) { + $arrayyears[$val['year']]=$val['year']; +} +if (! count($arrayyears)) $arrayyears[$nowyear]=$nowyear; + + +$h=0; +$head = array(); +$head[$h][0] = DOL_URL_ROOT . '/compta/salaries/stats/index.php'; +$head[$h][1] = $langs->trans("ByMonthYear"); +$head[$h][2] = 'byyear'; +$h++; + +complete_head_from_modules($conf,$langs,null,$head,$h,'trip_stats'); + +dol_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1); + + +print '
'; + + +// Show filter box +print ''; +print '
 '; - $form->select_types_paiements($typeid,'typeid','',0,0,1,16); + $form->select_types_paiements($typeid,'typeid','',0,1,1,16); print '
'; +print ''; +// User +print ''; +// Year +print ''; +print ''; +print '
'.$langs->trans("Filter").'
'.$langs->trans("User").''; +print $form->select_dolusers($userid, 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); +print '
'.$langs->trans("Year").''; +if (! in_array($year,$arrayyears)) $arrayyears[$year]=$year; +arsort($arrayyears); +print $form->selectarray('year',$arrayyears,$year,0); +print '
'; +print ''; +print '

'; + +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$oldyear=0; +foreach ($data as $val) +{ + $year = $val['year']; + while ($year && $oldyear > $year+1) + { + // If we have empty year + $oldyear--; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $oldyear=$year; +} + +print '
'.$langs->trans("Year").''.$langs->trans("Number").''.$langs->trans("AmountTotal").''.$langs->trans("AmountAverage").'
'.$oldyear.'000
'.$year.''.$val['nb'].''.price(price2num($val['total'],'MT'),1).''.price(price2num($val['avg'],'MT'),1).'
'; + + +print '
'; + + +// Show graphs +print '
'; +if ($mesg) { print $mesg; } +else { + print $px1->show(); + print "
\n"; + print $px2->show(); + print "
\n"; + print $px3->show(); +} +print '
'; + + +print '
'; +print '
'; + + +dol_fiche_end(); + + +llxFooter(); + +$db->close(); diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 23e3494a25d..101a934a524 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; @@ -38,8 +39,8 @@ if (! empty($conf->accounting->enabled)) { require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; } -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); $id=GETPOST('id','int'); $action=GETPOST('action','aZ09'); @@ -241,11 +242,12 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->tax->char { $object->paye = 0; $object->id = $object->ref = null; + $object->lib = $langs->trans("CopyOf").' '.$object->lib; - if(GETPOST('clone_for_next_month') != '') { - - $object->date_ech = strtotime('+1month', $object->date_ech); - $object->periode = strtotime('+1month', $object->periode); + if (GETPOST('clone_for_next_month') != '') + { + $object->date_ech = dol_time_plus_duree($object->date_ech, 1, 'm'); + $object->periode = dol_time_plus_duree($object->periode, 1, 'm'); } if ($object->check()) @@ -327,13 +329,23 @@ if ($action == 'create') // Date end period print ''; print ''; - print $langs->trans("PeriodEndDate"); + print $form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")); print ''; print ''; print $form->select_date(! empty($dateperiod)?$dateperiod:'-1', 'period', 0, 0, 0, 'charge', 1); print ''; print ''; + // Date due + print ''; + print ''; + print $langs->trans("DateDue"); + print ''; + print ''; + print $form->select_date(! empty($dateech)?$dateech:'-1', 'ech', 0, 0, 0, 'charge', 1); + print ''; + print "\n"; + // Amount print ''; print ''; @@ -370,16 +382,6 @@ if ($action == 'create') print ''; } - // Date due - print ''; - print ''; - print $langs->trans("DateDue"); - print ''; - print ''; - print $form->select_date(! empty($dateech)?$dateech:'-1', 'ech', 0, 0, 0, 'charge', 1); - print ''; - print "\n"; - print ''; dol_fiche_end(); @@ -496,7 +498,7 @@ if ($id > 0) print ""; // Period end date - print "".$langs->trans("PeriodEndDate").""; + print "".$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).""; print ""; if ($action == 'edit') { @@ -586,7 +588,7 @@ if ($id > 0) $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON p.fk_bank = b.rowid'; $sql.= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON b.fk_account = ba.rowid'; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepaiement = c.id AND c.entity IN (" . getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepaiement = c.id"; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " WHERE p.fk_charge = ".$id; $sql.= " AND p.fk_charge = cs.rowid"; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index 61728562d2e..65e6085a650 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -83,7 +83,7 @@ class ChargeSociales extends CommonObject $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id AND p.entity IN ('.getEntity('c_paiement').')'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON cs.fk_mode_reglement = p.id'; $sql.= ' WHERE cs.entity IN ('.getEntity('tax').')'; if ($ref) $sql.= " AND cs.rowid = ".$ref; else $sql.= " AND cs.rowid = ".$id; @@ -156,6 +156,7 @@ class ChargeSociales extends CommonObject function create($user) { global $conf; + $error=0; $now=dol_now(); @@ -191,8 +192,17 @@ class ChargeSociales extends CommonObject $this->id=$this->db->last_insert_id(MAIN_DB_PREFIX."chargesociales"); //dol_syslog("ChargesSociales::create this->id=".$this->id); - $this->db->commit(); - return $this->id; + $result=$this->call_trigger('SOCIALCONTRIBUTION_CREATE',$user); + if ($result < 0) $error++; + + if(empty($error)) { + $this->db->commit(); + return $this->id; + } + else { + $this->db->rollback(); + return -1*$error; + } } else { @@ -454,21 +464,58 @@ class ChargeSociales extends CommonObject /** * Return a link to the object card (with optionaly the picto) * - * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) - * @param int $maxlen Max length of label - * @param int $notooltip 1=Disable tooltip - * @return string String with link + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param int $maxlen Max length of label + * @param int $notooltip 1=Disable tooltip + * @param int $short 1=Return just URL + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with link */ - function getNomUrl($withpicto=0, $maxlen=0, $notooltip=0) + function getNomUrl($withpicto=0, $maxlen=0, $notooltip=0, $short=0, $save_lastsearch_value=-1) { - global $langs; + global $langs, $conf, $user, $form; + + if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips $result=''; - if (empty($this->ref)) $this->ref=$this->lib; - $label = $langs->trans("ShowSocialContribution").': '.$this->ref; + $url = DOL_URL_ROOT.'/compta/sociales/card.php?id='.$this->id; - $linkstart = ''; + if ($short) return $url; + + if ($option !== 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1; + if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1'; + } + + + if (empty($this->ref)) $this->ref=$this->lib; + + $label = ''.$langs->trans("ShowSocialContribution").''; + if (! empty($this->ref)) + $label .= '
'.$langs->trans('Ref') . ': ' . $this->ref; + if (! empty($this->lib)) + $label .= '
'.$langs->trans('Label') . ': ' . $this->lib; + if (! empty($this->type_libelle)) + $label .= '
'.$langs->trans('Type') . ': ' . $this->type_libelle; + + $linkclose=''; + if (empty($notooltip) && $user->rights->facture->lire) + { + if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label=$langs->trans("ShowSocialContribution"); + $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose.=' class="classfortooltip"'; + } + + $linkstart='
'; $linkend=''; $result .= $linkstart; diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 60a1a647661..ba9c671f755 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -164,6 +164,9 @@ class PaymentSocialContribution extends CommonObject } + $result = $this->call_trigger('PAYMENTSOCIALCONTRIBUTION_CREATE',$user); + if($result < 0) $error++; + if ($totalamount != 0 && ! $error) { $this->amount=$totalamount; @@ -203,7 +206,7 @@ class PaymentSocialContribution extends CommonObject $sql.= " t.fk_user_modif,"; $sql.= " pt.code as type_code, pt.libelle as type_libelle,"; $sql.= ' b.fk_account'; - $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepaiement = pt.id AND pt.entity IN (" . getEntity('c_paiement') . ")"; + $sql.= " FROM ".MAIN_DB_PREFIX."paiementcharge as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepaiement = pt.id"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id; // TODO link on entity of tax; diff --git a/htdocs/compta/sociales/document.php b/htdocs/compta/sociales/document.php index 0bf1e7f6f13..490dbf3a1fe 100644 --- a/htdocs/compta/sociales/document.php +++ b/htdocs/compta/sociales/document.php @@ -39,10 +39,8 @@ if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } -$langs->load("other"); -$langs->load("companies"); -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('other', 'companies', 'compta', 'bills')); $id = GETPOST('id','int'); $action = GETPOST('action','aZ09'); @@ -150,7 +148,7 @@ if ($object->id) print ''; print ''; - print ''; + print ''; print '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
'; print ''; diff --git a/htdocs/compta/sociales/index.php b/htdocs/compta/sociales/index.php index 281a0afb377..bd323c972fe 100644 --- a/htdocs/compta/sociales/index.php +++ b/htdocs/compta/sociales/index.php @@ -28,9 +28,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; -$langs->load("compta"); -$langs->load("banks"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'banks', 'bills')); // Security check $socid = isset($_GET["socid"])?$_GET["socid"]:''; @@ -42,7 +41,7 @@ $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; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -138,7 +137,6 @@ if ($resql) { $num = $db->num_rows($resql); $i = 0; - $var=true; $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; @@ -146,6 +144,14 @@ if ($resql) if ($year) $param.='&year='.$year; if ($typeid) $param.='&typeid='.$typeid; + $newcardbutton=''; + if($user->rights->tax->charges->creer) + { + $newcardbutton=''.$langs->trans('MenuNewSocialContribution'); + $newcardbutton.= ''; + $newcardbutton.= ''; + } + print '
'; if ($optioncss != '') print ''; print ''; @@ -158,11 +164,11 @@ if ($resql) if ($year) { $center=($year?"".img_previous()." ".$langs->trans("Year")." $year ".img_next()."":""); - print_barre_liste($langs->trans("SocialContributions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); + print_barre_liste($langs->trans("SocialContributions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $totalnboflines, 'title_accountancy.png', 0, $newcardbutton, '', $limit); } else { - print_barre_liste($langs->trans("SocialContributions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit); + print_barre_liste($langs->trans("SocialContributions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'title_accountancy.png', 0, $newcardbutton, '', $limit); } if (empty($mysoc->country_id) && empty($mysoc->country_code)) @@ -181,10 +187,10 @@ if ($resql) print ''; // Ref print ''; - print ''; + print ''; print ''; // Label - print ''; + print ''; // Type print ''; $formsocialcontrib->select_type_socialcontrib($typeid,'typeid',1,0,0,'maxwidth100onsmartphone'); @@ -193,7 +199,7 @@ if ($resql) print ' '; // Amount print ''; - print ''; + print ''; print ''; print ' '; // Status @@ -225,13 +231,15 @@ if ($resql) { $obj = $db->fetch_object($resql); + $chargesociale_static->id=$obj->id; + $chargesociale_static->ref=$obj->id; + $chargesociale_static->lib=$obj->libelle; + $chargesociale_static->type_libelle=$obj->type_lib; + print ''; // Ref print ''; - $chargesociale_static->id=$obj->id; - $chargesociale_static->lib=$obj->id; - $chargesociale_static->ref=$obj->id; print $chargesociale_static->getNomUrl(1,'20'); print ''; diff --git a/htdocs/compta/sociales/info.php b/htdocs/compta/sociales/info.php index dfa6439a3f4..1827c1597f8 100644 --- a/htdocs/compta/sociales/info.php +++ b/htdocs/compta/sociales/info.php @@ -31,8 +31,8 @@ if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); $id=GETPOST('id','int'); $action=GETPOST('action','aZ09'); diff --git a/htdocs/compta/sociales/payments.php b/htdocs/compta/sociales/payments.php index a7c388a26e6..3b7f68f8c83 100644 --- a/htdocs/compta/sociales/payments.php +++ b/htdocs/compta/sociales/payments.php @@ -33,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); // Security check if ($user->societe_id) $socid=$user->societe_id; @@ -45,7 +45,7 @@ $year=GETPOST("year",'int'); $filtre=GETPOST("filtre",'alpha'); if (! $year && $mode != 'sconly') { $year=date("Y", time()); } -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -133,7 +133,7 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs,"; $sql.= " ".MAIN_DB_PREFIX."paiementcharge as pc"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id AND pct.entity IN (".getEntity('c_paiement').")"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON pc.fk_typepaiement = pct.id"; $sql.= " WHERE cs.fk_type = c.id AND pc.fk_charge = cs.rowid"; $sql.= " AND cs.entity = ".$conf->entity; if ($year > 0) @@ -158,12 +158,10 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $total = 0; $totalnb = 0; $totalpaye = 0; - $var=true; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); - $var = !$var; print ''; // Ref payment $payment_sc_static->id=$obj->pid; @@ -253,14 +251,13 @@ if (! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"pv.datev","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"pv.amount","",$param,'align="right"',$sortfield,$sortorder); print "\n"; - $var=1; + while ($i < $num) { $obj = $db->fetch_object($result); $total = $total + $obj->amount; - print ''; print ''.dol_print_date($db->jdate($obj->dm),'day').''."\n"; @@ -355,14 +352,13 @@ while($j<$numlt) print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"pv.datep","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"pv.amount","",$param,'align="right"',$sortfield,$sortorder); print "\n"; - $var=1; + while ($i < $num) { $obj = $db->fetch_object($result); $total = $total + $obj->amount; - print ''; print ''.dol_print_date($db->jdate($obj->dm),'day').''."\n"; @@ -437,14 +433,13 @@ if (! empty($conf->salaries->enabled) && $user->rights->salaries->read) print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"s.datep","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("PayedByThisPayment",$_SERVER["PHP_SELF"],"s.amount","",$param,'align="right"',$sortfield,$sortorder); print "\n"; - $var=1; + while ($i < $num) { $obj = $db->fetch_object($result); $total = $total + $obj->amount; - print ''; print ''.dol_print_date($db->jdate($obj->dateep),'day').''."\n"; diff --git a/htdocs/compta/stats/byratecountry.php b/htdocs/compta/stats/byratecountry.php new file mode 100644 index 00000000000..2c43db42d13 --- /dev/null +++ b/htdocs/compta/stats/byratecountry.php @@ -0,0 +1,420 @@ + + * + * 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/stats/byratecountry.php + * \brief VAT by rate + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin","accountancy")); + +$modecompta = GETPOST('modecompta','alpha'); + +// Date range +$year=GETPOST("year",'int'); +$month=GETPOST("month",'int'); +if (empty($year)) +{ + $year_current = strftime("%Y",dol_now()); + $month_current = strftime("%m",dol_now()); + $year_start = $year_current; +} else { + $year_current = $year; + $month_current = strftime("%m",dol_now()); + $year_start = $year; +} +$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear")); +$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear")); +// Quarter +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $q=GETPOST("q","int"); + if (empty($q)) + { + // We define date_start and date_end + $month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); + $year_end=$year_start; + $month_end=$month_start; + if (! GETPOST("month")) // If month not forced + { + if (! GETPOST('year') && $month_start > $month_current) + { + $year_start--; + $year_end--; + } + $month_end=$month_start-1; + if ($month_end < 1) $month_end=12; + else $year_end++; + } + $date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false); + } + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + } +} + +// $date_start and $date_end are defined. We force $year_start and $nbofyear +$tmps=dol_getdate($date_start); +$year_start = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; + +$tmp_date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; +if ($tmp_date_end < $date_end || $date_end < $date_start) $date_end = $tmp_date_end; + +$min = price2num(GETPOST("min","alpha")); +if (empty($min)) $min = 0; + +// Define modetax (0 or 1) +// 0=normal, 1=option vat for services is on debit, 2=option on payments for products +$modetax = $conf->global->TAX_MODE; +if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int'); +if (empty($modetax)) $modetax=0; + +// Security check +$socid = GETPOST('socid','int'); +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'tax', '', '', 'charges'); + + + +/* + * View + */ + +$form=new Form($db); +$company_static=new Societe($db); +$invoice_customer=new Facture($db); +$invoice_supplier=new FactureFournisseur($db); +$expensereport=new ExpenseReport($db); +$product_static=new Product($db); +$payment_static=new Paiement($db); +$paymentfourn_static=new PaiementFourn($db); +$paymentexpensereport_static=new PaymentExpenseReport($db); + +$morequerystring=''; +$listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday'); +foreach ($listofparams as $param) +{ + if (GETPOST($param)!='') $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); +} + +llxHeader('',$langs->trans("TurnoverReport"),'','',0,0,'','',$morequerystring); + + +//print load_fiche_titre($langs->trans("VAT"),""); + +//$fsearch.='
'; +$fsearch.=' '; +$fsearch.=' '; +//$fsearch.=' '.$langs->trans("SalesTurnoverMinimum").': '; +//$fsearch.=' '; + + +// Show report header +$name=$langs->trans("xxx"); +$calcmode=''; +if ($modetax == 0) $calcmode=$langs->trans('OptionVATDefault'); +if ($modetax == 1) $calcmode=$langs->trans('OptionVATDebitOption'); +if ($modetax == 2) $calcmode=$langs->trans('OptionPaymentForProductAndServices'); +$calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; +// Set period +$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); +$prevyear=$year_start; $prevquarter=$q; +if ($prevquarter > 1) { + $prevquarter--; +} else { + $prevquarter=4; $prevyear--; +} +$nextyear=$year_start; $nextquarter=$q; +if ($nextquarter < 4) { + $nextquarter++; +} else { + $nextquarter=1; $nextyear++; +} +$description.=$fsearch; +$builddate=dol_now(); + +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description.=$langs->trans("RulesVATDueProducts"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description.=$langs->trans("RulesVATInProducts"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description.='
'.$langs->trans("RulesVATDueServices"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description.='
'.$langs->trans("RulesVATInServices"); +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description.='
'.$langs->trans("DepositsAreNotIncluded"); +} +if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue"); + +// Customers invoices +$elementcust=$langs->trans("CustomersInvoices"); +$productcust=$langs->trans("ProductOrService"); +$amountcust=$langs->trans("AmountHT"); + +// Suppliers invoices +$elementsup=$langs->trans("SuppliersInvoices"); +$productsup=$productcust; +$amountsup=$amountcust; +$namesup=$namecust; + + + +// TODO Report from bookkeeping not yet available, so we switch on report on business events +if ($modecompta=="BOOKKEEPING") $modecompta="CREANCES-DETTES"; +if ($modecompta=="BOOKKEEPINGCOLLECTED") $modecompta="RECETTES-DEPENSES"; + +// Show report header +if ($modecompta=="CREANCES-DETTES") { + $name=$langs->trans("Turnover").', '.$langs->trans("ByVatRate"); + $calcmode=$langs->trans("CalcModeDebt"); + //$calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + + $description=$langs->trans("RulesCADue"); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description.= $langs->trans("DepositsAreNotIncluded"); + } else { + $description.= $langs->trans("DepositsAreIncluded"); + } + + $builddate=dol_now(); +} +else if ($modecompta=="RECETTES-DEPENSES") +{ + $name=$langs->trans("TurnoverCollected").', '.$langs->trans("ByVatRate"); + $calcmode=$langs->trans("CalcModeEngagement"); + //$calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + + $description=$langs->trans("RulesCAIn"); + $description.= $langs->trans("DepositsAreIncluded"); + + $builddate=dol_now(); +} +else if ($modecompta=="BOOKKEEPING") +{ + + +} +else if ($modecompta=="BOOKKEEPINGCOLLECTED") +{ + + +} +$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); +if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) $periodlink=''.img_previous().' '.img_next().''; +else $periodlink = ''; + +$description.=' '; + +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); + +if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') +{ + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); +} + + +if ($modecompta == 'CREANCES-DETTES') +{ + +print ''; +print ''; +print ''; +print ''; +$i=0; +while($i < 12) +{ + $j = $i + (empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START); + if ($j > 12) $j -= 12; + print ''; + $i++; +} +print ''; + +$sql = "SELECT fd.tva_tx AS vatrate,"; +$sql .= " fd.product_type AS product_type,"; +$sql .= " cc.label AS country,"; +for ($i = 1; $i <= 12; $i ++) { + $sql .= " SUM(" . $db->ifsql('MONTH(f.datef)=' . $i, 'fd.total_ht', '0') . ") AS month" . str_pad($i, 2, '0', STR_PAD_LEFT) . ","; +} +$sql .= " SUM(fd.total_ht) as total"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; +$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; +$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe as soc ON soc.rowid = f.fk_soc"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as cc ON cc.rowid = soc.fk_pays"; +$sql .= " WHERE f.datef >= '" . $db->idate($date_start) . "'"; +$sql .= " AND f.datef <= '" . $db->idate($date_end) . "'"; +$sql.= " AND f.fk_statut in (1,2)"; +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql.= " AND f.type IN (0,1,2,5)"; +} else { + $sql.= " AND f.type IN (0,1,2,3,5)"; +} +$sql .= " AND f.entity IN (" . getEntity("facture", 0) . ")"; +$sql .= " GROUP BY fd.tva_tx,fd.product_type, cc.label "; + +dol_syslog("htdocs/compta/tva/index.php sql=" . $sql, LOG_DEBUG); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + $totalpermonth = array(); + while ( $obj = $db->fetch_object($resql)) { + print ''; + if ($obj->product_type == 0) { + print ''; + } else { + print ''; + } + print ''; + for($i = 0; $i < 12; $i++) { + $j = $i + (empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START); + if ($j > 12) $j -= 12; + $monthj = 'month'.str_pad($j, 2, '0', STR_PAD_LEFT); + print ''; + $totalpermonth[$j]=(empty($totalpermonth[$j])?0:$totalpermonth[$j])+$obj->$monthj; + } + print ''; + $totalpermonth['total']=(empty($totalpermonth['total'])?0:$totalpermonth['total'])+$obj->total; + print ''; + } + $db->free($resql); + + // Total + print ''; + print ''; + print ''; + for($i = 0; $i < 12; $i++) { + $j = $i + (empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START); + if ($j > 12) $j -= 12; + $monthj = 'month'.str_pad($j, 2, '0', STR_PAD_LEFT); + print ''; + } + print ''; + print ''; + +} else { + print $db->lasterror(); // Show last sql error +} + + +print ''; +print ''; +print ''; +$i=0; +while($i < 12) +{ + $j = $i + (empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START); + if ($j > 12) $j -= 12; + print ''; + $i++; +} +print ''; + +$sql2 = "SELECT ffd.tva_tx AS vatrate,"; +$sql2 .= " ffd.product_type AS product_type,"; +$sql2 .= " cc.label AS country,"; +for($i = 1; $i <= 12; $i ++) { + $sql2 .= " SUM(" . $db->ifsql('MONTH(ff.datef)=' . $i, 'ffd.total_ht', '0') . ") AS month" . str_pad($i, 2, '0', STR_PAD_LEFT) . ","; +} +$sql2 .= " SUM(ffd.total_ht) as total"; +$sql2 .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as ffd"; +$sql2 .= " INNER JOIN " . MAIN_DB_PREFIX . "facture_fourn as ff ON ff.rowid = ffd.fk_facture_fourn"; +$sql2 .= " INNER JOIN " . MAIN_DB_PREFIX . "societe as soc ON soc.rowid = ff.fk_soc"; +$sql2 .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as cc ON cc.rowid = soc.fk_pays"; +$sql2 .= " WHERE ff.datef >= '" . $db->idate($date_start) . "'"; +$sql2 .= " AND ff.datef <= '" . $db->idate($date_end) . "'"; +$sql.= " AND ff.fk_statut in (1,2)"; +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql.= " AND ff.type IN (0,1,2,5)"; +} else { + $sql.= " AND ff.type IN (0,1,2,3,5)"; +} +$sql2 .= " AND ff.entity IN (" . getEntity("facture_fourn", 0) . ")"; +$sql2 .= " GROUP BY ffd.tva_tx, ffd.product_type, cc.label"; + +//print $sql2; +dol_syslog("htdocs/compta/tva/index.php sql=" . $sql, LOG_DEBUG); +$resql2 = $db->query($sql2); +if ($resql2) { + $num = $db->num_rows($resql2); + $totalpermonth = array(); + while ( $obj = $db->fetch_object($resql2)) { + print ''; + if ($obj->product_type == 0) { + print ''; + } else { + print ''; + } + print ''; + for($i = 0; $i < 12; $i++) { + $j = $i + (empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START); + if ($j > 12) $j -= 12; + $monthj = 'month'.str_pad($j, 2, '0', STR_PAD_LEFT); + print ''; + $totalpermonth[$j]=(empty($totalpermonth[$j])?0:$totalpermonth[$j])+$obj->$monthj; + } + print ''; + $totalpermonth['total']=(empty($totalpermonth['total'])?0:$totalpermonth['total'])+$obj->total; + print ''; + } + $db->free($resql2); + + // Total + print ''; + print ''; + print ''; + for($i = 0; $i < 12; $i++) { + $j = $i + (empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START); + if ($j > 12) $j -= 12; + $monthj = 'month'.str_pad($j, 2, '0', STR_PAD_LEFT); + print ''; + } + print ''; + print ''; +} else { + print $db->lasterror(); // Show last sql error +} +print "
' . $langs->trans("TurnoverbyVatrate") . '' . $langs->trans("ProductOrService") . '' . $langs->trans("Country") . '' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("TotalHT") . '
' . vatrate($obj->vatrate) . ''. $langs->trans("Product") . ''. $langs->trans("Service") . '' .$obj->country . '' . price($obj->$monthj) . '' . price($obj->total) . '
' . price($totalpermonth[$j]) . '' . price($totalpermonth['total']) . '
' . $langs->trans("PurchasebyVatrate") . '' . $langs->trans("ProductOrService") . '' . $langs->trans("Country") . '' . $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT)) . '' . $langs->trans("TotalHT") . '
' . vatrate($obj->vatrate) . ''. $langs->trans("Product") . ''. $langs->trans("Service") . '' . $obj->country . '' . price($obj->$monthj) . '' . price($obj->total) . '
' . price($totalpermonth[$j]) . '' . price($totalpermonth['total']) . '
\n"; + +} else { + // $modecompta != 'CREANCES-DETTES' + // "Calculation of part of each product for accountancy in this mode is not possible. When a partial payment (for example 5 euros) is done on an + // invoice with 2 product (product A for 10 euros and product B for 20 euros), what is part of paiment for product A and part of paiment for product B ? + // Because there is no way to know this, this report is not relevant. + print '
'.$langs->trans("TurnoverPerSaleTaxRateInCommitmentAccountingNotRelevant") . '
'; +} + + +llxFooter(); + +$db->close(); diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index f367f8ee436..5d28ab3e077 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -29,9 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -$langs->load("products"); -$langs->load("categories"); -$langs->load("errors"); +// Load translation files required by the page +$langs->loadLangs(array("products","categories","errors",'accountancy')); // Security pack (data & check) $socid = GETPOST('socid','int'); @@ -78,13 +77,13 @@ if (empty($year)) $month_current = strftime("%m",dol_now()); $year_start = $year; } -$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]); -$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]); +$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear")); +$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear")); // Quarter if (empty($date_start) || empty($date_end)) // We define date_start and date_end { - $q=GETPOST("q")?GETPOST("q"):0; - if ($q==0) + $q=GETPOST("q","int"); + if (empty($q)) { // We define date_start and date_end $month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); @@ -103,14 +102,24 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } $date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false); } - if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } - if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } - if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } - if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + } } else { // TODO We define q } +// $date_start and $date_end are defined. We force $year_start and $nbofyear +$tmps=dol_getdate($date_start); +$year_start = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; +$nbofyear = ($year_end - $year_start) + 1; + $commonparams=array(); $commonparams['modecompta']=$modecompta; $commonparams['sortorder'] = $sortorder; @@ -149,14 +158,15 @@ llxHeader(); $form=new Form($db); $formother = new FormOther($db); +// TODO Report from bookkeeping not yet available, so we switch on report on business events +if ($modecompta=="BOOKKEEPING") $modecompta="CREANCES-DETTES"; +if ($modecompta=="BOOKKEEPINGCOLLECTED") $modecompta="RECETTES-DEPENSES"; + // Show report header -$name=$langs->trans("SalesTurnover").', '.$langs->trans("ByProductsAndServices"); - if ($modecompta=="CREANCES-DETTES") { + $name=$langs->trans("Turnover").', '.$langs->trans("ByProductsAndServices"); $calcmode=$langs->trans("CalcModeDebt"); - $calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; - - $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); + //$calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { @@ -166,23 +176,38 @@ if ($modecompta=="CREANCES-DETTES") { } $builddate=dol_now(); -} else { +} +else if ($modecompta=="RECETTES-DEPENSES") +{ + $name=$langs->trans("TurnoverCollected").', '.$langs->trans("ByProductsAndServices"); $calcmode=$langs->trans("CalcModeEngagement"); - $calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - - $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); + //$calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); $builddate=dol_now(); } +else if ($modecompta=="BOOKKEEPING") +{ + + +} +else if ($modecompta=="BOOKKEEPINGCOLLECTED") +{ + + +} + +$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); +if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) $periodlink=''.img_previous().' '.img_next().''; +else $periodlink = ''; report_header($name,$namelink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); if (! empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { - print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); + print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } @@ -199,17 +224,17 @@ if ($modecompta == 'CREANCES-DETTES') $sql = "SELECT DISTINCT p.rowid as rowid, p.ref as ref, p.label as label, p.fk_product_type as product_type,"; $sql.= " SUM(l.total_ht) as amount, SUM(l.total_ttc) as amount_ttc,"; $sql.= " SUM(CASE WHEN f.type = 2 THEN -l.qty ELSE l.qty END) as qty"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as l, ".MAIN_DB_PREFIX."product as p"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as l"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON l.fk_product = p.rowid"; if ($selected_cat === -2) // Without any category { - $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; } else if ($selected_cat) // Into a specific category { $sql.= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_product as cp"; } - $sql.= " WHERE l.fk_product = p.rowid"; - $sql.= " AND l.fk_facture = f.rowid"; + $sql.= " WHERE l.fk_facture = f.rowid"; $sql.= " AND f.fk_statut in (1,2)"; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $sql.= " AND f.type IN (0,1,2,5)"; @@ -357,23 +382,21 @@ if ($modecompta == 'CREANCES-DETTES') ); print "\n"; - // Array Data - $var=true; - if (count($name)) { foreach($name as $key=>$value) { print ''; // Product + print ""; $fullname=$name[$key]; - if ($key >= 0) { + if ($key > 0) { $linkname=''.img_object($langs->trans("ShowProduct"),$type[$key]==0?'product':'service').' '.$fullname.''; } else { $linkname=$langs->trans("PaymentsNotLinkedToProduct"); } - - print "".$linkname."\n"; + print $linkname; + print "\n"; // Quantity print ''; @@ -417,11 +440,11 @@ if ($modecompta == 'CREANCES-DETTES') // Total print ''; print ''.$langs->trans("Total").''; - print ''.price($qtytotal).''; - print ' '; + print ''.$qtytotal.''; + print '100%'; print ''.price($catotal_ht).''; print ''.price($catotal).''; - print ' '; + print '100%'; print ''; $db->free($result); diff --git a/htdocs/compta/stats/cabyuser.php b/htdocs/compta/stats/cabyuser.php index 1fa48738e66..ccb286c1420 100644 --- a/htdocs/compta/stats/cabyuser.php +++ b/htdocs/compta/stats/cabyuser.php @@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +// Load translation files required by the page $langs->load("accountancy"); $socid = GETPOST('socid','int'); @@ -99,6 +100,12 @@ else { // TODO We define q } +// $date_start and $date_end are defined. We force $year_start and $nbofyear +$tmps=dol_getdate($date_start); +$year_start = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; +$nbofyear = ($year_end - $year_start) + 1; $commonparams=array(); $commonparams['modecompta']=$modecompta; @@ -135,29 +142,45 @@ llxHeader(); $form=new Form($db); +// TODO Report from bookkeeping not yet available, so we switch on report on business events +if ($modecompta=="BOOKKEEPING") $modecompta="CREANCES-DETTES"; +if ($modecompta=="BOOKKEEPINGCOLLECTED") $modecompta="RECETTES-DEPENSES"; + // Show report header if ($modecompta=="CREANCES-DETTES") { - $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); + $name=$langs->trans("Turnover").', '.$langs->trans("ByUserAuthorOfInvoice"); $calcmode=$langs->trans("CalcModeDebt"); - $calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; - $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); - //$periodlink="".img_previous()." ".img_next().""; + //$calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); -} else { - $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice"); +} +else if ($modecompta=="RECETTES-DEPENSES") +{ + $name=$langs->trans("TurnoverCollected").', '.$langs->trans("ByUserAuthorOfInvoice"); $calcmode=$langs->trans("CalcModeEngagement"); - $calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - $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); - //$periodlink="".img_previous()." ".img_next().""; + //$calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } +else if ($modecompta=="BOOKKEEPING") +{ + + +} +else if ($modecompta=="BOOKKEEPINGCOLLECTED") +{ + + +} +$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); +if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) $periodlink=''.img_previous().' '.img_next().''; +else $periodlink = ''; + $moreparam=array(); if (! empty($modecompta)) $moreparam['modecompta']=$modecompta; @@ -321,7 +344,6 @@ print_liste_field_titre( 'align="center" width="20%"' ); print "\n"; -$var=true; if (count($amount)) { $arrayforsort=$name; diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index b7b37d0837c..8e00dfe5fbe 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -34,10 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; -$langs->load("companies"); -$langs->load("categories"); -$langs->load("bills"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'categories', 'bills', 'compta')); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') $modecompta = $conf->global->ACCOUNTING_MODE; @@ -90,8 +88,8 @@ $date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GE // Quarter if (empty($date_start) || empty($date_end)) // We define date_start and date_end { - $q=GETPOST("q")?GETPOST("q"):0; - if ($q==0) + $q=GETPOST("q","int")?GETPOST("q","int"):0; + if (empty($q)) { // We define date_start and date_end $month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1); @@ -120,6 +118,13 @@ else // TODO We define q } +// $date_start and $date_end are defined. We force $year_start and $nbofyear +$tmps=dol_getdate($date_start); +$year_start = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; +$nbofyear = ($year_end - $year_start) + 1; + $commonparams=array(); $commonparams['modecompta']=$modecompta; $commonparams['sortorder'] = $sortorder; @@ -162,30 +167,45 @@ $form=new Form($db); $thirdparty_static=new Societe($db); $formother = new FormOther($db); +// TODO Report from bookkeeping not yet available, so we switch on report on business events +if ($modecompta=="BOOKKEEPING") $modecompta="CREANCES-DETTES"; +if ($modecompta=="BOOKKEEPINGCOLLECTED") $modecompta="RECETTES-DEPENSES"; + // Show report header if ($modecompta=="CREANCES-DETTES") { - $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByThirdParties"); + $name=$langs->trans("Turnover").', '.$langs->trans("ByThirdParties"); $calcmode=$langs->trans("CalcModeDebt"); - $calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; - $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); - //$periodlink=''.img_previous().' '.img_next().''; + //$calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); -} else { - $name=$langs->trans("SalesTurnover").', '.$langs->trans("ByThirdParties"); +} +else if ($modecompta=="RECETTES-DEPENSES") +{ + $name=$langs->trans("TurnoverCollected").', '.$langs->trans("ByThirdParties"); $calcmode=$langs->trans("CalcModeEngagement"); - $calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - $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); - //$periodlink=''.img_previous().' '.img_next().''; + //$calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); } +else if ($modecompta=="BOOKKEEPING") +{ + + +} +else if ($modecompta=="BOOKKEEPINGCOLLECTED") +{ + + +} +$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); +if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) $periodlink=''.img_previous().' '.img_next().''; +else $periodlink = ''; report_header($name,$namelink,$period,$periodlink,$description,$builddate,$exportlink,$tableparams,$calcmode); @@ -226,8 +246,8 @@ if ($modecompta == 'CREANCES-DETTES') { $sql.=" AND cs.fk_soc is null"; } else if ($selected_cat) { // Into a specific category - $sql.= " AND (c.rowid = ".$selected_cat; - if ($subcat) $sql.=" OR c.fk_parent = " . $selected_cat; + $sql.= " AND (c.rowid = ".$db->escape($selected_cat); + if ($subcat) $sql.=" OR c.fk_parent = " . $db->escape($selected_cat); $sql.= ")"; $sql.= " AND cs.fk_categorie = c.rowid AND cs.fk_soc = s.rowid"; } @@ -266,10 +286,10 @@ if ($modecompta == 'CREANCES-DETTES') { $sql.= " AND cs.fk_categorie = c.rowid AND cs.fk_soc = s.rowid"; } } -if(!empty($search_societe)) $sql.= ' AND s.nom LIKE "%'.$search_societe.'%"'; -if(!empty($search_zip)) $sql.= ' AND s.zip LIKE "%'.$search_zip.'%"'; -if(!empty($search_town)) $sql.= ' AND s.town LIKE "%'.$search_town.'%"'; -if($search_country > 0) $sql.= ' AND s.fk_pays = '.$search_country.''; +if (!empty($search_societe)) $sql.= natural_search('s.nom', $search_societe); +if (!empty($search_zip)) $sql.= natural_search('s.zip', $search_zip); +if (!empty($search_town)) $sql.= natural_search('s.town', $search_town); +if ($search_country > 0) $sql.= ' AND s.fk_pays = '.$search_country.''; $sql.= " AND f.entity = ".$conf->entity; if ($socid) $sql.= " AND f.fk_soc = ".$socid; $sql.= " GROUP BY s.rowid, s.nom, s.zip, s.town, s.fk_pays"; diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index 598de2ba490..c255d236664 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -27,6 +27,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +// Load translation files required by the page $langs->loadLangs(array('compta','bills','donation','salaries')); $date_startmonth=GETPOST('date_startmonth'); @@ -71,7 +72,6 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } $month_end=$month_start-1; if ($month_end < 1) $month_end=12; - else $year_end++; } else $month_end=$month_start; $date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false); @@ -85,6 +85,12 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end $userid=GETPOST('userid','int'); $socid = GETPOST('socid','int'); +$tmps=dol_getdate($date_start); +$year_start = $tmps['year']; +$tmpe=dol_getdate($date_end); +$year_end = $tmpe['year']; +$nbofyear = ($year_end - $year_start) + 1; + // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING') $modecompta = $conf->global->ACCOUNTING_MODE; if (! empty($conf->accounting->enabled)) $modecompta='BOOKKEEPING'; @@ -109,12 +115,12 @@ $form=new Form($db); // Affiche en-tete du rapport if ($modecompta=="CREANCES-DETTES") { - $name=$langs->trans("SalesTurnover"); + $name=$langs->trans("Turnover"); $calcmode=$langs->trans("CalcModeDebt"); - $calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + //$calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; $calcmode.='
('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; $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); - $periodlink=($year_start?"".img_previous()." ".img_next()."":""); + $periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description=$langs->trans("RulesCADue"); if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded"); else $description.= $langs->trans("DepositsAreIncluded"); @@ -123,12 +129,12 @@ if ($modecompta=="CREANCES-DETTES") } else if ($modecompta=="RECETTES-DEPENSES") { - $name=$langs->trans("SalesTurnover"); + $name=$langs->trans("TurnoverCollected"); $calcmode=$langs->trans("CalcModeEngagement"); - $calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - $calcmode.='
('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; + //$calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; + //$calcmode.='
('.$langs->trans("SeeReportInBookkeepingMode",'','').')'; $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); - $periodlink=($year_start?"".img_previous()." ".img_next()."":""); + $periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description=$langs->trans("RulesCAIn"); $description.= $langs->trans("DepositsAreIncluded"); $builddate=dol_now(); @@ -136,12 +142,12 @@ else if ($modecompta=="RECETTES-DEPENSES") } else if ($modecompta=="BOOKKEEPING") { - $name=$langs->trans("SalesTurnover"); + $name=$langs->trans("Turnover"); $calcmode=$langs->trans("CalcModeBookkeeping"); $calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - $calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; + //$calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'','').')'; $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); - $periodlink=($year_start?"".img_previous()." ".img_next()."":""); + $periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description=$langs->trans("RulesCATotalSaleJournal"); $builddate=dol_now(); //$exportlink=$langs->trans("NotYetAvailable"); @@ -493,7 +499,7 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) } if (! $total[$annee-1] && $total[$annee]) { - print '+zzzz'.$total[$annee-1].$langs->trans('Inf').'%'; + print '+'.$langs->trans('Inf').'%'; } if (! $total[$annee-1] && ! $total[$annee]) { @@ -551,7 +557,6 @@ print ''; if ($num) { - $var = True; $total_ttc_Rac = $totalam_Rac = $total_Rac = 0; while ($i < $num) { @@ -561,7 +566,7 @@ print ''; $i++; } - print "Facture a encaisser : ".price($total_ttc_Rac)."<-- bug ici car n'exclut pas le deja r?gl? des factures partiellement r?gl?es"; + print "Facture a encaisser : ".price($total_ttc_Rac)."<-- bug ici car n'exclut pas le deja r?gl? des factures partiellement r?gl?es"; } $db->free($resql); } @@ -602,7 +607,6 @@ print ''; if ($num) { - $var = True; $total_pr = 0; while ($i < $num) { @@ -611,7 +615,7 @@ print ''; $i++; } - print "Signe et non facture:".price($total_pr)."<-- bug ici, ca devrait exclure le deja facture"; + print "Signe et non facture:".price($total_pr)."<-- bug ici, ca devrait exclure le deja facture"; } $db->free($resql); } @@ -619,7 +623,7 @@ print ''; { dol_print_error($db); } - print "Total CA previsionnel : ".price($total_CA)."<-- bug ici car bug sur les 2 precedents"; + print "Total CA previsionnel : ".price($total_CA)."<-- bug ici car bug sur les 2 precedents"; } print ""; diff --git a/htdocs/compta/tva/card.php b/htdocs/compta/tva/card.php index e76d96e1a5e..4480682b091 100644 --- a/htdocs/compta/tva/card.php +++ b/htdocs/compta/tva/card.php @@ -29,9 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php'; -$langs->load("compta"); -$langs->load("banks"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'banks', 'bills')); $id=GETPOST("id",'int'); $action=GETPOST("action","alpha"); @@ -55,14 +54,22 @@ $hookmanager->initHooks(array('taxvatcard','globalcard')); if ($_POST["cancel"] == $langs->trans("Cancel") && ! $id) { - header("Location: reglement.php"); + header("Location: list.php"); exit; } +if ($action == 'setlib' && $user->rights->tax->charges->creer) +{ + $object->fetch($id); + $result = $object->setValueFrom('label', GETPOST('lib','alpha'), '', '', 'text', '', $user, 'TAX_MODIFY'); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); +} + if ($action == 'setdatev' && $user->rights->tax->charges->creer) { $object->fetch($id); - $object->datev=dol_mktime(12,0,0,$_POST['datevmonth'],$_POST['datevday'],$_POST['datevyear']); + $object->datev=dol_mktime(12,0,0,GETPOST('datevmonth','int'),GETPOST('datevday','int'),GETPOST('datevyear','int')); $result=$object->update($user); if ($result < 0) dol_print_error($db,$object->error); @@ -119,7 +126,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) if ($ret > 0) { $db->commit(); - header("Location: reglement.php"); + header("Location: list.php"); exit; } else @@ -154,7 +161,7 @@ if ($action == 'delete') if ($result >= 0) { $db->commit(); - header("Location: ".DOL_URL_ROOT.'/compta/tva/reglement.php'); + header("Location: ".DOL_URL_ROOT.'/compta/tva/list.php'); exit; } else @@ -172,7 +179,8 @@ if ($action == 'delete') } else { - setEventMessages('Error try do delete a line linked to a conciliated bank transaction', null, 'errors'); + $mesg='Error try do delete a line linked to a conciliated bank transaction'; + setEventMessages($mesg, null, 'errors'); } } @@ -180,11 +188,13 @@ if ($action == 'delete') /* * View */ + +$form = new Form($db); + $title=$langs->trans("VAT") . " - " . $langs->trans("Card"); $help_url=''; llxHeader("",$title,$helpurl); -$form = new Form($db); if ($id) { @@ -248,7 +258,7 @@ if ($action == 'create') print $form->select_date($datep,"datep",'','','','add',1,1); print ''; - print ''.$langs->trans("DateValue").''; + print ''.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; print $form->select_date($datev,"datev",'','','','add',1,1); print ''; @@ -261,7 +271,7 @@ if ($action == 'create') print ''.$langs->trans("Label").''; // Amount - print ''.$langs->trans("Amount").''; + print ''.$langs->trans("Amount").''; if (! empty($conf->banque->enabled)) { @@ -306,7 +316,14 @@ if ($id) dol_fiche_head($head, 'card', $langs->trans("VATPayment"), -1, 'payment'); - $linkback = ''.$langs->trans("BackToList").''; + $morehtmlref='
'; + // Label of social contribution + $morehtmlref.=$form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 1); + // Project + $morehtmlref.='
'; + + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', ''); @@ -316,18 +333,17 @@ if ($id) print ''; // Label - print ''; + //print ''; print ""; - print ''; - print ''; diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index b5b36232e28..af330910cdf 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -2,6 +2,7 @@ /* Copyright (C) 2002-2003 Rodolphe Quiedeville * Copyright (C) 2004-2008 Laurent Destailleur * Copyright (C) 2011-2017 Alexandre Spangaro + * Copyright (C) 2018 Philippe Grand * * 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 @@ -32,8 +33,8 @@ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; */ class Tva extends CommonObject { - //public $element='tva'; //!< Id that identify managed objects - //public $table_element='tva'; //!< Name of table without prefix where object is stored + public $element='tva'; //!< Id that identify managed objects + public $table_element='tva'; //!< Name of table without prefix where object is stored public $picto='payment'; var $tms; @@ -47,8 +48,6 @@ class Tva extends CommonObject var $fk_user_creat; var $fk_user_modif; - - /** * Constructor * @@ -57,8 +56,6 @@ class Tva extends CommonObject function __construct($db) { $this->db = $db; - $this->element = 'tva'; - $this->table_element = 'tva'; } @@ -695,6 +692,38 @@ class Tva extends CommonObject return $result; } + /** + * Return amount of payments already done + * + * @return int Amount of payment already done, <0 if KO + */ + function getSommePaiement() + { + $table='paiementcharge'; + $field='fk_charge'; + + $sql = 'SELECT sum(amount) as amount'; + $sql.= ' FROM '.MAIN_DB_PREFIX.$table; + $sql.= ' WHERE '.$field.' = '.$this->id; + + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $amount=0; + + $obj = $this->db->fetch_object($resql); + if ($obj) $amount=$obj->amount?$obj->amount:0; + + $this->db->free($resql); + return $amount; + } + else + { + return -1; + } + } + /** * Informations of vat payment object * diff --git a/htdocs/compta/tva/clients.php b/htdocs/compta/tva/clients.php index 276f801d05b..ae95d71ca9c 100644 --- a/htdocs/compta/tva/clients.php +++ b/htdocs/compta/tva/clients.php @@ -1,7 +1,7 @@ * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2006 Yannick Warnier * Copyright (C) 2014 Ferran Marcet * @@ -20,9 +20,9 @@ */ /** - * \file htdocs/compta/tva/clients.php - * \ingroup tax - * \brief Page des societes + * \file htdocs/compta/tva/clients.php + * \ingroup tax + * \brief Page of sales taxes */ require '../../main.inc.php'; @@ -30,78 +30,68 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php'; -$langs->load("bills"); -$langs->load("compta"); -$langs->load("companies"); -$langs->load("products"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin")); // Date range -$year=GETPOST("year"); -if (empty($year)) { +$year=GETPOST("year","int"); +if (empty($year)) +{ $year_current = strftime("%Y",dol_now()); $year_start = $year_current; } else { $year_current = $year; $year_start = $year; } -$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]); -$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]); +$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear")); +$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear")); // Quarter -if (empty($date_start) || empty($date_end)) {// We define date_start and date_end +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ $q=GETPOST("q"); - if (empty($q)) { - if (isset($_REQUEST["month"])) { - $date_start=dol_get_first_day($year_start,$_REQUEST["month"],false); - $date_end=dol_get_last_day($year_start,$_REQUEST["month"],false); - } else { - $month_current = strftime("%m",dol_now()); - if ($month_current >= 10) $q=4; - elseif ($month_current >= 7) $q=3; - elseif ($month_current >= 4) $q=2; - else $q=1; + if (empty($q)) + { + if (GETPOST("month")) { $date_start=dol_get_first_day($year_start,GETPOST("month"),false); $date_end=dol_get_last_day($year_start,GETPOST("month"),false); } + else + { + $date_start=dol_get_first_day($year_start,empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START,false); + if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end=dol_time_plus_duree($date_start, 3, 'm') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end=dol_time_plus_duree($date_start, 1, 'm') - 1; } } - if ($q==1) { - $date_start=dol_get_first_day($year_start,1,false); - $date_end=dol_get_last_day($year_start,3,false); - } - if ($q==2) { - $date_start=dol_get_first_day($year_start,4,false); - $date_end=dol_get_last_day($year_start,6,false); - } - if ($q==3) { - $date_start=dol_get_first_day($year_start,7,false); - $date_end=dol_get_last_day($year_start,9,false); - } - if ($q==4) { - $date_start=dol_get_first_day($year_start,10,false); - $date_end=dol_get_last_day($year_start,12,false); + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } } } -$min = price2num(GETPOST("min")); +$min = price2num(GETPOST("min","alpha")); if (empty($min)) $min = 0; // Define modetax (0 or 1) -// 0=normal, 1=option vat for services is on debit +// 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (isset($_REQUEST["modetax"])) $modetax=$_REQUEST["modetax"]; +if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int'); if (empty($modetax)) $modetax=0; // Security check $socid = GETPOST('socid','int'); -if ($user->societe_id) { - $socid=$user->societe_id; -} +if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); -// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta = $conf->global->ACCOUNTING_MODE; -if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta"); - /* @@ -110,13 +100,19 @@ if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta"); $form=new Form($db); $company_static=new Societe($db); +$invoice_customer=new Facture($db); +$invoice_supplier=new FactureFournisseur($db); +$expensereport=new ExpenseReport($db); +$product_static=new Product($db); +$payment_static=new Paiement($db); +$paymentfourn_static=new PaiementFourn($db); +$paymentexpensereport_static=new PaymentExpenseReport($db); $morequerystring=''; $listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday'); -foreach($listofparams as $param) { - if (GETPOST($param)!='') { - $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); - } +foreach ($listofparams as $param) +{ + if (GETPOST($param)!='') $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); } $special_report = false; @@ -132,69 +128,42 @@ $fsearch.=' '; $fsearch.=' '.$langs->trans("SalesTurnoverMinimum").': '; $fsearch.=' '; -// Affiche en-tete du rapport -if ($modetax==1) { // Calculate on invoice for goods and services - $name=$langs->trans("VATReportByCustomersInDueDebtMode"); - $calcmode=$langs->trans("CalcModeVATDebt"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - //$name.='
('.$langs->trans("SeeVATReportInInputOutputMode",'','').')'; - $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); - //$periodlink=($year_start?"".img_previous()." ".img_next()."":""); - $description=$langs->trans("RulesVATDueServices"); - $description.='
'; - $description.=$langs->trans("RulesVATDueProducts"); - //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); - //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $description.='
'.$langs->trans("DepositsAreNotIncluded"); - } else { - $description.='
'.$langs->trans("DepositsAreIncluded"); - } - $description.=$fsearch; - $description.='
' - . ' ' - . $langs->trans('SimpleReport') - . '' - . '
' - . ' ' - . $langs->trans('AddExtraReport') - . '' - . '
'; - $builddate=dol_now(); - //$exportlink=$langs->trans("NotYetAvailable"); - - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("Description"); - $amountcust=$langs->trans("AmountHT"); - if ($mysoc->tva_assuj) { - $vatcust.=' ('.$langs->trans("ToPay").')'; - } - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$langs->trans("Description"); - $amountsup=$langs->trans("AmountHT"); - if ($mysoc->tva_assuj) { - $vatsup.=' ('.$langs->trans("ToGetBack").')'; - } +// Show report header +$name=$langs->trans("VATReportByThirdParties"); +$calcmode=''; +if ($modetax == 0) $calcmode=$langs->trans('OptionVATDefault'); +if ($modetax == 1) $calcmode=$langs->trans('OptionVATDebitOption'); +if ($modetax == 2) $calcmode=$langs->trans('OptionPaymentForProductAndServices'); +$calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; +// Set period +$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); +$prevyear=$year_start; $prevquarter=$q; +if ($prevquarter > 1) { + $prevquarter--; +} else { + $prevquarter=4; $prevyear--; } -if ($modetax==0) { // Invoice for goods, payment for services - $name=$langs->trans("VATReportByCustomersInInputOutputMode"); - $calcmode=$langs->trans("CalcModeVATEngagement"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - //$name.='
('.$langs->trans("SeeVATReportInDueDebtMode",'','').')'; - $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); - //$periodlink=($year_start?"".img_previous()." ".img_next()."":""); - $description=$langs->trans("RulesVATInServices"); - $description.=' '.$langs->trans("DepositsAreIncluded"); - $description.='
'; - $description.=$langs->trans("RulesVATInProducts"); - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $description .= ' ' . $langs->trans("DepositsAreNotIncluded"); - } else { - $description .= ' ' . $langs->trans("DepositsAreIncluded"); - } - //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); - //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); - $description.=$fsearch; +$nextyear=$year_start; $nextquarter=$q; +if ($nextquarter < 4) { + $nextquarter++; +} else { + $nextquarter=1; $nextyear++; +} +$builddate=dol_now(); + +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description.=$langs->trans("RulesVATDueProducts"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description.=$langs->trans("RulesVATInProducts"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description.='
'.$langs->trans("RulesVATDueServices"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description.='
'.$langs->trans("RulesVATInServices"); +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description.='
'.$langs->trans("DepositsAreNotIncluded"); +} +if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue"); + +//$periodlink=($year_start?"".img_previous()." ".img_next()."":""); +$description.=$fsearch; +if (! empty($conf->global->TAX_REPORT_EXTRA_REPORT)) +{ $description.='
' . ' ' . $langs->trans('SimpleReport') @@ -204,21 +173,20 @@ if ($modetax==0) { // Invoice for goods, payment for services . $langs->trans('AddExtraReport') . '' . '
'; - $builddate=dol_now(); - //$exportlink=$langs->trans("NotYetAvailable"); +} - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("Description"); - $amountcust=$langs->trans("AmountHT"); - if ($mysoc->tva_assuj) { - $vatcust.=' ('.$langs->trans("ToPay").')'; - } - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$langs->trans("Description"); - $amountsup=$langs->trans("AmountHT"); - if ($mysoc->tva_assuj) { - $vatsup.=' ('.$langs->trans("ToGetBack").')'; - } +$elementcust=$langs->trans("CustomersInvoices"); +$productcust=$langs->trans("Description"); +$namerate=$langs->trans("VATRate"); +$amountcust=$langs->trans("AmountHT"); +if ($mysoc->tva_assuj) { + $vatcust.=' ('.$langs->trans("ToPay").')'; +} +$elementsup=$langs->trans("SuppliersInvoices"); +$productsup=$langs->trans("Description"); +$amountsup=$langs->trans("AmountHT"); +if ($mysoc->tva_assuj) { + $vatsup.=' ('.$langs->trans("ToGetBack").')'; } report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); @@ -228,152 +196,547 @@ $vatsup=$langs->trans("VATPaid"); // VAT Received -//print "
"; -//print load_fiche_titre($vatcust); - print "
'.$langs->trans("Label").''.$object->label.'
'.$langs->trans("Label").''.$object->label.'
'.$langs->trans("DatePayment").''; + print ''.$langs->trans("DatePayment").''; print dol_print_date($object->datep,'day'); print '
'; - print $form->editfieldkey("DateValue", 'datev', $object->datev, $object, $user->rights->tax->charges->creer, 'day'); + print $form->editfieldkey($form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")), 'datev', $object->datev, $object, $user->rights->tax->charges->creer, 'day'); print ''; - print $form->editfieldval("DateValue", 'datev', $object->datev, $object, $user->rights->tax->charges->creer, 'day'); + print $form->editfieldval("PeriodEndDate", 'datev', $object->datev, $object, $user->rights->tax->charges->creer, 'day'); //print dol_print_date($object->datev,'day'); print '
"; -print ""; -print '"; -print '"; -print ""; -print ""; -print ""; -print "\n"; -$coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'sell'); +$y = $year_current; +$total = 0; +$i=0; +$columns = 5; -$action = "tvaclient"; -$object = &$coll_list; -$parameters["mode"] = $modetax; -$parameters["start"] = $date_start; -$parameters["end"] = $date_end; -$parameters["direction"] = 'sell'; -$parameters["type"] = 'vat'; +// Load arrays of datas +$x_coll = tax_by_thirdparty('vat', $db, 0, $date_start, $date_end, $modetax, 'sell'); +$x_paye = tax_by_thirdparty('vat', $db, 0, $date_start, $date_end, $modetax, 'buy'); -// Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('externalbalance')); -$reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - -if (is_array($coll_list)) { - $var=true; - $total = 0; $totalamount = 0; - $i = 1; - foreach ($coll_list as $coll) { - if ($min == 0 or ($min > 0 && $coll->amount > $min)) { - - $intra = str_replace($find,$replace,$coll->tva_intra); - if(empty($intra)) { - if($coll->assuj == '1') { - $intra = $langs->trans('Unknown'); - } else { - //$intra = $langs->trans('NotRegistered'); - $intra = ''; - } - } - print ''; - print '"; - $company_static->id=$coll->socid; - $company_static->name=$coll->name; - $company_static->client=1; - print ''; - $find = array(' ','.'); - $replace = array('',''); - print '"; - print ""; - print ""; - $totalamount = $totalamount + $coll->amount; - $total = $total + $coll->tva; - print "\n"; - $i++; - } - } - $x_coll_sum = $total; - - print ''; - print ''; - print ''; - print ''; -} else { +if (! is_array($x_coll) || ! is_array($x_paye)) +{ $langs->load("errors"); - if ($coll_list == -1) { - if ($modecompta == 'CREANCES-DETTES') - { - print ''; - } - else - { - print ''; - } - } else if ($coll_list == -2) { - print ''; + if ($x_coll == -1) { + print ''; + } else if ($x_coll == -2) { + print ''; } else { - print ''; + print ''; } -} - -//print '
'.$langs->trans("Num")."'.$langs->trans("Customer")."".$langs->trans("VATIntra")."".$langs->trans("AmountHTVATRealReceived")."".$vatcust."
'.$i."'.$company_static->getNomUrl(1,'customer').''.$intra."".price($coll->amount)."".price($coll->tva)."
'.$langs->trans("Total").':'.price($totalamount).''.price($total).'
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("Error") . '
' . $langs->trans("Error") . '
'; - - -// VAT Paid - -//print "
"; -//print load_fiche_titre($vatsup); - -//print ""; -print ""; -print '"; -print '"; -print ""; -print ""; -print ""; -print "\n"; - -$company_static=new Societe($db); - -$coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'buy'); - -$parameters["direction"] = 'buy'; -$reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks -if (is_array($coll_list)) { - $var=true; - $total = 0; $totalamount = 0; - $i = 1; - foreach ($coll_list as $coll) { - if ($min == 0 or ($min > 0 && $coll->amount > $min)) { - - $intra = str_replace($find,$replace,$coll->tva_intra); - if (empty($intra)) { - if ($coll->assuj == '1') { - $intra = $langs->trans('Unknown'); - } else { - //$intra = $langs->trans('NotRegistered'); - $intra = ''; - } - } - print ''; - print '"; - $company_static->id=$coll->socid; - $company_static->name=$coll->name; - $company_static->fournisseur=1; - print ''; - $find = array(' ','.'); - $replace = array('',''); - print '"; - print ""; - print ""; - $totalamount = $totalamount + $coll->amount; - $total = $total + $coll->tva; - print "\n"; - $i++; +} else { + $x_both = array(); + //now, from these two arrays, get another array with one rate per line + foreach(array_keys($x_coll) as $my_coll_thirdpartyid) + { + $x_both[$my_coll_thirdpartyid]['coll']['totalht'] = $x_coll[$my_coll_thirdpartyid]['totalht']; + $x_both[$my_coll_thirdpartyid]['coll']['vat'] = $x_coll[$my_coll_thirdpartyid]['vat']; + $x_both[$my_coll_thirdpartyid]['paye']['totalht'] = 0; + $x_both[$my_coll_thirdpartyid]['paye']['vat'] = 0; + $x_both[$my_coll_thirdpartyid]['coll']['links'] = ''; + $x_both[$my_coll_thirdpartyid]['coll']['detail'] = array(); + foreach($x_coll[$my_coll_thirdpartyid]['facid'] as $id=>$dummy) { + $invoice_customer->id=$x_coll[$my_coll_thirdpartyid]['facid'][$id]; + $invoice_customer->ref=$x_coll[$my_coll_thirdpartyid]['facnum'][$id]; + $invoice_customer->type=$x_coll[$my_coll_thirdpartyid]['type'][$id]; + $company_static->fetch($x_coll[$my_coll_thirdpartyid]['company_id'][$id]); + $x_both[$my_coll_thirdpartyid]['coll']['detail'][] = array( + 'id' =>$x_coll[$my_coll_thirdpartyid]['facid'][$id], + 'descr' =>$x_coll[$my_coll_thirdpartyid]['descr'][$id], + 'pid' =>$x_coll[$my_coll_thirdpartyid]['pid'][$id], + 'pref' =>$x_coll[$my_coll_thirdpartyid]['pref'][$id], + 'ptype' =>$x_coll[$my_coll_thirdpartyid]['ptype'][$id], + 'payment_id'=>$x_coll[$my_coll_thirdpartyid]['payment_id'][$id], + 'payment_amount'=>$x_coll[$my_coll_thirdpartyid]['payment_amount'][$id], + 'ftotal_ttc'=>$x_coll[$my_coll_thirdpartyid]['ftotal_ttc'][$id], + 'dtotal_ttc'=>$x_coll[$my_coll_thirdpartyid]['dtotal_ttc'][$id], + 'dtype' =>$x_coll[$my_coll_thirdpartyid]['dtype'][$id], + 'drate' =>$x_coll[$my_coll_thirdpartyid]['drate'][$id], + 'datef' =>$x_coll[$my_coll_thirdpartyid]['datef'][$id], + 'datep' =>$x_coll[$my_coll_thirdpartyid]['datep'][$id], + 'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_coll[$my_coll_thirdpartyid]['ddate_start'][$id], + 'ddate_end' =>$x_coll[$my_coll_thirdpartyid]['ddate_end'][$id], + 'totalht' =>$x_coll[$my_coll_thirdpartyid]['totalht_list'][$id], + 'vat' =>$x_coll[$my_coll_thirdpartyid]['vat_list'][$id], + 'link' =>$invoice_customer->getNomUrl(1,'',12) + ); } } - $x_paye_sum = $total; + // tva paid + foreach (array_keys($x_paye) as $my_paye_thirdpartyid) { + $x_both[$my_paye_thirdpartyid]['paye']['totalht'] = $x_paye[$my_paye_thirdpartyid]['totalht']; + $x_both[$my_paye_thirdpartyid]['paye']['vat'] = $x_paye[$my_paye_thirdpartyid]['vat']; + if (!isset($x_both[$my_paye_thirdpartyid]['coll']['totalht'])) { + $x_both[$my_paye_thirdpartyid]['coll']['totalht'] = 0; + $x_both[$my_paye_thirdpartyid]['coll']['vat'] = 0; + } + $x_both[$my_paye_thirdpartyid]['paye']['links'] = ''; + $x_both[$my_paye_thirdpartyid]['paye']['detail'] = array(); - print ''; - print ''; - print ''; + foreach ($x_paye[$my_paye_thirdpartyid]['facid'] as $id=>$dummy) + { + // ExpenseReport + if ($x_paye[$my_paye_thirdpartyid]['ptype'][$id] == 'ExpenseReportPayment') + { + $expensereport->id=$x_paye[$my_paye_thirdpartyid]['facid'][$id]; + $expensereport->ref=$x_paye[$my_paye_thirdpartyid]['facnum'][$id]; + $expensereport->type=$x_paye[$my_paye_thirdpartyid]['type'][$id]; + + $x_both[$my_paye_thirdpartyid]['paye']['detail'][] = array( + 'id' =>$x_paye[$my_paye_thirdpartyid]['facid'][$id], + 'descr' =>$x_paye[$my_paye_thirdpartyid]['descr'][$id], + 'pid' =>$x_paye[$my_paye_thirdpartyid]['pid'][$id], + 'pref' =>$x_paye[$my_paye_thirdpartyid]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_thirdpartyid]['ptype'][$id], + 'payment_id' =>$x_paye[$my_paye_thirdpartyid]['payment_id'][$id], + 'payment_amount' =>$x_paye[$my_paye_thirdpartyid]['payment_amount'][$id], + 'ftotal_ttc' =>price2num($x_paye[$my_paye_thirdpartyid]['ftotal_ttc'][$id]), + 'dtotal_ttc' =>price2num($x_paye[$my_paye_thirdpartyid]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_thirdpartyid]['dtype'][$id], + 'drate' =>$x_paye[$my_coll_thirdpartyid]['drate'][$id], + 'ddate_start' =>$x_paye[$my_paye_thirdpartyid]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_thirdpartyid]['ddate_end'][$id], + 'totalht' =>price2num($x_paye[$my_paye_thirdpartyid]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_thirdpartyid]['vat_list'][$id], + 'link' =>$expensereport->getNomUrl(1) + ); + } + else + { + $invoice_supplier->id=$x_paye[$my_paye_thirdpartyid]['facid'][$id]; + $invoice_supplier->ref=$x_paye[$my_paye_thirdpartyid]['facnum'][$id]; + $invoice_supplier->type=$x_paye[$my_paye_thirdpartyid]['type'][$id]; + $company_static->fetch($x_paye[$my_paye_thirdpartyid]['company_id'][$id]); + $x_both[$my_paye_thirdpartyid]['paye']['detail'][] = array( + 'id' =>$x_paye[$my_paye_thirdpartyid]['facid'][$id], + 'descr' =>$x_paye[$my_paye_thirdpartyid]['descr'][$id], + 'pid' =>$x_paye[$my_paye_thirdpartyid]['pid'][$id], + 'pref' =>$x_paye[$my_paye_thirdpartyid]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_thirdpartyid]['ptype'][$id], + 'payment_id'=>$x_paye[$my_paye_thirdpartyid]['payment_id'][$id], + 'payment_amount'=>$x_paye[$my_paye_thirdpartyid]['payment_amount'][$id], + 'ftotal_ttc'=>price2num($x_paye[$my_paye_thirdpartyid]['ftotal_ttc'][$id]), + 'dtotal_ttc'=>price2num($x_paye[$my_paye_thirdpartyid]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_thirdpartyid]['dtype'][$id], + 'drate' =>$x_paye[$my_coll_thirdpartyid]['drate'][$id], + 'datef' =>$x_paye[$my_paye_thirdpartyid]['datef'][$id], + 'datep' =>$x_paye[$my_paye_thirdpartyid]['datep'][$id], + 'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_paye[$my_paye_thirdpartyid]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_thirdpartyid]['ddate_end'][$id], + 'totalht' =>price2num($x_paye[$my_paye_thirdpartyid]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_thirdpartyid]['vat_list'][$id], + 'link' =>$invoice_supplier->getNomUrl(1,'',12) + ); + } + } + } + //now we have an array (x_both) indexed by rates for coll and paye + + + //print table headers for this quadri - incomes first + + $x_coll_sum = 0; + $x_coll_ht = 0; + $x_paye_sum = 0; + $x_paye_ht = 0; + + $span=$columns; + if ($modetax != 1) $span+=2; + + //print ''; + + // Customers invoices + print ''; + print ''; + print ''; + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; + else print ''; + print ''; + print ''; + if ($modetax != 1) + { + print ''; + print ''; + } + print ''; + print ''; print ''; + $action = "tvadetail"; + $parameters["mode"] = $modetax; + $parameters["start"] = $date_start; + $parameters["end"] = $date_end; + $parameters["type"] = 'vat'; + + $object = array(&$x_coll, &$x_paye, &$x_both); + // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array + $hookmanager->initHooks(array('externalbalance')); + $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + + foreach (array_keys($x_coll) as $thirdparty_id) { + $subtot_coll_total_ht = 0; + $subtot_coll_vat = 0; + + if (is_array($x_both[$thirdparty_id]['coll']['detail'])) + { + + // VAT Rate + print ""; + print ''; + print ''."\n"; + + foreach ($x_both[$thirdparty_id]['coll']['detail'] as $index => $fields) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } + + + print ''; + + // Ref + print ''; + + // Invoice date + print ''; + + // Payment date + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; + else print ''; + + // Rate + print ''; + + // Description + print ''; + + // Total HT + if ($modetax != 1) + { + print ''; + } + + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + print ''; + } + + // Total collected + print ''; + + // VAT + print ''; + print ''; + + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; + } + } + // Total customers for this vat rate + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + + if (count($x_coll) == 0) // Show a total ine if nothing shown + { + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + + // Blank line + print ''; + + // Print table headers for this quadri - expenses now + print ''; + print ''; + print ''; + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''; + else print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''."\n"; + + foreach (array_keys($x_paye) as $thirdparty_id) + { + $subtot_paye_total_ht = 0; + $subtot_paye_vat = 0; + + if (is_array($x_both[$thirdparty_id]['paye']['detail'])) + { + print ""; + print ''; + print ''."\n"; + + foreach ($x_both[$thirdparty_id]['paye']['detail'] as $index=>$fields) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } + + + print ''; + + // Ref + print ''; + + // Invoice date + print ''; + + // Payment date + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''; + else print ''; + + // Company name + print ''; + + // Description + print ''; + + // Total HT + if ($modetax != 1) + { + print ''; + } + + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + print ''; + } + + // VAT paid + print ''; + + // VAT + print ''; + print ''; + + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; + } + } + // Total suppliers for this vat rate + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + + if (count($x_paye) == 0) { // Show a total line if nothing shown + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + print '
'.$langs->trans("Num")."'.$langs->trans("Supplier")."".$langs->trans("VATIntra")."".$langs->trans("AmountHTVATRealPaid")."".$vatsup."
'.$i."'.$company_static->getNomUrl(1,'supplier').''.$intra."".price($coll->amount)."".price($coll->tva)."
'.$langs->trans("Total").':'.price($totalamount).''.price($total).'
'..')
'.$elementcust.''.$langs->trans("DateInvoice").''.$langs->trans("DatePayment").''.$namerate.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("AmountHTVATRealReceived").''.$vatcust.'
'; + if (is_numeric($thirdparty_id)) + { + $company_static->fetch($thirdparty_id); + print $langs->trans("ThirdParty").': '.$company_static->getNomUrl(1); + } + else + { + $tmpid = preg_replace('/userid_/','',$thirdparty_id); + $user_static->fetch($tmpid); + print $langs->trans("User").': '.$user_static->getNomUrl(1); + } + print '
'.$fields['link'].'' . dol_print_date($fields['datef'], 'day') . '' . dol_print_date($fields['datep'], 'day') . '' . $fields['drate'] . ''; + if ($fields['pid']) + { + $product_static->id=$fields['pid']; + $product_static->ref=$fields['pref']; + $product_static->type=$fields['dtype']; // We force with the type of line to have type how line is registered + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); + } + } + else + { + if ($type) { + $text = img_object($langs->trans('Service'),'service'); + } else { + $text = img_object($langs->trans('Product'),'product'); + } + if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) { + if ($reg[1]=='DEPOSIT') { + $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); + } elseif ($reg[1]=='CREDIT_NOTE') { + $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); + } else { + $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); + } + } + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); + + // Show range + print_date_range($fields['ddate_start'],$fields['ddate_end']); + } + print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) + { + //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; + $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); + //print ' ('.round($ratiolineinvoice*100,2).'%)'; + } + print ''; + //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; + if ($fields['payment_amount'] && $fields['ftotal_ttc']) + { + $payment_static->id=$fields['payment_id']; + print $payment_static->getNomUrl(2); + } + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) + { + print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + print price(price2num($fields['payment_amount'],'MT')); + if (isset($fields['payment_amount'])) { + print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } + } + print ''; + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + print price(price2num($temp_ht,'MT'),1); + print ''; + $temp_vat=$fields['vat']*$ratiopaymentinvoice; + print price(price2num($temp_vat,'MT'),1); + //print price($fields['vat']); + print '
'.$langs->trans("Total").':  '.price(price2num($subtot_coll_total_ht,'MT')).''.price(price2num($subtot_coll_vat,'MT')).'
'.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
 
'.$elementsup.''.$langs->trans("DateInvoice").''.$langs->trans("DatePayment").''.$namesup.''.$productsup.''.$amountsup.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("AmountHTVATRealPaid").''.$vatsup.'
'; + if (is_numeric($thirdparty_id)) + { + $company_static->fetch($thirdparty_id); + print $langs->trans("ThirdParty").': '.$company_static->getNomUrl(1); + } + else + { + $tmpid = preg_replace('/userid_/','',$thirdparty_id); + $user_static->fetch($tmpid); + print $langs->trans("User").': '.$user_static->getNomUrl(1); + } + print '
'.$fields['link'].'' . dol_print_date($fields['datef'], 'day') . '' . dol_print_date($fields['datep'], 'day') . '' . $fields['company_link'] . ''; + if ($fields['pid']) + { + $product_static->id=$fields['pid']; + $product_static->ref=$fields['pref']; + $product_static->type=$fields['dtype']; // We force with the type of line to have type how line is registered + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); + } + } + else + { + if ($type) { + $text = img_object($langs->trans('Service'),'service'); + } else { + $text = img_object($langs->trans('Product'),'product'); + } + if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) { + if ($reg[1]=='DEPOSIT') { + $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); + } elseif ($reg[1]=='CREDIT_NOTE') { + $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); + } else { + $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); + } + } + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); + + // Show range + print_date_range($fields['ddate_start'],$fields['ddate_end']); + } + print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) + { + //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; + $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); + //print ' ('.round($ratiolineinvoice*100,2).'%)'; + } + print ''; + if ($fields['payment_amount'] && $fields['ftotal_ttc']) + { + $paymentfourn_static->id=$fields['payment_id']; + print $paymentfourn_static->getNomUrl(2); + } + + if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) + { + print $langs->trans("NA"); + } + else + { + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + print price(price2num($fields['payment_amount'],'MT')); + if (isset($fields['payment_amount'])) { + print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } + } + print ''; + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + print price(price2num($temp_ht,'MT'),1); + print ''; + $temp_vat=$fields['vat']*$ratiopaymentinvoice; + print price(price2num($temp_vat,'MT'),1); + //print price($fields['vat']); + print '
'.$langs->trans("Total").':  '.price(price2num($subtot_paye_total_ht,'MT')).''.price(price2num($subtot_paye_vat,'MT')).'
'.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
'; // Total to pay @@ -381,198 +744,15 @@ if (is_array($coll_list)) { print ''; $diff = $x_coll_sum - $x_paye_sum; print ''; - print ''; + print ''; print '\n"; print "\n"; -} else { - $langs->load("errors"); - if ($coll_list == -1) { - if ($modecompta == 'CREANCES-DETTES') - { - print ''; - } - else - { - print ''; - } - } else if ($coll_list == -2) { - print ''; - } else { - print ''; - } + $i++; } print '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("Error") . '
'; -if ($special_report) { - // Get country 2-letters code - global $mysoc; - $country_id = $mysoc->country_id; - $country = new Ccountry($db); - $country->fetch($country_id); - - // Print listing of other-country customers as additional report - // This matches tax requirements to list all same-country customers (only) - print '

'.$langs->trans('OtherCountriesCustomersReport').'

'; - print $langs->trans('BasedOnTwoFirstLettersOfVATNumberBeingDifferentFromYourCompanyCountry'); - $coll_list = vat_by_thirdparty($db, 0, $date_start, $date_end, $modetax, 'sell'); - - print ""; - print ""; - print '"; - print '"; - print ""; - print ""; - print ""; - print "\n"; - - if (is_array($coll_list)) { - $var = true; - $total = 0; - $totalamount = 0; - $i = 1; - foreach ($coll_list as $coll) { - if (substr($coll->tva_intra, 0, 2) == $country->code) { - // Only use different-country VAT codes - continue; - } - if ($min == 0 or ($min > 0 && $coll->amount > $min)) { - $var = !$var; - $intra = str_replace($find, $replace, $coll->tva_intra); - if (empty($intra)) { - if ($coll->assuj == '1') { - $intra = $langs->trans('Unknown'); - } else { - //$intra = $langs->trans('NotRegistered'); - $intra = ''; - } - } - print ""; - print '"; - $company_static->id = $coll->socid; - $company_static->name = $coll->name; - $company_static->client = 1; - print ''; - $find = array(' ', '.'); - $replace = array('', ''); - print '"; - print ""; - print ""; - $totalamount = $totalamount + $coll->amount; - $total = $total + $coll->tva; - print "\n"; - $i++; - } - } - $x_coll_sum = $total; - - print ''; - print ''; - print ''; - print ''; - } else { - $langs->load("errors"); - if ($coll_list == -1) { - if ($modecompta == 'CREANCES-DETTES') - { - print ''; - } - else - { - print ''; - } - } else { - if ($coll_list == -2) { - print ''; - } else { - print ''; - } - } - } - print '
' . $langs->trans("Num") . "' . $langs->trans("Customer") . "" . $langs->trans("VATIntra") . "" . $langs->trans("AmountHTVATRealReceived") . "" . $vatcust . "
' . $i . "' . $company_static->getNomUrl(1, - 'customer') . '' . $intra . "" . price($coll->amount) . "" . price($coll->tva) . "
' . $langs->trans("Total") . ':' . price($totalamount) . '' . price($total) . '
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("Error") . '
'; - - // Print listing of same-country customers as additional report - // This matches tax requirements to list all same-country customers (only) - print '

'.$langs->trans('SameCountryCustomersWithVAT').'

'; - print $langs->trans('BasedOnTwoFirstLettersOfVATNumberBeingTheSameAsYourCompanyCountry'); - $coll_list = vat_by_thirdparty($db, 0, $date_start, $date_end, $modetax, 'sell'); - - print ""; - print ""; - print '"; - print '"; - print ""; - print ""; - print ""; - print "\n"; - - if (is_array($coll_list)) { - $var = true; - $total = 0; - $totalamount = 0; - $i = 1; - foreach ($coll_list as $coll) { - if (substr($coll->tva_intra, 0, 2) != $country->code) { - // Only use same-country VAT codes - continue; - } - if ($min == 0 or ($min > 0 && $coll->amount > $min)) { - $var = !$var; - $intra = str_replace($find, $replace, $coll->tva_intra); - if (empty($intra)) { - if ($coll->assuj == '1') { - $intra = $langs->trans('Unknown'); - } else { - //$intra = $langs->trans('NotRegistered'); - $intra = ''; - } - } - print ""; - print '"; - $company_static->id = $coll->socid; - $company_static->name = $coll->name; - $company_static->client = 1; - print ''; - $find = array(' ', '.'); - $replace = array('', ''); - print '"; - print ""; - print ""; - $totalamount = $totalamount + $coll->amount; - $total = $total + $coll->tva; - print "\n"; - $i++; - } - } - $x_coll_sum = $total; - - print ''; - print ''; - print ''; - print ''; - } else { - $langs->load("errors"); - if ($coll_list == -1) { - if ($modecompta == 'CREANCES-DETTES') - { - print ''; - } - else - { - print ''; - } - } else { - if ($coll_list == -2) { - print ''; - } else { - print ''; - } - } - } - print '
' . $langs->trans("Num") . "' . $langs->trans("Customer") . "" . $langs->trans("VATIntra") . "" . $langs->trans("AmountHTVATRealReceived") . "" . $vatcust . "
' . $i . "' . $company_static->getNomUrl(1, 'customer') . '' . $intra . "" . price($coll->amount) . "" . price($coll->tva) . "
' . $langs->trans("Total") . ':' . price($totalamount) . '' . price($total) . '
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("Error") . '
'; -} llxFooter(); diff --git a/htdocs/compta/tva/document.php b/htdocs/compta/tva/document.php new file mode 100644 index 00000000000..b83cad80bdd --- /dev/null +++ b/htdocs/compta/tva/document.php @@ -0,0 +1,160 @@ + + * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2005 Simon TOSSER + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2013 Cédric Salvador + * Copyright (C) 2018 Philippe Grand + * + * 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/tva/document.php + * \ingroup tax + * \brief Page with attached files on social contributions + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.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'; +} + +// Load translation files required by the page +$langs->loadLangs(array('other', 'companies', 'compta', 'bills')); + +$id = GETPOST('id','int'); +$action = GETPOST('action','aZ09'); +$confirm = GETPOST('confirm', 'alpha'); + +// Security check +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'tax', $id, 'vat','charges'); + + +// Get parameters +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if ($page == -1) { + $page = 0; +} +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortorder) $sortorder="ASC"; +if (! $sortfield) $sortfield="name"; + + +$object = new Tva($db); +if ($id > 0) $object->fetch($id); + +$upload_dir = $conf->tax->dir_output.'/'.dol_sanitizeFileName($object->ref); +$modulepart='tax'; + + +/* + * Actions + */ + +include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; + +if ($action == 'setlib' && $user->rights->tax->charges->creer) +{ + $object->fetch($id); + $result = $object->setValueFrom('label', GETPOST('lib','alpha'), '', '', 'text', '', $user, 'TAX_MODIFY'); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); +} + + +/* + * View + */ + +$form = new Form($db); +if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } + +$title = $langs->trans("VATPayment") . ' - ' . $langs->trans("Documents"); +$help_url='EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:Módulo Impuestos y cargas sociales (IVA, impuestos)'; +llxHeader("",$title,$help_url); + +if ($object->id) +{ + $alreadypayed=$object->getSommePaiement(); + + $head=vat_prepare_head($object); + + dol_fiche_head($head, 'documents', $langs->trans("VATPayment"), -1, 'bill'); + + $morehtmlref='
'; + // Label of social contribution + $morehtmlref.=$form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 1); + $morehtmlref.='
'; + + $linkback = '' . $langs->trans("BackToList") . ''; + + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlright); + + print '
'; + print '
'; + + // Construit liste des fichiers + $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); + $totalsize=0; + foreach($filearray as $key => $file) + { + $totalsize+=$file['size']; + } + + + print ''; + + print ''; + print ''; + print '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
'; + + print '
'; + + print '
'; + + dol_fiche_end(); + + $modulepart = 'tax'; + $permission = $user->rights->tax->charges->creer; + $permtoedit = $user->rights->fournisseur->facture->creer; + $param = '&id=' . $object->id; + include_once DOL_DOCUMENT_ROOT . '/core/tpl/document_actions_post_headers.tpl.php'; +} +else +{ + print $langs->trans("ErrorUnknown"); +} + + +llxFooter(); + +$db->close(); diff --git a/htdocs/compta/tva/index.php b/htdocs/compta/tva/index.php index 1ac38a93c96..7c4912411f6 100644 --- a/htdocs/compta/tva/index.php +++ b/htdocs/compta/tva/index.php @@ -1,7 +1,7 @@ * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2004-2012 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2014 Ferran Marcet * @@ -25,77 +25,162 @@ * \brief Index page of VAT reports */ require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; -$langs->load("other"); -$langs->load("compta"); -$langs->load("banks"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin")); +// Date range $year=GETPOST("year","int"); -if ($year == 0) +if (empty($year)) { - $year_current = strftime("%Y",time()); - $year_start = $year_current; + $year_current = strftime("%Y",dol_now()); + $year_start = $year_current; } else { - $year_current = $year; - $year_start = $year; + $year_current = $year; + $year_start = $year; +} +$date_start=dol_mktime(0,0,0,GETPOST("date_startmonth"),GETPOST("date_startday"),GETPOST("date_startyear")); +$date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GETPOST("date_endyear")); +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $q=GETPOST("q","int"); + if (empty($q)) + { + if (GETPOST("month","int")) { $date_start=dol_get_first_day($year_start,GETPOST("month","int"),false); $date_end=dol_get_last_day($year_start,GETPOST("month","int"),false); } + else + { + $date_start=dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START,false); + $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1; + } + } + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + } } +// Define modetax (0 or 1) +// 0=normal, 1=option vat for services is on debit, 2=option on payments for products +$modetax = $conf->global->TAX_MODE; +if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int'); +if (empty($modetax)) $modetax=0; + // Security check -$socid = isset($_GET["socid"])?$_GET["socid"]:''; +$socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); -// Define modetax (0 or 1) -// 0=normal, 1=option vat for services is on debit -$modetax = $conf->global->TAX_MODE; -if (isset($_GET["modetax"])) $modetax=$_GET["modetax"]; - /** * print function * - * @param DoliDB $db Database handler - * @param string $sql SQL Request - * @param string $date Date - * @return void + * @param DoliDB $db Database handler + * @param string $sql SQL Request + * @param string $date Date + * @return void */ -function pt ($db, $sql, $date) +function pt($db, $sql, $date) { global $conf, $bc,$langs; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; $total = 0; print ''; + print ''; - print ''; - print ''; - print ''."\n"; + print ''; + print ''; + print ''; print "\n"; - $var=True; - while ($i < $num) - { + + $totalclaimed = 0; + $totalpaid = 0; + $amountclaimed = 0; + $amountpaid = 0; + $previousmonth = ''; + $previousmode = ''; + $mode = ''; + + while ($i < $num) { $obj = $db->fetch_object($result); + $mode = $obj->mode; - print ''; - print '\n"; - $total = $total + $obj->mm; + //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; + if ($obj->mode == 'claimed' && ! empty($previousmode)) + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - print '\n"; - print "\n"; + $amountclaimed = 0; + $amountpaid = 0; + } + + if ($obj->mode == 'claimed') + { + $amountclaimed = $obj->mm; + $totalclaimed = $totalclaimed + $amountclaimed; + } + if ($obj->mode == 'paid') + { + $amountpaid = $obj->mm; + $totalpaid = $totalpaid + $amountpaid; + } + + if ($obj->mode == 'paid') + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; + $amountclaimed = 0; + $amountpaid = 0; + $previousmode = ''; + $previousmonth = ''; + } + else + { + $previousmode = $obj->mode; + $previousmonth = $obj->dm; + } $i++; } - print '"; + + if ($mode == 'claimed' && ! empty($previousmode)) + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; + + $amountclaimed = 0; + $amountpaid = 0; + } + + print ''; + print ''; + print ''; + print ''; + print ""; print "
'.$date.''.$langs->trans("Amount").' '.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").'
'.$obj->dm."
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.price($obj->mm)." 
'.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
'.$langs->trans("Total")." :".price($total)." 
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
"; + $db->free($result); } else { @@ -108,18 +193,45 @@ function pt ($db, $sql, $date) * View */ -llxHeader(); - +$form=new Form($db); +$company_static=new Societe($db); $tva = new Tva($db); +$description = ''; -$textprevyear="".img_previous($langs->trans("Previous"), 'class="valignbottom"').""; -$textnextyear=" ".img_next($langs->trans("Next"), 'class="valignbottom"').""; +// Show report header +$name = $langs->trans("ReportByMonth"); +$calcmode=''; +if ($modetax == 0) $calcmode=$langs->trans('OptionVATDefault'); +if ($modetax == 1) $calcmode=$langs->trans('OptionVATDebitOption'); +if ($modetax == 2) $calcmode=$langs->trans('OptionPaymentForProductAndServices'); +$calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; + +$description = $langs->trans("VATSummary").'
'; +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description.=$langs->trans("RulesVATDueProducts"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description.=$langs->trans("RulesVATInProducts"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description.='
'.$langs->trans("RulesVATDueServices"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description.='
'.$langs->trans("RulesVATInServices"); +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description.='
'.$langs->trans("DepositsAreNotIncluded"); +} +if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue"); + +$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); + +$builddate=dol_now(); + + +llxHeader('', $name); + +//$textprevyear="".img_previous($langs->trans("Previous"), 'class="valignbottom"').""; +//$textnextyear=" ".img_next($langs->trans("Next"), 'class="valignbottom"').""; +//print load_fiche_titre($langs->transcountry("VAT", $mysoc->country_code), $textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, 'title_accountancy.png'); + +report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +//report_header($name,'',$textprevyear.$langs->trans("Year")." ".$year_start.$textnextyear,'',$description,$builddate,$exportlink,array(),$calcmode); -print load_fiche_titre($langs->transcountry("VAT", $mysoc->country_code), $textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, 'title_accountancy.png'); -print $langs->trans("VATReportBuildWithOptionDefinedInModule").'
'; -print '('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')
'; print '
'; print '
'; @@ -131,24 +243,138 @@ print ''; print ''.$langs->trans("Year")." ".$y.''; print ''.$langs->trans("VATToPay").''; print ''.$langs->trans("VATToCollect").''; -print ''.$langs->trans("TotalToPay").''; +print ''.$langs->trans("Balance").''; print ' '."\n"; print ''."\n"; - -$y = $year_current ; - - -$var=True; +$tmp=dol_getdate($date_start); +$y = $tmp['year']; +$m = $tmp['mon']; +$tmp=dol_getdate($date_end); +$yend = $tmp['year']; +$mend = $tmp['mon']; +//var_dump($m); $total=0; $subtotalcoll=0; $subtotalpaye=0; $subtotal=0; -$i=0; -for ($m = 1 ; $m < 13 ; $m++ ) +$i=0; $mcursor=0; +while ((($y < $yend) || ($y == $yend && $m < $mend)) && $mcursor < 1000) // $mcursor is to avoid too large loop { - $coll_listsell = tax_by_date('vat', $db, $y, 0, 0, 0, $modetax, 'sell', $m); - $coll_listbuy = tax_by_date('vat', $db, $y, 0, 0, 0, $modetax, 'buy', $m); + //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12); + if ($m == 13) $y++; + if ($m > 12) $m -= 12; + $mcursor++; + + $x_coll = tax_by_rate('vat', $db, $y, 0, 0, 0, $modetax, 'sell', $m); + $x_paye = tax_by_rate('vat', $db, $y, 0, 0, 0, $modetax, 'buy', $m); + + $x_both = array(); + //now, from these two arrays, get another array with one rate per line + foreach(array_keys($x_coll) as $my_coll_rate) + { + $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; + $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; + $x_both[$my_coll_rate]['paye']['totalht'] = 0; + $x_both[$my_coll_rate]['paye']['vat'] = 0; + $x_both[$my_coll_rate]['coll']['links'] = ''; + $x_both[$my_coll_rate]['coll']['detail'] = array(); + foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) { + //$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; + //$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; + //$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; + //$company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]); + $x_both[$my_coll_rate]['coll']['detail'][] = array( + 'id' =>$x_coll[$my_coll_rate]['facid'][$id], + 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], + 'pid' =>$x_coll[$my_coll_rate]['pid'][$id], + 'pref' =>$x_coll[$my_coll_rate]['pref'][$id], + 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id], + 'payment_id'=>$x_coll[$my_coll_rate]['payment_id'][$id], + 'payment_amount'=>$x_coll[$my_coll_rate]['payment_amount'][$id], + 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], + 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], + 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], + 'datef' =>$x_coll[$my_coll_rate]['datef'][$id], + 'datep' =>$x_coll[$my_coll_rate]['datep'][$id], + //'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id], + 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], + 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], + 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], + //'link' =>$invoice_customer->getNomUrl(1,'',12) + ); + } + } + + // tva paid + foreach (array_keys($x_paye) as $my_paye_rate) { + $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; + $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; + if (!isset($x_both[$my_paye_rate]['coll']['totalht'])) { + $x_both[$my_paye_rate]['coll']['totalht'] = 0; + $x_both[$my_paye_rate]['coll']['vat'] = 0; + } + $x_both[$my_paye_rate]['paye']['links'] = ''; + $x_both[$my_paye_rate]['paye']['detail'] = array(); + + foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) + { + // ExpenseReport + if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') + { + //$expensereport->id=$x_paye[$my_paye_rate]['facid'][$id]; + //$expensereport->ref=$x_paye[$my_paye_rate]['facnum'][$id]; + //$expensereport->type=$x_paye[$my_paye_rate]['type'][$id]; + + $x_both[$my_paye_rate]['paye']['detail'][] = array( + 'id' =>$x_paye[$my_paye_rate]['facid'][$id], + 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], + 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], + 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id' =>$x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount' =>$x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc' =>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc' =>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'ddate_start' =>$x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], + 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], + //'link' =>$expensereport->getNomUrl(1) + ); + } + else + { + //$invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; + //$invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; + //$invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; + //$company_static->fetch($x_paye[$my_paye_rate]['company_id'][$id]); + $x_both[$my_paye_rate]['paye']['detail'][] = array( + 'id' =>$x_paye[$my_paye_rate]['facid'][$id], + 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], + 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], + 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id'=>$x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount'=>$x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'datef' =>$x_paye[$my_paye_rate]['datef'][$id], + 'datep' =>$x_paye[$my_paye_rate]['datep'][$id], + //'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], + 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], + //'link' =>$invoice_supplier->getNomUrl(1,'',12) + ); + } + } + } + //now we have an array (x_both) indexed by rates for coll and paye $action = "tva"; - $object = array(&$coll_listsell, &$coll_listbuy); + $object = array(&$x_coll, &$x_paye, &$x_both); $parameters["mode"] = $modetax; $parameters["year"] = $y; $parameters["month"] = $m; @@ -158,13 +384,13 @@ for ($m = 1 ; $m < 13 ; $m++ ) $hookmanager->initHooks(array('externalbalance')); $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - if (! is_array($coll_listbuy) && $coll_listbuy == -1) + if (! is_array($x_coll) && $coll_listbuy == -1) { $langs->load("errors"); print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").''; break; } - if (! is_array($coll_listbuy) && $coll_listbuy == -2) + if (! is_array($x_paye) && $coll_listbuy == -2) { print ''.$langs->trans("FeatureNotYetAvailable").''; break; @@ -172,45 +398,121 @@ for ($m = 1 ; $m < 13 ; $m++ ) print ''; - print ''.dol_print_date(dol_mktime(0,0,0,$m,1,$y),"%b %Y").''; + print ''.dol_print_date(dol_mktime(0,0,0,$m,1,$y),"%b %Y").''; - $x_coll = 0; - foreach($coll_listsell as $vatrate=>$val) + $x_coll_sum = 0; + foreach (array_keys($x_coll) as $rate) { - $x_coll+=$val['vat']; - } - $subtotalcoll = $subtotalcoll + $x_coll; - print "".price($x_coll).""; + $subtot_coll_total_ht = 0; + $subtot_coll_vat = 0; - $x_paye = 0; - foreach($coll_listbuy as $vatrate=>$val) + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) + { + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } + + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) + { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + $temp_vat=$fields['vat']*$ratiopaymentinvoice; + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; + } + } + print "".price(price2num($x_coll_sum,'MT')).""; + + $x_paye_sum = 0; + foreach (array_keys($x_paye) as $rate) { - $x_paye+=$val['vat']; - } - $subtotalpaye = $subtotalpaye + $x_paye; - print "".price($x_paye).""; + $subtot_paye_total_ht = 0; + $subtot_paye_vat = 0; - $diff = $x_coll - $x_paye; + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) + { + // Payment + $ratiopaymentinvoice=1; + if ($modetax != 1) + { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } + + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) + { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + $temp_vat=$fields['vat']*$ratiopaymentinvoice; + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; + } + } + print "".price(price2num($x_paye_sum,'MT')).""; + + $subtotalcoll = $subtotalcoll + $x_coll_sum; + $subtotalpaye = $subtotalpaye + $x_paye_sum; + + $diff = $x_coll_sum - $x_paye_sum; $total = $total + $diff; - $subtotal = $subtotal + $diff; + $subtotal = price2num($subtotal + $diff, 'MT'); - print "".price($diff)."\n"; + print "".price(price2num($diff,'MT'))."\n"; print " \n"; print "\n"; - $i++; - if ($i > 2) { + $i++; $m++; + if ($i > 2) + { print ''; print ''.$langs->trans("SubTotal").':'; - print ''.price($subtotalcoll).''; - print ''.price($subtotalpaye).''; - print ''.price($subtotal).''; + print ''.price(price2num($subtotalcoll,'MT')).''; + print ''.price(price2num($subtotalpaye,'MT')).''; + print ''.price(price2num($subtotal,'MT')).''; print ' '; $i = 0; $subtotalcoll=0; $subtotalpaye=0; $subtotal=0; } } -print ''.$langs->trans("TotalToPay").':'.price($total).''; +print ''.$langs->trans("TotalToPay").':'.price(price2num($total, 'MT')).''; print " \n"; print ''; @@ -220,39 +522,50 @@ print ''; print '
'; -print load_fiche_titre($langs->trans("VATPaid"), '', ''); /* * Payed */ -$sql = "SELECT SUM(amount) as mm, date_format(f.datep,'%Y-%m') as dm"; +print load_fiche_titre($langs->trans("VATPaid"), '', ''); + +$sql=''; + +$sql.= "SELECT SUM(amount) as mm, date_format(f.datev,'%Y-%m') as dm, 'claimed' as mode"; $sql.= " FROM ".MAIN_DB_PREFIX."tva as f"; $sql.= " WHERE f.entity = ".$conf->entity; -$sql.= " AND f.datep >= '".$db->idate(dol_get_first_day($y,1,false))."'"; -$sql.= " AND f.datep <= '".$db->idate(dol_get_last_day($y,12,false))."'"; -$sql.= " GROUP BY dm ORDER BY dm ASC"; +$sql.= " AND (f.datev >= '".$db->idate($date_start)."' AND f.datev <= '".$db->idate($date_end)."')"; +$sql.= " GROUP BY dm"; -pt($db, $sql,$langs->trans("Year")." $y"); +$sql.= " UNION "; +$sql.= "SELECT SUM(amount) as mm, date_format(f.datep,'%Y-%m') as dm, 'paid' as mode"; +$sql.= " FROM ".MAIN_DB_PREFIX."tva as f"; +$sql.= " WHERE f.entity = ".$conf->entity; +$sql.= " AND (f.datep >= '".$db->idate($date_start)."' AND f.datep <= '".$db->idate($date_end)."')"; +$sql.= " GROUP BY dm"; -print '
'; +$sql.= " ORDER BY dm ASC, mode ASC"; +//print $sql; +pt($db, $sql, $langs->trans("Month")); if (! empty($conf->global->MAIN_FEATURES_LEVEL)) { - /* + print '
'; + + /* * Recap */ - print load_fiche_titre($langs->trans("VATRecap"), '', ''); // need to add translation + print load_fiche_titre($langs->trans("VATBalance"), '', ''); // need to add translation $sql1 = "SELECT SUM(amount) as mm, date_format(f.datev,'%Y') as dm"; $sql1 .= " FROM " . MAIN_DB_PREFIX . "tva as f"; $sql1 .= " WHERE f.entity = " . $conf->entity; - $sql1 .= " AND f.datev >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; - $sql1 .= " AND f.datev <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; + $sql1 .= " AND f.datev >= '" . $db->idate($date_start) . "'"; + $sql1 .= " AND f.datev <= '" . $db->idate($date_end) . "'"; $sql1 .= " GROUP BY dm ORDER BY dm ASC"; $result = $db->query($sql1); @@ -261,7 +574,7 @@ if (! empty($conf->global->MAIN_FEATURES_LEVEL)) print ''; print ""; - print ''; // need to add translation + print ''; print ''; print "\n"; @@ -272,7 +585,7 @@ if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $restopay = $total - $obj->mm; print ""; - print ''; // need to add translation + print ''; print ''; print "\n"; diff --git a/htdocs/compta/tva/info.php b/htdocs/compta/tva/info.php index f6026c8f8ea..4a2308bd0bd 100644 --- a/htdocs/compta/tva/info.php +++ b/htdocs/compta/tva/info.php @@ -26,8 +26,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); $id=GETPOST('id','int'); $action=GETPOST('action','aZ09'); @@ -37,10 +37,27 @@ $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); +$object = new Tva($db); + + + +/* + * Actions + */ + +if ($action == 'setlib' && $user->rights->tax->charges->creer) +{ + $object->fetch($id); + $result = $object->setValueFrom('label', GETPOST('lib','alpha'), '', '', 'text', '', $user, 'TAX_MODIFY'); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); +} + /* * View */ + $title=$langs->trans("VAT") . " - " . $langs->trans("Info"); $help_url=''; llxHeader("",$title,$helpurl); @@ -53,7 +70,13 @@ $head = vat_prepare_head($object); dol_fiche_head($head, 'info', $langs->trans("VATPayment"), -1, 'payment'); -$linkback = ''.$langs->trans("BackToList").''; +$morehtmlref='
'; +// Label of social contribution +$morehtmlref.=$form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1); +$morehtmlref.=$form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 1); +$morehtmlref.='
'; + +$linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', ''); diff --git a/htdocs/compta/tva/reglement.php b/htdocs/compta/tva/list.php similarity index 87% rename from htdocs/compta/tva/reglement.php rename to htdocs/compta/tva/list.php index 66099cd63db..d835b0264e1 100644 --- a/htdocs/compta/tva/reglement.php +++ b/htdocs/compta/tva/list.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2011-2017 Alexandre Spangaro * @@ -19,7 +19,7 @@ */ /** - * \file htdocs/compta/tva/reglement.php + * \file htdocs/compta/tva/list.php * \ingroup tax * \brief List of VAT payments */ @@ -31,11 +31,11 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; -$langs->load("compta"); -$langs->load("bills"); +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); // Security check -$socid = isset($_GET["socid"])?$_GET["socid"]:''; +$socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -46,7 +46,7 @@ $search_account = GETPOST('search_account','int'); $month = GETPOST("month","int"); $year = GETPOST("year","int"); -$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit; +$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -100,7 +100,7 @@ $bankstatic = new Account($db); $sql = "SELECT t.rowid, t.amount, t.label, t.datev, t.datep, t.fk_typepayment as type, t.num_payment, t.fk_bank, pst.code as payment_code,"; $sql.= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id AND pst.entity IN (".getEntity('c_paiement').")"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql.= " WHERE t.entity IN (".getEntity('tax').")"; @@ -141,13 +141,19 @@ if ($result) $num = $db->num_rows($result); $i = 0; $total = 0 ; - $var=true; $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; if ($typeid) $param.='&typeid='.$typeid; + $newcardbutton=''; + if ($user->rights->tax->charges->creer) + { + $newcardbutton=''.$langs->trans('NewVATPayment'); + $newcardbutton.= ''; + $newcardbutton.= ''; + } print ''; if ($optioncss != '') print ''; @@ -157,23 +163,23 @@ if ($result) print ''; print ''; - print_barre_liste($langs->trans("VATPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$totalnboflines, 'title_accountancy', 0, '', '', $limit); + print_barre_liste($langs->trans("VATPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$totalnboflines, 'title_accountancy', 0, $newcardbutton, '', $limit); print '
'; print '
' . $langs->trans("VATDue") . '' . $langs->trans("VATDue") . '' . price(price2num($total, 'MT')) . '
' . $langs->trans("VATRestopay") . '' . $langs->trans("RemainToPay") . '' . price(price2num($restopay, 'MT')) . '
'; print ''; - print ''; - print ''; + print ''; + print ''; print ''; - print ''; // Type print ''; // Account if (! empty($conf->banque->enabled)) @@ -192,7 +198,7 @@ if ($result) print ''; print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"t.rowid","",$param,"",$sortfield,$sortorder); print_liste_field_titre("Label",$_SERVER["PHP_SELF"],"t.label","",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre("DateValue",$_SERVER["PHP_SELF"],"t.datev","",$param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre("PeriodEndDate",$_SERVER["PHP_SELF"],"t.datev","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"t.datep","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"type","",$param,'align="left"',$sortfield,$sortorder); if (! empty($conf->banque->enabled)) print_liste_field_titre("Account",$_SERVER["PHP_SELF"],"ba.label","",$param,"",$sortfield,$sortorder); @@ -259,7 +265,7 @@ if ($result) $colspan=5; if (! empty($conf->banque->enabled)) $colspan++; print ''; - print ""; + print ''; print ""; print "
'; - print ''; + print ''; + print ''; $syear = $year; $formother->select_year($syear?$syear:-1,'year',1, 20, 5); print ''; - $form->select_types_paiements($typeid,'typeid','',0,0,1,16); + $form->select_types_paiements($typeid,'typeid','',0,1,1,16); print '
'.$langs->trans("Total").'".price($total)."'.price($total).' 
"; diff --git a/htdocs/compta/tva/quadri.php b/htdocs/compta/tva/quadri.php deleted file mode 100644 index 6d33c358af2..00000000000 --- a/htdocs/compta/tva/quadri.php +++ /dev/null @@ -1,317 +0,0 @@ - - * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2004-2008 Laurent Destailleur - * Copyright (C) 2006 Yannick Warnier - * Copyright (C) 2005-2009 Regis Houssin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/compta/tva/quadri.php - * \ingroup tax - * \brief Trimestrial page - * TODO Deal with recurrent invoices as well - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; - -$year = GETPOST('year', 'int'); -if ($year == 0 ) -{ - $year_current = strftime("%Y",time()); - $year_start = $year_current; -} else { - $year_current = $year; - $year_start = $year; -} - -// Security check -$socid = isset($_GET["socid"])?$_GET["socid"]:''; -if ($user->societe_id) $socid=$user->societe_id; -$result = restrictedArea($user, 'tax', '', '', 'charges'); - - -/** - * Gets VAT to collect for the given month of the given year - * The function gets the VAT in split results, as the VAT declaration asks - * to report the amounts for different VAT rates as different lines. - * This function also accounts recurrent invoices. - * - * @param DoliDB $db Database handler - * @param int $y Year - * @param int $q Year quarter (1-4) - * @return array - */ -function tva_coll($db,$y,$q) -{ - global $conf; - - if ($conf->global->ACCOUNTING_MODE == "CREANCES-DETTES") - { - // if vat paid on due invoices - $sql = "SELECT d.fk_facture as facid, f.facnumber as facnum, d.tva_tx as rate, d.total_ht as totalht, d.total_tva as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."facturedet as d" ; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND f.fk_statut in (1,2)"; - $sql.= " AND f.rowid = d.fk_facture "; - $sql.= " AND date_format(f.datef,'%Y') = '".$y."'"; - $sql.= " AND (date_format(f.datef,'%m') > ".(($q-1)*3); - $sql.= " AND date_format(f.datef,'%m') <= ".($q*3).")"; - $sql.= " ORDER BY rate, facid"; - - } - else - { - // if vat paid on paiments - } - - $resql = $db->query($sql); - - if ($resql) - { - $list = array(); - $rate = -1; - while($assoc = $db->fetch_array($resql)) - { - if($assoc['rate'] != $rate){ //new rate - $list[$assoc['rate']]['totalht'] = $assoc['totalht']; - $list[$assoc['rate']]['vat'] = $assoc['amount']; - $list[$assoc['rate']]['facid'][] = $assoc['facid']; - $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; - }else{ - $list[$assoc['rate']]['totalht'] += $assoc['totalht']; - $list[$assoc['rate']]['vat'] += $assoc['amount']; - if(!in_array($assoc['facid'],$list[$assoc['rate']]['facid'])){ - $list[$assoc['rate']]['facid'][] = $assoc['facid']; - $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; - } - } - $rate = $assoc['rate']; - } - return $list; - } - else - { - dol_print_error($db); - } -} - - -/** - * Gets VAT to pay for the given month of the given year - * The function gets the VAT in split results, as the VAT declaration asks - * to report the amounts for different VAT rates as different lines - * - * @param DoliDB $db Database handler object - * @param int $y Year - * @param int $q Year quarter (1-4) - * @return array - */ -function tva_paye($db, $y,$q) -{ - global $conf; - - if ($conf->global->ACCOUNTING_MODE == "CREANCES-DETTES") - { - // Si on paye la tva sur les factures dues (non brouillon) - $sql = "SELECT d.fk_facture_fourn as facid, f.ref_supplier as facnum, d.tva_tx as rate, d.total_ht as totalht, d.tva as amount"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - $sql.= ", ".MAIN_DB_PREFIX."facture_fourn_det as d" ; - $sql.= ", ".MAIN_DB_PREFIX."societe as s"; - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND f.entity = ".$conf->entity; - $sql.= " AND f.fk_statut = 1 "; - $sql.= " AND f.rowid = d.fk_facture_fourn "; - $sql.= " AND date_format(f.datef,'%Y') = '".$y."'"; - $sql.= " AND (round(date_format(f.datef,'%m')) > ".(($q-1)*3); - $sql.= " AND round(date_format(f.datef,'%m')) <= ".($q*3).")"; - $sql.= " ORDER BY rate, facid "; - } - else - { - // Si on paye la tva sur les payments - } - - $resql = $db->query($sql); - if ($resql) - { - $list = array(); - $rate = -1; - while($assoc = $db->fetch_array($resql)) - { - if($assoc['rate'] != $rate){ //new rate - $list[$assoc['rate']]['totalht'] = $assoc['totalht']; - $list[$assoc['rate']]['vat'] = $assoc['amount']; - $list[$assoc['rate']]['facid'][] = $assoc['facid']; - $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; - }else{ - $list[$assoc['rate']]['totalht'] += $assoc['totalht']; - $list[$assoc['rate']]['vat'] += $assoc['amount']; - if(!in_array($assoc['facid'],$list[$assoc['rate']]['facid'])){ - $list[$assoc['rate']]['facid'][] = $assoc['facid']; - $list[$assoc['rate']]['facnum'][] = $assoc['facnum']; - } - } - $rate = $assoc['rate']; - } - return $list; - - } - else - { - dol_print_error($db); - } -} - - -/** - * View - */ - -llxHeader(); - -$textprevyear="".img_previous().""; -$textnextyear=" ".img_next().""; - -print load_fiche_titre($langs->trans("VAT"),"$textprevyear ".$langs->trans("Year")." $year_start $textnextyear"); - - -echo ''; -echo ''; - -echo ''; - -print "
'; -print load_fiche_titre($langs->trans("VATSummary")); -echo '
"; -print ""; -print ""; -print ""; -print ""; -print ""; -print ""; -print ""; -print ""; -print ""; -print "\n"; - -if ($conf->global->ACCOUNTING_MODE == "CREANCES-DETTES") -{ - $y = $year_current; - - $total = 0; $subtotal = 0; - $i=0; - $subtot_coll_total = 0; - $subtot_coll_vat = 0; - $subtot_paye_total = 0; - $subtot_paye_vat = 0; - for ($q = 1 ; $q <= 4 ; $q++) { - print ""; - $var=true; - - $x_coll = tva_coll($db, $y, $q); - $x_paye = tva_paye($db, $y, $q); - $x_both = array(); - //now, from these two arrays, get another array with one rate per line - foreach(array_keys($x_coll) as $my_coll_rate){ - $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; - $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; - $x_both[$my_coll_rate]['paye']['totalht'] = 0; - $x_both[$my_coll_rate]['paye']['vat'] = 0; - $x_both[$my_coll_rate]['coll']['links'] = ''; - foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy){ - $x_both[$my_coll_rate]['coll']['links'] .= '..'.substr($x_coll[$my_coll_rate]['facnum'][$id],-2).' '; - } - } - foreach(array_keys($x_paye) as $my_paye_rate){ - $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; - $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; - if(!isset($x_both[$my_paye_rate]['coll']['totalht'])){ - $x_both[$my_paye_rate]['coll']['total_ht'] = 0; - $x_both[$my_paye_rate]['coll']['vat'] = 0; - } - $x_both[$my_paye_rate]['paye']['links'] = ''; - foreach($x_paye[$my_paye_rate]['facid'] as $id=>$dummy){ - $x_both[$my_paye_rate]['paye']['links'] .= '..'.substr($x_paye[$my_paye_rate]['facnum'][$id],-2).' '; - } - } - //now we have an array (x_both) indexed by rates for coll and paye - - $x_coll_sum = 0; - $x_coll_ht = 0; - $x_paye_sum = 0; - $x_paye_ht = 0; - foreach($x_both as $rate => $both){ - - print ''; - print ""; - print ""; - print ""; - print ""; - print ""; - print ""; - print ""; - print ""; - print ""; - $x_coll_sum += $both['coll']['vat']; - $x_paye_sum += $both['paye']['vat']; - $subtot_coll_total += $both['coll']['totalht']; - $subtot_coll_vat += $both['coll']['vat']; - $subtot_paye_total += $both['paye']['totalht']; - $subtot_paye_vat += $both['paye']['vat']; - } - - $diff = $x_coll_sum - $x_paye_sum; - $total = $total + $diff; - $subtotal = $subtotal + $diff; - - - print ''; - print ''; - print "\n"; - print "\n"; - - $i++; - } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - -} -else -{ - print ''; - print ''; -} - -print '
".$langs->trans("Year")." $year_current".$langs->trans("Income")."".$langs->trans("VATToPay")."".$langs->trans("Invoices")."".$langs->trans("Outcome")."".$langs->trans("VATToCollect")."".$langs->trans("Invoices")."".$langs->trans("TotalToPay")."
".$langs->trans("Quadri")." $q (".dol_print_date(dol_mktime(0,0,0,(($q-1)*3)+1,1,$y),"%b %Y").' - '.dol_print_date(dol_mktime(0,0,0,($q*3),1,$y),"%b %Y").")
$rate%".price($both['coll']['totalht'])."".price($both['coll']['vat'])."".$both['coll']['links']."".price($both['paye']['totalht'])."".price($both['paye']['vat'])."".$both['paye']['links']."
".price($diff)."
'.$langs->trans("Total").':'.price($subtot_coll_total).''.price($subtot_coll_vat).''.price($subtot_paye_total).''.price($subtot_paye_vat).''.price($total).''; - print '
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("FeatureIsSupportedInInOutModeOnly").'
'; -echo ''; -echo ''; - -llxFooter(); -$db->close(); diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php index 5a05ef5974f..e2c7cc5d793 100644 --- a/htdocs/compta/tva/quadri_detail.php +++ b/htdocs/compta/tva/quadri_detail.php @@ -1,10 +1,9 @@ - * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2004-2013 Laurent Destailleur - * Copyright (C) 2006-2007 Yannick Warnier - * Copyright (C) 2014 Ferran Marcet - * Copyright (C) 2016 Alexandre Spangaro +/* Copyright (C) 2001-2003 Rodolphe Quiedeville + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2006-2007, 2015 Yannick Warnier + * Copyright (C) 2014 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -21,10 +20,9 @@ */ /** - * \file htdocs/compta/tva/quadri_detail.php - * \ingroup tax - * \brief Trimestrial page - detailed version - * TODO Deal with recurrent invoices as well + * \file htdocs/compta/tva/quadri_detail.php + * \ingroup tax + * \brief VAT by rate */ require '../../main.inc.php'; @@ -32,6 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; @@ -40,12 +39,8 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php'; -$langs->load("bills"); -$langs->load("compta"); -$langs->load("companies"); -$langs->load("products"); -$langs->load("trips"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array("other","compta","banks","bills","companies","product","trips","admin")); // Date range $year=GETPOST("year","int"); @@ -62,32 +57,34 @@ $date_end=dol_mktime(23,59,59,GETPOST("date_endmonth"),GETPOST("date_endday"),GE // Quarter if (empty($date_start) || empty($date_end)) // We define date_start and date_end { - $q=GETPOST("q"); + $q=GETPOST("q","int"); if (empty($q)) { - if (GETPOST("month")) { $date_start=dol_get_first_day($year_start,GETPOST("month"),false); $date_end=dol_get_last_day($year_start,GETPOST("month"),false); } + if (GETPOST("month","int")) { $date_start=dol_get_first_day($year_start,GETPOST("month","int"),false); $date_end=dol_get_last_day($year_start,GETPOST("month","int"),false); } else { - $month_current = strftime("%m",dol_now()); - if ($month_current >= 10) $q=4; - elseif ($month_current >= 7) $q=3; - elseif ($month_current >= 4) $q=2; - else $q=1; + $date_start=dol_get_first_day($year_start,empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START,false); + if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end=dol_time_plus_duree($date_start, 3, 'm') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end=dol_time_plus_duree($date_start, 1, 'y') - 1; + else if ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end=dol_time_plus_duree($date_start, 1, 'm') - 1; } } - if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } - if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } - if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } - if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + else + { + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } + } } -$min = GETPOST("min"); +$min = price2num(GETPOST("min","alpha")); if (empty($min)) $min = 0; // Define modetax (0 or 1) -// 0=normal, 1=option vat for services is on debit +// 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (isset($_REQUEST["modetax"])) $modetax=$_REQUEST["modetax"]; +if (GETPOSTISSET("modetax")) $modetax=GETPOST("modetax",'int'); if (empty($modetax)) $modetax=0; // Security check @@ -101,17 +98,7 @@ $result = restrictedArea($user, 'tax', '', '', 'charges'); * View */ -$morequerystring=''; -$listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday'); -foreach($listofparams as $param) -{ - if (GETPOST($param)!='') $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); -} - -llxHeader('',$langs->trans("VATReport"),'','',0,0,'','',$morequerystring); - $form=new Form($db); - $company_static=new Societe($db); $invoice_customer=new Facture($db); $invoice_supplier=new FactureFournisseur($db); @@ -121,6 +108,16 @@ $payment_static=new Paiement($db); $paymentfourn_static=new PaiementFourn($db); $paymentexpensereport_static=new PaymentExpenseReport($db); +$morequerystring=''; +$listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday'); +foreach ($listofparams as $param) +{ + if (GETPOST($param)!='') $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); +} + +llxHeader('',$langs->trans("VATReport"),'','',0,0,'','',$morequerystring); + + //print load_fiche_titre($langs->trans("VAT"),""); //$fsearch.='
'; @@ -130,160 +127,139 @@ $fsearch.=' '; //$fsearch.=' '; -// Affiche en-tete du rapport -if ($modetax==1) // Calculate on invoice for goods and services -{ - $name=$langs->trans("VATReportByQuartersInDueDebtMode"); - $calcmode=$langs->trans("CalcModeVATDebt"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - $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); - $prevyear=$year_start; $prevquarter=$q; - if ($prevquarter > 1) $prevquarter--; - else { $prevquarter=4; $prevyear--; } - $nextyear=$year_start; $nextquarter=$q; - if ($nextquarter < 4) $nextquarter++; - else { $nextquarter=1; $nextyear++; } - //$periodlink=($prevyear?"".img_previous()." ".img_next()."":""); - $description=$langs->trans("RulesVATDueServices"); - $description.='
'; - $description.=$langs->trans("RulesVATDueProducts"); - //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); - //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.='
'.$langs->trans("DepositsAreNotIncluded"); - else $description.='
'.$langs->trans("DepositsAreIncluded"); - $description.=$fsearch; - $builddate=dol_now(); - //$exportlink=$langs->trans("NotYetAvailable"); - - // Customers invoices - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("ProductOrService"); - $amountcust=$langs->trans("AmountHT"); - $vatcust=$langs->trans("VATReceived"); - if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')'; - - // Suppliers invoices - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$langs->trans("ProductOrService"); - $amountsup=$langs->trans("AmountHT"); - $vatsup=$langs->trans("VATPaid"); - if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; - +// Show report header +$name=$langs->trans("VATReportByRates"); +$calcmode=''; +if ($modetax == 0) $calcmode=$langs->trans('OptionVATDefault'); +if ($modetax == 1) $calcmode=$langs->trans('OptionVATDebitOption'); +if ($modetax == 2) $calcmode=$langs->trans('OptionPaymentForProductAndServices'); +$calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; +// Set period +$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); +$prevyear=$year_start; $prevquarter=$q; +if ($prevquarter > 1) { + $prevquarter--; +} else { + $prevquarter=4; $prevyear--; } -if ($modetax==0) // Invoice for goods, payment for services -{ - $name=$langs->trans("VATReportByQuartersInInputOutputMode"); - $calcmode=$langs->trans("CalcModeVATEngagement"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - $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); - $prevyear=$year_start; $prevquarter=$q; - if ($prevquarter > 1) $prevquarter--; - else { $prevquarter=4; $prevyear--; } - $nextyear=$year_start; $nextquarter=$q; - if ($nextquarter < 4) $nextquarter++; - else { $nextquarter=1; $nextyear++; } - //$periodlink=($prevyear?"".img_previous()." ".img_next()."":""); - $description=$langs->trans("RulesVATInServices"); - $description.=' '.$langs->trans("DepositsAreIncluded"); - $description.='
'; - $description.=$langs->trans("RulesVATInProducts"); - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.=' '.$langs->trans("DepositsAreNotIncluded"); - else $description.=' '.$langs->trans("DepositsAreIncluded"); - //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); - //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); - $description.=$fsearch; - $builddate=dol_now(); - //$exportlink=$langs->trans("NotYetAvailable"); - - // Customers invoices - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("ProductOrService"); - $amountcust=$langs->trans("AmountHT"); - $vatcust=$langs->trans("VATReceived"); - if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')'; - - // Suppliers invoices - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$langs->trans("ProductOrService"); - $amountsup=$langs->trans("AmountHT"); - $vatsup=$langs->trans("VATPaid"); - if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; - +$nextyear=$year_start; $nextquarter=$q; +if ($nextquarter < 4) { + $nextquarter++; +} else { + $nextquarter=1; $nextyear++; } +$description.=$fsearch; +$builddate=dol_now(); + +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description.=$langs->trans("RulesVATDueProducts"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description.=$langs->trans("RulesVATInProducts"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description.='
'.$langs->trans("RulesVATDueServices"); +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description.='
'.$langs->trans("RulesVATInServices"); +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description.='
'.$langs->trans("DepositsAreNotIncluded"); +} +if (! empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description.='
'.$langs->trans("ThisIsAnEstimatedValue"); + +// Customers invoices +$elementcust=$langs->trans("CustomersInvoices"); +$productcust=$langs->trans("ProductOrService"); +$amountcust=$langs->trans("AmountHT"); +$vatcust=$langs->trans("VATReceived"); +$namecust=$langs->trans("Name"); +if ($mysoc->tva_assuj) { + $vatcust.=' ('.$langs->trans("ToPay").')'; +} + +// Suppliers invoices +$elementsup=$langs->trans("SuppliersInvoices"); +$productsup=$productcust; +$amountsup=$amountcust; +$vatsup=$langs->trans("VATPaid"); +$namesup=$namecust; +if ($mysoc->tva_assuj) { + $vatsup.=' ('.$langs->trans("ToGetBack").')'; +} + + report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); $vatcust=$langs->trans("VATReceived"); $vatsup=$langs->trans("VATPaid"); $vatexpensereport=$langs->trans("VATPaid"); + // VAT Received and paid print ''; $y = $year_current; $total = 0; $i=0; +$columns = 5; // Load arrays of datas -$x_coll = tax_by_date('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); -$x_paye = tax_by_date('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); +$x_coll = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); +$x_paye = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); if (! is_array($x_coll) || ! is_array($x_paye)) { $langs->load("errors"); - if ($x_coll == -1) - print ''; - else if ($x_coll == -2) - print ''; - else - print ''; -} -else -{ + if ($x_coll == -1) { + print ''; + } else if ($x_coll == -2) { + print ''; + } else { + print ''; + } +} else { $x_both = array(); //now, from these two arrays, get another array with one rate per line foreach(array_keys($x_coll) as $my_coll_rate) { $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; - $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; + $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; $x_both[$my_coll_rate]['paye']['totalht'] = 0; $x_both[$my_coll_rate]['paye']['vat'] = 0; $x_both[$my_coll_rate]['coll']['links'] = ''; $x_both[$my_coll_rate]['coll']['detail'] = array(); - foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) - { + foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) { $invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; $invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; $invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; + $company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]); $x_both[$my_coll_rate]['coll']['detail'][] = array( - 'id' =>$x_coll[$my_coll_rate]['facid'][$id], - 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], - 'pid' =>$x_coll[$my_coll_rate]['pid'][$id], - 'pref' =>$x_coll[$my_coll_rate]['pref'][$id], - 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id], - 'payment_id' =>$x_coll[$my_coll_rate]['payment_id'][$id], - 'payment_amount' =>$x_coll[$my_coll_rate]['payment_amount'][$id], - 'ftotal_ttc' =>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], - 'dtotal_ttc' =>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], - 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], - 'ddate_start' =>$x_coll[$my_coll_rate]['ddate_start'][$id], - 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], - 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], - 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], - 'link' =>$invoice_customer->getNomUrl(1,'',12)); + 'id' =>$x_coll[$my_coll_rate]['facid'][$id], + 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], + 'pid' =>$x_coll[$my_coll_rate]['pid'][$id], + 'pref' =>$x_coll[$my_coll_rate]['pref'][$id], + 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id], + 'payment_id'=>$x_coll[$my_coll_rate]['payment_id'][$id], + 'payment_amount'=>$x_coll[$my_coll_rate]['payment_amount'][$id], + 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], + 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], + 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], + 'datef' =>$x_coll[$my_coll_rate]['datef'][$id], + 'datep' =>$x_coll[$my_coll_rate]['datep'][$id], + 'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id], + 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], + 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], + 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], + 'link' =>$invoice_customer->getNomUrl(1,'',12) + ); } } // tva paid - foreach(array_keys($x_paye) as $my_paye_rate){ + foreach (array_keys($x_paye) as $my_paye_rate) { $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; - if(!isset($x_both[$my_paye_rate]['coll']['totalht'])){ + if (!isset($x_both[$my_paye_rate]['coll']['totalht'])) { $x_both[$my_paye_rate]['coll']['totalht'] = 0; $x_both[$my_paye_rate]['coll']['vat'] = 0; } $x_both[$my_paye_rate]['paye']['links'] = ''; $x_both[$my_paye_rate]['paye']['detail'] = array(); - foreach($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) + foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) { // ExpenseReport if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') @@ -293,21 +269,21 @@ else $expensereport->type=$x_paye[$my_paye_rate]['type'][$id]; $x_both[$my_paye_rate]['paye']['detail'][] = array( - 'id' =>$x_paye[$my_paye_rate]['facid'][$id], - 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], - 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], - 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], - 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], - 'payment_id' =>$x_paye[$my_paye_rate]['payment_id'][$id], - 'payment_amount' =>$x_paye[$my_paye_rate]['payment_amount'][$id], - 'ftotal_ttc' =>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), - 'dtotal_ttc' =>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), - 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], - 'ddate_start' =>$x_paye[$my_paye_rate]['ddate_start'][$id], - 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], - 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), - 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], - 'link' =>$expensereport->getNomUrl(1) + 'id' =>$x_paye[$my_paye_rate]['facid'][$id], + 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], + 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], + 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id' =>$x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount' =>$x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc' =>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc' =>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'ddate_start' =>$x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], + 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], + 'link' =>$expensereport->getNomUrl(1) ); } else @@ -315,22 +291,26 @@ else $invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; $invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; $invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; + $company_static->fetch($x_paye[$my_paye_rate]['company_id'][$id]); $x_both[$my_paye_rate]['paye']['detail'][] = array( - 'id' =>$x_paye[$my_paye_rate]['facid'][$id], - 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], - 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], - 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], - 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], - 'payment_id' =>$x_paye[$my_paye_rate]['payment_id'][$id], - 'payment_amount' =>$x_paye[$my_paye_rate]['payment_amount'][$id], - 'ftotal_ttc' =>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), - 'dtotal_ttc' =>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), - 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], - 'ddate_start' =>$x_paye[$my_paye_rate]['ddate_start'][$id], - 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], - 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), - 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], - 'link' =>$invoice_supplier->getNomUrl(1,'',12) + 'id' =>$x_paye[$my_paye_rate]['facid'][$id], + 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], + 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], + 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id'=>$x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount'=>$x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'datef' =>$x_paye[$my_paye_rate]['datef'][$id], + 'datep' =>$x_paye[$my_paye_rate]['datep'][$id], + 'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], + 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], + 'link' =>$invoice_supplier->getNomUrl(1,'',12) ); } } @@ -345,16 +325,20 @@ else $x_paye_sum = 0; $x_paye_ht = 0; - $span=3; - if ($modetax == 0) $span+=2; + $span=$columns; + if ($modetax != 1) $span+=2; //print ''; // Customers invoices print ''; print ''; + print ''; + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; + else print ''; + print ''; print ''; - if ($modetax == 0) + if ($modetax != 1) { print ''; print ''; @@ -374,27 +358,29 @@ else $hookmanager->initHooks(array('externalbalance')); $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - foreach(array_keys($x_coll) as $rate) - { + foreach (array_keys($x_coll) as $rate) { $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; if (is_array($x_both[$rate]['coll']['detail'])) { // VAT Rate - $var=true; print ""; - print ''; + print ''; print ''."\n"; - foreach($x_both[$rate]['coll']['detail'] as $index => $fields) - { + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { // Define type - $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. - if (! empty($fields['ddate_start'])) $type=1; - if (! empty($fields['ddate_end'])) $type=1; + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } print ''; @@ -402,27 +388,45 @@ else // Ref print ''; + // Invoice date + print ''; + + // Payment date + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''; + else print ''; + + // Company name + print ''; + // Description print ''; // Total HT - if ($modetax == 0) + if ($modetax != 1) { print ''; } // Total collected print ''; // VAT print ''; @@ -487,45 +493,45 @@ else $x_coll_sum += $temp_vat; } } - // Total customers for this vat rate - print ''; - print ''; - print ''; - if ($modetax == 0) - { - print ''; - print ''; - } - print ''; - print ''; - print ''; + // Total customers for this vat rate + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; } - if (count($x_coll) == 0) // Show a total ine if nothing shown - { - print ''; - print ''; - print ''; - if ($modetax == 0) - { - print ''; - print ''; - } - print ''; - print ''; - print ''; - } + if (count($x_coll) == 0) // Show a total line if nothing shown + { + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } - // Blank line + // Blank line print ''; - //print table headers for this quadri - expenses now - //imprime les en-tete de tables pour ce quadri - maintenant les d�penses + // Print table headers for this quadri - expenses now print ''; print ''; + print ''; + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''; + else print ''; + print ''; print ''; - if ($modetax == 0) - { + if ($modetax != 1) { print ''; print ''; } @@ -533,25 +539,29 @@ else print ''; print ''."\n"; - foreach(array_keys($x_paye) as $rate) + foreach (array_keys($x_paye) as $rate) { $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; - if(is_array($x_both[$rate]['paye']['detail'])) + if (is_array($x_both[$rate]['paye']['detail'])) { - $var=true; print ""; - print ''; + print ''; print ''."\n"; - foreach($x_both[$rate]['paye']['detail'] as $index=>$fields) - { + + foreach ($x_both[$rate]['paye']['detail'] as $index=>$fields) { // Define type - $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type=(isset($fields['dtype'])?$fields['dtype']:$fields['ptype']); // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. - if (! empty($fields['ddate_start'])) $type=1; - if (! empty($fields['ddate_end'])) $type=1; + if (!empty($fields['ddate_start'])) { + $type=1; + } + if (!empty($fields['ddate_end'])) { + $type=1; + } print ''; @@ -559,21 +569,45 @@ else // Ref print ''; + // Invoice date + print ''; + + // Payment date + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''; + else print ''; + + // Company name + print ''; + // Description print ''; // Total HT - if ($modetax == 0) + if ($modetax != 1) { print ''; } // VAT paid print ''; // VAT print ''; print ''; $subtot_paye_total_ht += $temp_ht; - $subtot_paye_vat += $temp_vat; - $x_paye_sum += $temp_vat; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; } } - // Total suppliers for this vat rate - print ''; - print ''; - print ''; - if ($modetax == 0) - { - print ''; - print ''; - } - print ''; - print ''; - print ''; + // Total suppliers for this vat rate + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; } - if (count($x_paye) == 0) // Show a total line if nothing shown - { - print ''; - print ''; - print ''; - if ($modetax == 0) - { - print ''; - print ''; - } - print ''; - print ''; - print ''; + if (count($x_paye) == 0) { // Show a total line if nothing shown + print ''; + print ''; + print ''; + if ($modetax != 1) { + print ''; + print ''; + } + print ''; + print ''; + print ''; } - print '
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("Error") . '
'..')
'.$elementcust.''.$langs->trans("DateInvoice").''.$langs->trans("DatePayment").''.$namecust.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')
'.$langs->trans("Rate").': '.vatrate($rate).'%'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].'' . dol_print_date($fields['datef'], 'day') . '' . dol_print_date($fields['datep'], 'day') . '' . $fields['company_link'] . ''; if ($fields['pid']) { $product_static->id=$fields['pid']; $product_static->ref=$fields['pref']; - $product_static->type=$fields['ptype']; + $product_static->type=$fields['dtype']; // We force with the type of line to have type how line is registered print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); + } } else { - if ($type) $text = img_object($langs->trans('Service'),'service'); - else $text = img_object($langs->trans('Product'),'product'); - if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) - { - if ($reg[1]=='DEPOSIT') $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); - elseif ($reg[1]=='CREDIT_NOTE') $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); - else $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); + if ($type) { + $text = img_object($langs->trans('Service'),'service'); + } else { + $text = img_object($langs->trans('Product'),'product'); } - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) { + if ($reg[1]=='DEPOSIT') { + $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); + } elseif ($reg[1]=='CREDIT_NOTE') { + $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); + } else { + $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); + } + } + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); // Show range print_date_range($fields['ddate_start'],$fields['ddate_end']); @@ -430,7 +434,7 @@ else print ''; print price($fields['totalht']); @@ -445,9 +449,8 @@ else // Payment $ratiopaymentinvoice=1; - if ($modetax == 0) + if ($modetax != 1) { - if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); print ''; //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; if ($fields['payment_amount'] && $fields['ftotal_ttc']) @@ -455,28 +458,31 @@ else $payment_static->id=$fields['payment_id']; print $payment_static->getNomUrl(2); } - if ($type == 0) + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { - print $langs->trans("NotUsedForGoods"); - } - else { - print price($fields['payment_amount']); - if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + print price(price2num($fields['payment_amount'],'MT')); + if (isset($fields['payment_amount'])) { + print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } } print ''; - $temp_ht=$fields['totalht']; - if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; print price(price2num($temp_ht,'MT'),1); print ''; - $temp_vat=$fields['vat']; - if ($type == 1) $temp_vat=$fields['vat']*$ratiopaymentinvoice; + $temp_vat=$fields['vat']*$ratiopaymentinvoice; print price(price2num($temp_vat,'MT'),1); //print price($fields['vat']); print '
'.$langs->trans("Total").':  '.price(price2num($subtot_coll_total_ht,'MT')).''.price(price2num($subtot_coll_vat,'MT')).'
'.$langs->trans("Total").':  '.price(price2num($subtot_coll_total_ht,'MT')).''.price(price2num($subtot_coll_vat,'MT')).'
 '.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
'.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
 
'.$elementsup.''.$langs->trans("DateInvoice").''.$langs->trans("DatePayment").''.$namesup.''.$productsup.''.$amountsup.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$vatsup.'
'.$langs->trans("Rate").': '.vatrate($rate).'%'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].'' . dol_print_date($fields['datef'], 'day') . '' . dol_print_date($fields['datep'], 'day') . '' . $fields['company_link'] . ''; if ($fields['pid']) { $product_static->id=$fields['pid']; $product_static->ref=$fields['pref']; - $product_static->type=$fields['ptype']; + $product_static->type=$fields['dtype']; // We force with the type of line to have type how line is registered print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); + } } else { - if ($type) $text = img_object($langs->trans('Service'),'service'); - else $text = img_object($langs->trans('Product'),'product'); - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + if ($type) { + $text = img_object($langs->trans('Service'),'service'); + } else { + $text = img_object($langs->trans('Product'),'product'); + } + if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) { + if ($reg[1]=='DEPOSIT') { + $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); + } elseif ($reg[1]=='CREDIT_NOTE') { + $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); + } else { + $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); + } + } + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),24); // Show range print_date_range($fields['ddate_start'],$fields['ddate_end']); @@ -581,7 +615,7 @@ else print ''; print price($fields['totalht']); @@ -596,83 +630,84 @@ else // Payment $ratiopaymentinvoice=1; - if ($modetax == 0) + if ($modetax != 1) { - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); print ''; if ($fields['payment_amount'] && $fields['ftotal_ttc']) { $paymentfourn_static->id=$fields['payment_id']; print $paymentfourn_static->getNomUrl(2); } - if ($type == 0) + + if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { - print $langs->trans("NotUsedForGoods"); + print $langs->trans("NA"); } else { - print price($fields['payment_amount']); - if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + } + print price(price2num($fields['payment_amount'],'MT')); + if (isset($fields['payment_amount'])) { + print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } } print ''; - $temp_ht=$fields['totalht']; - if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; print price(price2num($temp_ht,'MT'),1); print ''; - $temp_vat=$fields['vat']; - if ($type == 1) $temp_vat=$fields['vat']*$ratiopaymentinvoice; + $temp_vat=$fields['vat']*$ratiopaymentinvoice; print price(price2num($temp_vat,'MT'),1); //print price($fields['vat']); print '
 '.$langs->trans("Total").':  '.price(price2num($subtot_paye_total_ht,'MT')).''.price(price2num($subtot_paye_vat,'MT')).'
'.$langs->trans("Total").':  '.price(price2num($subtot_paye_total_ht,'MT')).''.price(price2num($subtot_paye_vat,'MT')).'
 '.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
'.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
'; + print ''; // Total to pay - print '

'; - print ''; - $diff = $x_coll_sum - $x_paye_sum; + print '

'; + print '
'; + $diff = $x_coll_sum - $x_paye_sum; print ''; print ''; print '\n"; @@ -680,7 +715,7 @@ else $i++; } -echo '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
'; +print ''; llxFooter(); $db->close(); diff --git a/htdocs/compta/tva/quarter_report.php b/htdocs/compta/tva/quarter_report.php deleted file mode 100644 index dd058c6ebc2..00000000000 --- a/htdocs/compta/tva/quarter_report.php +++ /dev/null @@ -1,713 +0,0 @@ - - * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2004-2013 Laurent Destailleur - * Copyright (C) 2006-2007, 2015 Yannick Warnier - * Copyright (C) 2014 Ferran Marcet - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (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/tva/quadri_detail.php - * \ingroup tax - * \brief Trimestrial page - detailed version - * TODO Deal with recurrent invoices as well - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; -require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; - -$langs->load("main"); -$langs->load("bills"); -$langs->load("compta"); -$langs->load("companies"); -$langs->load("products"); -$langs->load("other"); - -// Date range -$year=GETPOST('year', 'int'); -if (empty($year)) { - $year_current = strftime("%Y",dol_now()); - $year_start = $year_current; -} else { - $year_current = $year; - $year_start = $year; -} -$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]); -$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]); -// Quarter -if (empty($date_start) || empty($date_end)) { // We define date_start and date_end - $q=GETPOST('q', 'int'); - if (empty($q)) { - if (isset($_REQUEST["month"])) { - $date_start=dol_get_first_day($year_start,$_REQUEST["month"],false); - $date_end=dol_get_last_day($year_start,$_REQUEST["month"],false); - } else { - $month_current = strftime("%m",dol_now()); - if ($month_current >= 10) $q=4; - elseif ($month_current >= 7) $q=3; - elseif ($month_current >= 4) $q=2; - else $q=1; - } - } - if ($q==1) { - $date_start=dol_get_first_day($year_start,1,false); - $date_end=dol_get_last_day($year_start,3,false); - } - if ($q==2) { - $date_start=dol_get_first_day($year_start,4,false); - $date_end=dol_get_last_day($year_start,6,false); - } - if ($q==3) { - $date_start=dol_get_first_day($year_start,7,false); - $date_end=dol_get_last_day($year_start,9,false); - } - if ($q==4) { - $date_start=dol_get_first_day($year_start,10,false); - $date_end=dol_get_last_day($year_start,12,false); - } -} - -$min = GETPOST("min"); -if (empty($min)) { - $min = 0; -} - -// Define modetax (0 or 1) -// 0=normal, 1=option vat for services is on debit -$modetax = $conf->global->TAX_MODE; -if (isset($_REQUEST["modetax"])) { - $modetax=$_REQUEST["modetax"]; -} -if (empty($modetax)) { - $modetax=0; -} - -// Security check -$socid = GETPOST('socid','int'); -if ($user->societe_id) { - $socid=$user->societe_id; -} -$result = restrictedArea($user, 'tax', '', '', 'charges'); - - - -/* - * View - */ - -$morequerystring=''; -$listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday'); -foreach ($listofparams as $param) { - if (GETPOST($param)!='') { - $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); - } -} - -llxHeader('','','','',0,0,'','',$morequerystring); - -$form=new Form($db); - -$company_static=new Societe($db); -$invoice_customer=new Facture($db); -$invoice_supplier=new FactureFournisseur($db); -$product_static=new Product($db); -$payment_static=new Paiement($db); -$paymentfourn_static=new PaiementFourn($db); - -//print load_fiche_titre($langs->trans("VAT"),""); - -//$fsearch.='
'; -$fsearch.=' '; -$fsearch.=' '; -//$fsearch.=' '.$langs->trans("SalesTurnoverMinimum").': '; -//$fsearch.=' '; - - -// Affiche en-tete du rapport -if ($modetax==1) { // Calculate on invoice for goods and services - $name=$langs->trans("VATReportByQuartersInDueDebtMode"); - $calcmode=$langs->trans("CalcModeVATDebt"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - $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); - $prevyear=$year_start; $prevquarter=$q; - if ($prevquarter > 1) { - $prevquarter--; - } else { - $prevquarter=4; $prevyear--; - } - $nextyear=$year_start; $nextquarter=$q; - if ($nextquarter < 4) { - $nextquarter++; - } else { - $nextquarter=1; $nextyear++; - } - //$periodlink=($prevyear?"".img_previous()." ".img_next()."":""); - $description=$langs->trans("RulesVATDueServices"); - $description.='
'; - $description.=$langs->trans("RulesVATDueProducts"); - //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); - //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $description.='
'.$langs->trans("DepositsAreNotIncluded"); - } else { - $description.='
'.$langs->trans("DepositsAreIncluded"); - } - $description.=$fsearch; - $builddate=dol_now(); - //$exportlink=$langs->trans("NotYetAvailable"); - - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("ProductOrService"); - $amountcust=$langs->trans("AmountHT"); - $vatcust=$langs->trans("VATReceived"); - $namecust=$langs->trans("Name"); - if ($mysoc->tva_assuj) { - $vatcust.=' ('.$langs->trans("ToPay").')'; - } - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$langs->trans("ProductOrService"); - $amountsup=$langs->trans("AmountHT"); - $vatsup=$langs->trans("VATPaid"); - $namesup=$namecust; - if ($mysoc->tva_assuj) { - $vatsup.=' ('.$langs->trans("ToGetBack").')'; - } -} -if ($modetax==0) { // Invoice for goods, payment for services - $name=$langs->trans("VATReportByQuartersInInputOutputMode"); - $calcmode=$langs->trans("CalcModeVATEngagement"); - $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - $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); - $prevyear=$year_start; $prevquarter=$q; - if ($prevquarter > 1) { - $prevquarter--; - } else { - $prevquarter=4; $prevyear--; - } - $nextyear=$year_start; $nextquarter=$q; - if ($nextquarter < 4) { - $nextquarter++; - } else { - $nextquarter=1; $nextyear++; - } - //$periodlink=($prevyear?"".img_previous()." ".img_next()."":""); - $description=$langs->trans("RulesVATInServices"); - $description.=' '.$langs->trans("DepositsAreIncluded"); - $description.='
'; - $description.=$langs->trans("RulesVATInProducts"); - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { - $description.=' '.$langs->trans("DepositsAreNotIncluded"); - } else { - $description.=' '.$langs->trans("DepositsAreIncluded"); - } - //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); - //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); - $description.=$fsearch; - $builddate=dol_now(); - //$exportlink=$langs->trans("NotYetAvailable"); - - $elementcust=$langs->trans("CustomersInvoices"); - $productcust=$langs->trans("ProductOrService"); - $amountcust=$langs->trans("AmountHT"); - $vatcust=$langs->trans("VATReceived"); - $namecust=$langs->trans("Name"); - if ($mysoc->tva_assuj) { - $vatcust.=' ('.$langs->trans("ToPay").')'; - } - $elementsup=$langs->trans("SuppliersInvoices"); - $productsup=$productcust; - $amountsup=$amountcust; - $vatsup=$langs->trans("VATPaid"); - $namesup=$namecust; - if ($mysoc->tva_assuj) { - $vatsup.=' ('.$langs->trans("ToGetBack").')'; - } -} -report_header($name,'',$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); - -$vatcust=$langs->trans("VATReceived"); -$vatsup=$langs->trans("VATPaid"); - - -// VAT Received and paid - -print ''; - -$y = $year_current; -$total = 0; -$i=0; -$columns = 6; - -// Load arrays of datas -$x_coll = tax_by_date('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); -$x_paye = tax_by_date('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); - -if (!is_array($x_coll) || !is_array($x_paye)) { - $langs->load("errors"); - if ($x_coll == -1) { - print ''; - } else if ($x_coll == -2) { - print ''; - } else { - print ''; - } -} else { - $x_both = array(); - //now, from these two arrays, get another array with one rate per line - foreach(array_keys($x_coll) as $my_coll_rate) { - $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; - $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; - $x_both[$my_coll_rate]['paye']['totalht'] = 0; - $x_both[$my_coll_rate]['paye']['vat'] = 0; - $x_both[$my_coll_rate]['coll']['links'] = ''; - $x_both[$my_coll_rate]['coll']['detail'] = array(); - foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) { - $invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; - $invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; - $invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; - $company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]); - $x_both[$my_coll_rate]['coll']['detail'][] = array( - 'id' =>$x_coll[$my_coll_rate]['facid'][$id], - 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], - 'pid' =>$x_coll[$my_coll_rate]['pid'][$id], - 'pref' =>$x_coll[$my_coll_rate]['pref'][$id], - 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id], - 'payment_id'=>$x_coll[$my_coll_rate]['payment_id'][$id], - 'payment_amount'=>$x_coll[$my_coll_rate]['payment_amount'][$id], - 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], - 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], - 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], - 'datef' =>$x_coll[$my_coll_rate]['datef'][$id], - 'company_link'=>$company_static->getNomUrl(1,'',20), - 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id], - 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], - 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], - 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], - 'link' =>$invoice_customer->getNomUrl(1,'',12) - ); - } - } - // tva paid - foreach (array_keys($x_paye) as $my_paye_rate) { - $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; - $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; - if (!isset($x_both[$my_paye_rate]['coll']['totalht'])) { - $x_both[$my_paye_rate]['coll']['totalht'] = 0; - $x_both[$my_paye_rate]['coll']['vat'] = 0; - } - $x_both[$my_paye_rate]['paye']['links'] = ''; - $x_both[$my_paye_rate]['paye']['detail'] = array(); - - foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) { - $invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; - $invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; - $invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; - $company_static->fetch($x_paye[$my_paye_rate]['company_id'][$id]); - $x_both[$my_paye_rate]['paye']['detail'][] = array( - 'id' =>$x_paye[$my_paye_rate]['facid'][$id], - 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], - 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], - 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], - 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], - 'payment_id'=>$x_paye[$my_paye_rate]['payment_id'][$id], - 'payment_amount'=>$x_paye[$my_paye_rate]['payment_amount'][$id], - 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), - 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), - 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], - 'datef' =>$x_paye[$my_paye_rate]['datef'][$id], - 'company_link'=>$company_static->getNomUrl(1,'',20), - 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id], - 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], - 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), - 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], - 'link' =>$invoice_supplier->getNomUrl(1,'',12) - ); - } - } - //now we have an array (x_both) indexed by rates for coll and paye - - - //print table headers for this quadri - incomes first - - $x_coll_sum = 0; - $x_coll_ht = 0; - $x_paye_sum = 0; - $x_paye_ht = 0; - - $span=$columns-3; - if ($modetax == 0) $span+=2; - - //print ''; - - // Customers invoices - print ''; - print ''; - print ''; - print ''; - print ''; - if ($modetax == 0) { - print ''; - print ''; - } - print ''; - print ''; - print ''; - - $action = "tvadetail"; - $parameters["mode"] = $modetax; - $parameters["start"] = $date_start; - $parameters["end"] = $date_end; - $parameters["type"] = 'vat'; - - $object = array(&$x_coll, &$x_paye, &$x_both); - // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array - $hookmanager->initHooks(array('externalbalance')); - $reshook=$hookmanager->executeHooks('addVatLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - - foreach (array_keys($x_coll) as $rate) { - $subtot_coll_total_ht = 0; - $subtot_coll_vat = 0; - - if (is_array($x_both[$rate]['coll']['detail'])) { - // VAT Rate - $var=true; - print ""; - print ''; - print ''."\n"; - - foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { - // Define type - $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type=1; - } - if (!empty($fields['ddate_end'])) { - $type=1; - } - - - print ''; - - // Ref - print ''; - - // Invoice date - print ''; - // Company name - print ''; - - // Description - print ''; - - // Total HT - if ($modetax == 0) { - print ''; - } - - // Payment - $ratiopaymentinvoice=1; - if ($modetax == 0) { - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { - $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); - } - print ''; - } - - // Total collected - print ''; - - // VAT - print ''; - print ''; - - $subtot_coll_total_ht += $temp_ht; - $subtot_coll_vat += $temp_vat; - $x_coll_sum += $temp_vat; - } - } - // Total customers for this vat rate - print ''; - print ''; - print ''; - if ($modetax == 0) { - print ''; - print ''; - } - print ''; - print ''; - print ''; - } - - if (count($x_coll) == 0) { // Show a total ine if nothing shown - print ''; - print ''; - print ''; - if ($modetax == 0) { - print ''; - print ''; - } - print ''; - print ''; - print ''; - } - - // Blank line - print ''; - - // Print table headers for this quadri - expenses now - print ''; - print ''; - print ''; - print ''; - print ''; - if ($modetax == 0) { - print ''; - print ''; - } - print ''; - print ''; - print ''."\n"; - - foreach (array_keys($x_paye) as $rate) { - $subtot_paye_total_ht = 0; - $subtot_paye_vat = 0; - - if (is_array($x_both[$rate]['paye']['detail'])) { - $var=true; - print ""; - print ''; - print ''."\n"; - - foreach ($x_both[$rate]['paye']['detail'] as $index=>$fields) { - // Define type - $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type=1; - } - if (!empty($fields['ddate_end'])) { - $type=1; - } - - - print ''; - - // Ref - print ''; - // Invoice date - print ''; - // Company name - print ''; - - // Description - print ''; - - // Total HT - if ($modetax == 0) { - print ''; - } - - // Payment - $ratiopaymentinvoice=1; - if ($modetax == 0) { - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { - $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); - } - print ''; - } - - // VAT paid - print ''; - - // VAT - print ''; - print ''; - - $subtot_paye_total_ht += $temp_ht; - $subtot_paye_vat += $temp_vat; - $x_paye_sum += $temp_vat; - } - } - // Total suppliers for this vat rate - print ''; - print ''; - print ''; - if ($modetax == 0) { - print ''; - print ''; - } - print ''; - print ''; - print ''; - } - - if (count($x_paye) == 0) { // Show a total line if nothing shown - print ''; - print ''; - print ''; - if ($modetax == 0) { - print ''; - print ''; - } - print ''; - print ''; - print ''; - } - - print '
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . $langs->trans("Error") . '
'..')
'.$elementcust.''.$langs->trans("Date").''.$namecust.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("AmountHTVATRealReceived").''.$vatcust.'
'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].'' . $fields['datef'] . '' . $fields['company_link'] . ''; - if ($fields['pid']) { - $product_static->id=$fields['pid']; - $product_static->ref=$fields['pref']; - $product_static->type=$fields['ptype']; - print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) { - print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); - } - } else { - if ($type) { - $text = img_object($langs->trans('Service'),'service'); - } else { - $text = img_object($langs->trans('Product'),'product'); - } - if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) { - if ($reg[1]=='DEPOSIT') { - $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); - } elseif ($reg[1]=='CREDIT_NOTE') { - $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); - } else { - $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); - } - } - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); - - // Show range - print_date_range($fields['ddate_start'],$fields['ddate_end']); - } - print ''; - print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) { - //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; - $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); - //print ' ('.round($ratiolineinvoice*100,2).'%)'; - } - print ''; - //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) { - $payment_static->id=$fields['payment_id']; - print $payment_static->getNomUrl(2); - } - if ($type == 0) { - print $langs->trans("NotUsedForGoods"); - } else { - print $fields['payment_amount']; - if (isset($fields['payment_amount'])) { - print ' ('.round($ratiopaymentinvoice*100,2).'%)'; - } - } - print ''; - $temp_ht=$fields['totalht']; - if ($type == 1) { - $temp_ht=$fields['totalht']*$ratiopaymentinvoice; - } - print price(price2num($temp_ht,'MT'),1); - print ''; - $temp_vat=$fields['vat']; - if ($type == 1) { - $temp_vat=$fields['vat']*$ratiopaymentinvoice; - } - print price(price2num($temp_vat,'MT'),1); - //print price($fields['vat']); - print '
'.$langs->trans("Total").':  '.price(price2num($subtot_coll_total_ht,'MT')).''.price(price2num($subtot_coll_vat,'MT')).'
'.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
 
'.$elementsup.''.$langs->trans("Date").''.$namesup.''.$productsup.''.$amountsup.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("AmountHTVATRealPaid").''.$vatsup.'
'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].'' . $fields['datef'] . '' . $fields['company_link'] . ''; - if ($fields['pid']) { - $product_static->id=$fields['pid']; - $product_static->ref=$fields['pref']; - $product_static->type=$fields['ptype']; - print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) { - print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); - } - } else { - if ($type) { - $text = img_object($langs->trans('Service'),'service'); - } else { - $text = img_object($langs->trans('Product'),'product'); - } - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); - - // Show range - print_date_range($fields['ddate_start'],$fields['ddate_end']); - } - print ''; - print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) { - //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; - $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); - //print ' ('.round($ratiolineinvoice*100,2).'%)'; - } - print ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) { - $paymentfourn_static->id=$fields['payment_id']; - print $paymentfourn_static->getNomUrl(2); - } - if ($type == 0) { - print $langs->trans("NotUsedForGoods"); - } else { - print $fields['payment_amount']; - if (isset($fields['payment_amount'])) { - print ' ('.round($ratiopaymentinvoice*100,2).'%)'; - } - } - print ''; - $temp_ht=$fields['totalht']; - if ($type == 1) { - $temp_ht=$fields['totalht']*$ratiopaymentinvoice; - } - print price(price2num($temp_ht,'MT'),1); - print ''; - $temp_vat=$fields['vat']; - if ($type == 1) { - $temp_vat=$fields['vat']*$ratiopaymentinvoice; - } - print price(price2num($temp_vat,'MT'),1); - //print price($fields['vat']); - print '
'.$langs->trans("Total").':  '.price(price2num($subtot_paye_total_ht,'MT')).''.price(price2num($subtot_paye_vat,'MT')).'
'.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
'; - - // Total to pay - print '

'; - print ''; - $diff = $x_coll_sum - $x_paye_sum; - print ''; - print ''; - print '\n"; - print "\n"; - - $i++; -} -print '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
'; - -llxFooter(); -$db->close(); diff --git a/htdocs/conf/conf.php.example b/htdocs/conf/conf.php.example index 356e76ba374..7475cf54ddb 100644 --- a/htdocs/conf/conf.php.example +++ b/htdocs/conf/conf.php.example @@ -238,6 +238,15 @@ $dolibarr_main_prod='0'; // $dolibarr_main_restrict_os_commands='mysqldump, mysql, pg_dump, pgrestore'; +// $dolibarr_main_restrict_ip +// To restrict access to backoffice to some ip addresses only. +// Note: Pages that does not need login (like public pages, web site) are not protected with this. +// Default value: '' +// Examples: +// $dolibarr_main_restrict_ip='127.0.0.1, 192.168.0.1'; +// +$dolibarr_main_restrict_ip=''; + // dolibarr_nocsrfcheck // This parameter can be used to disable CSRF protection. // This might be required if you access Dolibarr behind a proxy that make @@ -284,16 +293,6 @@ $dolibarr_nocsrfcheck='0'; // Examples: // $dolibarr_strict_mode=0; -// dolibarr_pdf_force_fpdf -// Set this to 1 to use the libray FPDF instead of TCPDF. FPDF is not embedded with Dolibarr, -// so you also have to uncomment line $dolibarr_lib_FPDF_PATH to provide path to FPDF library. -// Warning: FPDF does not support all features supported by TCPDF used by default. So using -// this library instead of TCPF will break some features like transparent logo, cyrillic, arab, -// and asiatic languages, total number of pages, ... -// Default value: 0 -// Examples: -// $dolibarr_pdf_force_fpdf=1; - //################################# diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php index c885f0869de..183433b02f9 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -44,10 +44,8 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; -$langs->load("companies"); -$langs->load("users"); -$langs->load("other"); -$langs->load("commercial"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'users', 'other', 'commercial')); $mesg=''; $error=0; $errors=array(); @@ -101,7 +99,7 @@ if (! $sortfield) $sortfield='a.datep, a.id'; if (! $sortorder) $sortorder='DESC'; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('contactcard','globalcard')); +$hookmanager->initHooks(array('contactagenda','globalcard')); /* @@ -190,7 +188,8 @@ else $object = new Contact($db); $res=$object->fetch($id, $user); if ($res < 0) { dol_print_error($db,$object->error); exit; } - $res=$object->fetch_optionals($object->id,$extralabels); + $res=$object->fetch_optionals(); + if ($res < 0) { dol_print_error($db,$object->error); exit; } // Show tabs $head = contact_prepare_head($object); diff --git a/htdocs/contact/canvas/actions_contactcard_common.class.php b/htdocs/contact/canvas/actions_contactcard_common.class.php index b5df91ce210..ba96c865d1a 100644 --- a/htdocs/contact/canvas/actions_contactcard_common.class.php +++ b/htdocs/contact/canvas/actions_contactcard_common.class.php @@ -43,34 +43,6 @@ abstract class ActionsContactCardCommon var $errors=array(); - /** - * Instantiation of DAO class - * - * @return int 0 - * @deprecated Using getInstanceDao should not be used. - */ - private function getInstanceDao() - { - dol_syslog(__METHOD__ . " is deprecated", LOG_WARNING); - - if (! is_object($this->object)) - { - $modelclassfile = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/dao_'.$this->targetmodule.'_'.$this->canvas.'.class.php'); - if (file_exists($modelclassfile)) - { - // Include dataservice class (model) - $ret = require_once $modelclassfile; - if ($ret) - { - // Instantiate dataservice class (model) - $modelclassname = 'Dao'.ucfirst($this->targetmodule).ucfirst($this->canvas); - $this->object = new $modelclassname($this->db); - } - } - } - return 0; - } - /** * Get object * @@ -93,141 +65,6 @@ abstract class ActionsContactCardCommon //} } - /** - * doActions of a canvas is not the doActions of the hook - * @deprecated Use the doActions of hooks instead of this. - * - * @param string $action Type of action - * @param int $id Id of object - * @return void - */ - function doActions(&$action, $id) - { - global $conf, $user, $langs; - - // Creation utilisateur depuis contact - if ($action == 'confirm_create_user' && GETPOST("confirm") == 'yes') - { - // Recuperation contact actuel - $result = $this->object->fetch($id); - - if ($result > 0) - { - $this->db->begin(); - - // Creation user - $nuser = new User($this->db); - $result=$nuser->create_from_contact($this->object,$_POST["login"]); - - if ($result > 0) - { - $result2=$nuser->setPassword($user,$_POST["password"],0,1,1); - if ($result2) - { - $this->db->commit(); - } - else - { - $this->db->rollback(); - } - } - else - { - $this->errors=$nuser->error; - - $this->db->rollback(); - } - } - else - { - $this->errors=$this->object->errors; - } - } - - // Creation contact - if ($action == 'add') - { - $this->assign_post(); - - if (! $_POST["name"]) - { - array_push($this->errors,$langs->trans("ErrorFieldRequired",$langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label"))); - $action = 'create'; - } - - if ($_POST["name"]) - { - $id = $this->object->create($user); - if ($id > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } - else - { - $this->errors=$this->object->errors; - $action = 'create'; - } - } - } - - if ($action == 'confirm_delete' && GETPOST("confirm") == 'yes') - { - $result=$this->object->fetch($id); - - $this->object->old_name = $_POST["old_name"]; - $this->object->old_firstname = $_POST["old_firstname"]; - - $result = $this->object->delete(); - if ($result > 0) - { - header("Location: list.php"); - exit; - } - else - { - $this->errors=$this->object->errors; - } - } - - if ($action == 'update') - { - if ($_POST["cancel"]) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$this->object->id); - exit; - } - - if (empty($_POST["name"])) - { - $this->error=array($langs->trans("ErrorFieldRequired",$langs->transnoentities("Name").' / '.$langs->transnoentities("Label"))); - $action = 'edit'; - } - - if (empty($this->error)) - { - $this->object->fetch($_POST["contactid"]); - - $this->object->oldcopy = clone $this->object; - - $this->assign_post(); - - $result = $this->object->update($_POST["contactid"], $user); - - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$this->object->id); - exit; - } - else - { - $this->errors=$this->object->errors; - $action = 'edit'; - } - } - } - } - /** * Set content of ->tpl array, to use into template * diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 36152275a64..52957d25343 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -42,10 +42,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT. '/core/class/html.form.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; -$langs->load("companies"); -$langs->load("users"); -$langs->load("other"); -$langs->load("commercial"); + +// Load translation files required by the page +$langs->loadLangs(array('companies', 'users', 'other', 'commercial')); $mesg=''; $error=0; $errors=array(); @@ -468,7 +467,8 @@ else $object = new Contact($db); $res=$object->fetch($id, $user); if ($res < 0) { dol_print_error($db,$object->error); exit; } - $res=$object->fetch_optionals($object->id,$extralabels); + $res=$object->fetch_optionals(); + if ($res < 0) { dol_print_error($db,$object->error); exit; } // Show tabs $head = contact_prepare_head($object); @@ -607,7 +607,15 @@ else // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { - print ''; + if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) + { + print ''; + } + else + { + print ''; + } + if ($object->country_id) { print $formcompany->select_state(GETPOST("state_id",'alpha')?GETPOST("state_id",'alpha'):$object->state_id,$object->country_code,'state_id'); @@ -677,7 +685,7 @@ else $parameters=array('socid' => $socid, 'objsoc' => $objsoc, 'colspan' => ' colspan="3"', 'cols' => 3); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } @@ -852,7 +860,15 @@ else // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { - print ''; + if(!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) + { + print ''; + } + else + { + print ''; + } + print $formcompany->select_state($object->state_id,isset($_POST["country_id"])?GETPOST("country_id"):$object->country_id,'state_id'); print ''; } @@ -946,7 +962,7 @@ else $parameters=array('colspan' => ' colspan="3"', 'cols'=>3); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook) && ! empty($extrafields->attribute_label)) + if (empty($reshook)) { print $object->showOptionals($extrafields,'edit'); } diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 036ee75a43d..59ca7caaf99 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -204,7 +204,7 @@ class Contact extends CommonObject if (empty($this->priv)) $this->priv = 0; if (empty($this->statut)) $this->statut = 0; // This is to convert '' into '0' to avoid bad sql request - $entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity); + $this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity); $sql = "INSERT INTO ".MAIN_DB_PREFIX."socpeople ("; $sql.= " datec"; @@ -220,15 +220,15 @@ class Contact extends CommonObject $sql.= ", import_key"; $sql.= ") VALUES ("; $sql.= "'".$this->db->idate($now)."',"; - if ($this->socid > 0) $sql.= " ".$this->socid.","; + if ($this->socid > 0) $sql.= " ".$this->db->escape($this->socid).","; else $sql.= "null,"; $sql.= "'".$this->db->escape($this->lastname)."',"; $sql.= "'".$this->db->escape($this->firstname)."',"; - $sql.= " ".($user->id > 0 ? "'".$user->id."'":"null").","; - $sql.= " ".$this->priv.","; - $sql.= " ".$this->statut.","; + $sql.= " ".($user->id > 0 ? "'".$this->db->escape($user->id)."'":"null").","; + $sql.= " ".$this->db->escape($this->priv).","; + $sql.= " ".$this->db->escape($this->statut).","; $sql.= " ".(! empty($this->canvas)?"'".$this->db->escape($this->canvas)."'":"null").","; - $sql.= " ".$entity.","; + $sql.= " ".$this->db->escape($this->entity).","; $sql.= "'".$this->db->escape($this->ref_ext)."',"; $sql.= " ".(! empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null"); $sql.= ")"; @@ -307,6 +307,8 @@ class Contact extends CommonObject $this->id = $id; + $this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity); + // Clean parameters $this->lastname=trim($this->lastname)?trim($this->lastname):trim($this->lastname); $this->firstname=trim($this->firstname); @@ -350,10 +352,11 @@ class Contact extends CommonObject $sql .= ", phone_mobile = ".(isset($this->phone_mobile)?"'".$this->db->escape($this->phone_mobile)."'":"null"); $sql .= ", jabberid = ".(isset($this->jabberid)?"'".$this->db->escape($this->jabberid)."'":"null"); $sql .= ", priv = '".$this->db->escape($this->priv)."'"; - $sql .= ", statut = ".$this->statut; + $sql .= ", statut = ".$this->db->escape($this->statut); $sql .= ", fk_user_modif=".($user->id > 0 ? "'".$this->db->escape($user->id)."'":"NULL"); $sql .= ", default_lang=".($this->default_lang?"'".$this->db->escape($this->default_lang)."'":"NULL"); $sql .= ", no_email=".($this->no_email?"'".$this->db->escape($this->no_email)."'":"0"); + $sql .= ", entity = " . $this->db->escape($this->entity); $sql .= " WHERE rowid=".$this->db->escape($id); dol_syslog(get_class($this)."::update", LOG_DEBUG); @@ -367,22 +370,15 @@ class Contact extends CommonObject $action='update'; - // Actions on extra fields (by external module or standard code) - $hookmanager->initHooks(array('contactdao')); - $parameters=array('socid'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) + // Actions on extra fields + if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + $result=$this->insertExtraFields(); + if ($result < 0) { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } + $error++; } } - else if ($reshook < 0) $error++; if (! $error && $this->user_id > 0) { @@ -531,7 +527,7 @@ class Contact extends CommonObject if ($this->phone_mobile && ! empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile; if ($this->fax && ! empty($conf->global->LDAP_CONTACT_FIELD_FAX)) $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax; if ($this->skype && ! empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype; - if ($this->note_private && ! empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = $this->note_private; + if ($this->note_private && ! empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); if ($this->email && ! empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email; if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') @@ -692,7 +688,10 @@ class Contact extends CommonObject $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid"; if ($id) $sql.= " WHERE c.rowid = ". $id; - elseif ($ref_ext) $sql .= " WHERE c.ref_ext = '".$this->db->escape($ref_ext)."'"; + elseif ($ref_ext) { + $sql .= " WHERE c.entity IN (".getEntity($this->element).")"; + $sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'"; + } $resql=$this->db->query($sql); if ($resql) @@ -806,12 +805,9 @@ class Contact extends CommonObject } } - // Retreive all extrafield for contact - // fetch optionals attributes and labels - require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); return 1; } @@ -1058,10 +1054,7 @@ class Contact extends CommonObject $sql.= " WHERE mc.email = '".$this->db->escape($this->email)."'"; $sql.= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes - dol_syslog(get_class($this)."::getNbOfEMailings", LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) { $obj = $this->db->fetch_object($resql); @@ -1119,7 +1112,6 @@ class Contact extends CommonObject $url .= $moreparam; - $linkstart = 'global->MAIN_OPTIMIZEFORTEXTBROWSER)) @@ -1129,20 +1121,17 @@ class Contact extends CommonObject } $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose.= ' class="classfortooltip"'; - } - $linkclose.='>'; - if (! is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager=new HookManager($this->db); + /* + $hookmanager->initHooks(array('contactdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ } - $hookmanager->initHooks(array('contactdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - $linkstart.=$linkclose; + $linkstart = ''; $linkend=''; if ($option == 'xxx') @@ -1151,12 +1140,18 @@ class Contact extends CommonObject $linkend=''; } - $result.=$linkstart; if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1); if ($withpicto != 2) $result.=($maxlen?dol_trunc($this->getFullName($langs),$maxlen):$this->getFullName($langs)); $result.=$linkend; + global $action; + $hookmanager->initHooks(array('contactdao')); + $parameters=array('id'=>$this->id, 'getnomurl'=>$result); + $reshook=$hookmanager->executeHooks('getNomUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $result = $hookmanager->resPrint; + else $result .= $hookmanager->resPrint; + return $result; } diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index 281924cb589..1a60ddaaccb 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -30,9 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/contact.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -$langs->load("other"); -$langs->load("companies"); -$langs->load("contact"); +// Load translation files required by the page +$langs->loadLangs(array('other', 'companies', 'contact')); $id = GETPOST('id','int'); $action = GETPOST('action','aZ09'); @@ -153,7 +152,7 @@ if ($object->id) print ''; print ''.$langs->trans("NbOfAttachedFiles").''.count($filearray).''; - print ''.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").''; + print ''.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).''; print ''; print '
'; diff --git a/htdocs/contact/info.php b/htdocs/contact/info.php index 287c27d8b10..7ddee3f7722 100644 --- a/htdocs/contact/info.php +++ b/htdocs/contact/info.php @@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/contact.lib.php'; +// Load translation files required by the page $langs->load("companies"); diff --git a/htdocs/contact/ldap.php b/htdocs/contact/ldap.php index 02a25d8005c..045cdfcd2c5 100644 --- a/htdocs/contact/ldap.php +++ b/htdocs/contact/ldap.php @@ -28,8 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/contact.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/ldap.lib.php'; -$langs->load("companies"); -$langs->load("ldap"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'ldap')); $langs->load("admin"); $action=GETPOST('action','aZ09'); diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index c63467390b4..30b7c5158ba 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -7,6 +7,7 @@ * Copyright (C) 2013 Cédric Salvador * Copyright (C) 2013 Alexandre Spangaro * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2018 Nicolas ZABOURI * Copyright (C) 2018 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -31,8 +32,10 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +// Load translation files required by the page $langs->loadLangs(array("companies", "suppliers")); $action=GETPOST('action','alpha'); @@ -40,6 +43,7 @@ $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'contactlist'; // Security check $id = GETPOST('id','int'); @@ -73,14 +77,15 @@ $search_type=GETPOST('search_type','alpha'); $search_zip=GETPOST('search_zip','alpha'); $search_town=GETPOST('search_town','alpha'); $search_import_key=GETPOST("search_import_key","alpha"); +$search_country=GETPOST("search_country",'intcomma'); if ($search_status=='') $search_status=1; // always display activ customer first $optioncss = GETPOST('optioncss','alpha'); -$type=GETPOST("type"); -$view=GETPOST("view"); +$type=GETPOST("type",'aZ'); +$view=GETPOST("view",'alpha'); $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); @@ -93,35 +98,35 @@ if (! $sortfield) $sortfield="p.lastname"; if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; -$contextpage='contactlist'; $titre = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); if ($type == "p") { - $contextpage='contactprospectlist'; + if (empty($contextpage) || $contextpage == 'contactlist') $contextpage='contactprospectlist'; $titre.=' ('.$langs->trans("ThirdPartyProspects").')'; $urlfiche="card.php"; } if ($type == "c") { - $contextpage='contactcustomerlist'; + if (empty($contextpage) || $contextpage == 'contactlist') $contextpage='contactcustomerlist'; $titre.=' ('.$langs->trans("ThirdPartyCustomers").')'; $urlfiche="card.php"; } else if ($type == "f") { - $contextpage='contactsupplierlist'; + if (empty($contextpage) || $contextpage == 'contactlist') $contextpage='contactsupplierlist'; $titre.=' ('.$langs->trans("ThirdPartySuppliers").')'; $urlfiche="card.php"; } else if ($type == "o") { - $contextpage='contactotherlist'; + if (empty($contextpage) || $contextpage == 'contactlist') $contextpage='contactotherlist'; $titre.=' ('.$langs->trans("OthersNotLinkedToThirdParty").')'; $urlfiche=""; } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array($contextpage)); +$object = new Contact($db); +$hookmanager->initHooks(array('contactlist')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -134,6 +139,7 @@ $fieldstosearchall = array( 'p.firstname'=>'Firstname', 'p.email'=>'EMail', 's.nom'=>"ThirdParty", + 'p.phone'=>"Phone", ); // Definition of fields for list @@ -144,6 +150,7 @@ $arrayfields=array( 'p.poste'=>array('label'=>"PostOrFunction", 'checked'=>1), 'p.town'=>array('label'=>"Town", 'checked'=>0), 'p.zip'=>array('label'=>"Zip", 'checked'=>0), + 'country.code_iso'=>array('label'=>"Country", 'checked'=>0), 'p.phone'=>array('label'=>"Phone", 'checked'=>1), 'p.phone_perso'=>array('label'=>"PhonePerso", 'checked'=>0), 'p.phone_mobile'=>array('label'=>"PhoneMobile", 'checked'=>1), @@ -199,6 +206,9 @@ if (empty($reshook)) $search_lastname=""; $search_firstname=""; $search_societe=""; + $search_town=""; + $search_zip=""; + $search_country=""; $search_poste=""; $search_phone=""; $search_phone_perso=""; @@ -257,7 +267,7 @@ if (! empty($search_categ)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_conta if (! empty($search_categ_thirdparty)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc"; // We need this table joined to the select in order to filter by categ if (! empty($search_categ_supplier)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs2 ON s.rowid = cs2.fk_soc"; // We need this table joined to the select in order to filter by categ if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; -$sql.= ' WHERE p.entity IN ('.getEntity('societe').')'; +$sql.= ' WHERE p.entity IN ('.getEntity('socpeople').')'; if (!$user->rights->societe->client->voir && !$socid) //restriction { $sql .= " AND (sc.fk_user = " .$user->id." OR p.fk_soc IS NULL)"; @@ -294,6 +304,7 @@ if ($search_id > 0) $sql.= natural_search("p.rowid",$search_id,1 if ($search_lastname) $sql.= natural_search('p.lastname', $search_lastname); if ($search_firstname) $sql.= natural_search('p.firstname', $search_firstname); if ($search_societe) $sql.= natural_search('s.nom', $search_societe); +if ($search_country) $sql .= " AND p.fk_pays IN (".$search_country.')'; if (strlen($search_poste)) $sql.= natural_search('p.poste', $search_poste); if (strlen($search_phone_perso)) $sql.= natural_search('p.phone_perso', $search_phone_perso); if (strlen($search_phone_pro)) $sql.= natural_search('p.phone', $search_phone); @@ -346,6 +357,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit+1, $offset); @@ -387,6 +403,7 @@ if ($search_firstname != '') $param.='&search_firstname='.urlencode($search_ 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_country != '') $param.= "&search_country=".urlencode($search_country); 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); @@ -411,6 +428,14 @@ if ($user->rights->societe->supprimer) $arrayofmassactions['predelete']=$langs-> if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); $massactionbutton=$form->selectMassAction('', $arrayofmassactions); +$newcardbutton=''; +if ($user->rights->societe->contact->creer) +{ + $newcardbutton=''.$langs->trans('NewContactAddress').''; + $newcardbutton.= ''; + $newcardbutton.= ''; +} + print ''; if ($optioncss != '') print ''; print ''; @@ -421,7 +446,7 @@ print ''; print ''; print ''; -print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit); +print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies.png', 0, $newcardbutton, '', $limit); $topicmail="Information"; $modelmail="contact"; @@ -432,11 +457,11 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + print '
'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'
'; } if ($search_firstlast_only) { - print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); + print '
'.$langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname").'
'; } $moreforfilter=''; @@ -501,6 +526,12 @@ if (! empty($arrayfields['p.firstname']['checked'])) print ''; print ''; } +if (! empty($arrayfields['p.poste']['checked'])) +{ + print ''; + print ''; + print ''; +} if (! empty($arrayfields['p.zip']['checked'])) { print ''; @@ -513,10 +544,25 @@ if (! empty($arrayfields['p.town']['checked'])) print ''; print ''; } -if (! empty($arrayfields['p.poste']['checked'])) +// State +/*if (! empty($arrayfields['state.nom']['checked'])) + { + print ''; + print ''; + print ''; + } + // Region + if (! empty($arrayfields['region.nom']['checked'])) + { + print ''; + print ''; + print ''; + }*/ +// Country +if (! empty($arrayfields['country.code_iso']['checked'])) { - print ''; - print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); print ''; } if (! empty($arrayfields['p.phone']['checked'])) @@ -613,9 +659,12 @@ print ''; if (! empty($arrayfields['p.rowid']['checked'])) print_liste_field_titre($arrayfields['p.rowid']['label'], $_SERVER["PHP_SELF"],"p.rowid","",$param,"",$sortfield,$sortorder); if (! empty($arrayfields['p.lastname']['checked'])) print_liste_field_titre($arrayfields['p.lastname']['label'],$_SERVER["PHP_SELF"],"p.lastname", $begin, $param, '', $sortfield,$sortorder); if (! empty($arrayfields['p.firstname']['checked'])) print_liste_field_titre($arrayfields['p.firstname']['label'],$_SERVER["PHP_SELF"],"p.firstname", $begin, $param, '', $sortfield,$sortorder); +if (! empty($arrayfields['p.poste']['checked'])) print_liste_field_titre($arrayfields['p.poste']['label'],$_SERVER["PHP_SELF"],"p.poste", $begin, $param, '', $sortfield,$sortorder); if (! empty($arrayfields['p.zip']['checked'])) print_liste_field_titre($arrayfields['p.zip']['label'],$_SERVER["PHP_SELF"],"p.zip", $begin, $param, '', $sortfield,$sortorder); if (! empty($arrayfields['p.town']['checked'])) print_liste_field_titre($arrayfields['p.town']['label'],$_SERVER["PHP_SELF"],"p.town", $begin, $param, '', $sortfield,$sortorder); -if (! empty($arrayfields['p.poste']['checked'])) print_liste_field_titre($arrayfields['p.poste']['label'],$_SERVER["PHP_SELF"],"p.poste", $begin, $param, '', $sortfield,$sortorder); +//if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); +//if (! empty($arrayfields['region.nom']['checked'])) print_liste_field_titre($arrayfields['region.nom']['label'],$_SERVER["PHP_SELF"],"region.nom","",$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"co.code_iso","",$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['p.phone']['checked'])) print_liste_field_titre($arrayfields['p.phone']['label'],$_SERVER["PHP_SELF"],"p.phone", $begin, $param, '', $sortfield,$sortorder); if (! empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre($arrayfields['p.phone_perso']['label'],$_SERVER["PHP_SELF"],"p.phone_perso", $begin, $param, '', $sortfield,$sortorder); if (! empty($arrayfields['p.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['p.phone_mobile']['label'],$_SERVER["PHP_SELF"],"p.phone_mobile", $begin, $param, '', $sortfield,$sortorder); @@ -680,6 +729,12 @@ while ($i < min($num,$limit)) print ''.$obj->firstname.''; if (! $i) $totalarray['nbfield']++; } + // Job position + if (! empty($arrayfields['p.poste']['checked'])) + { + print ''.dol_trunc($obj->poste,20).''; + if (! $i) $totalarray['nbfield']++; + } // Zip if (! empty($arrayfields['p.zip']['checked'])) { @@ -692,10 +747,25 @@ while ($i < min($num,$limit)) print ''.$obj->town.''; if (! $i) $totalarray['nbfield']++; } - // Function - if (! empty($arrayfields['p.poste']['checked'])) + // State + /*if (! empty($arrayfields['state.nom']['checked'])) { - print ''.dol_trunc($obj->poste,20).''; + print "".$obj->state_name."\n"; + if (! $i) $totalarray['nbfield']++; + } + // Region + if (! empty($arrayfields['region.nom']['checked'])) + { + print "".$obj->region_name."\n"; + if (! $i) $totalarray['nbfield']++; + }*/ + // Country + if (! empty($arrayfields['country.code_iso']['checked'])) + { + print ''; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; + print ''; if (! $i) $totalarray['nbfield']++; } // Phone diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index 1fa766e0913..731dadb6433 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; $action = GETPOST('action','aZ09'); +// Load translation files required by the page $langs->load("companies"); // Security check diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index 9e85ef98294..3e5ec085132 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -27,8 +27,8 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/contact.lib.php'; -$langs->load("companies"); -$langs->load("other"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'other')); $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); diff --git a/htdocs/contrat/admin/contract_extrafields.php b/htdocs/contrat/admin/contract_extrafields.php index 3fb55acc2ca..b9b0d51c162 100644 --- a/htdocs/contrat/admin/contract_extrafields.php +++ b/htdocs/contrat/admin/contract_extrafields.php @@ -4,7 +4,7 @@ * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2012 Regis Houssin * Copyright (C) 2013 Florian Henry - * Copyright (C) 2013 Philippe Grand + * Copyright (C) 2013-2018 Philippe Grand * * 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 @@ -31,9 +31,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("admin"); -$langs->load("contracts"); +// Load translation files required by the page +$langs->loadLangs(array("companies","admin","contracts")); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/contrat/admin/contractdet_extrafields.php b/htdocs/contrat/admin/contractdet_extrafields.php index e3047466e1b..42a8ed589d7 100644 --- a/htdocs/contrat/admin/contractdet_extrafields.php +++ b/htdocs/contrat/admin/contractdet_extrafields.php @@ -31,9 +31,8 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$langs->load("companies"); -$langs->load("admin"); -$langs->load("contracts"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'admin', 'contracts')); $extrafields = new ExtraFields($db); $form = new Form($db); diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 91738ac81be..d0120d130df 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -46,12 +46,8 @@ if (! empty($conf->projet->enabled)) { } require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; -$langs->load("contracts"); -$langs->load("orders"); -$langs->load("companies"); -$langs->load("bills"); -$langs->load("products"); -$langs->load('compta'); +// Load translation files required by the page +$langs->loadLangs(array("contracts","orders","companies","bills","products",'compta')); $action=GETPOST('action','alpha'); $confirm=GETPOST('confirm','alpha'); @@ -94,6 +90,7 @@ $permissionnote=$user->rights->contrat->creer; // Used by the include of actions $permissiondellink=$user->rights->contrat->creer; // Used by the include of actions_dellink.inc.php + /* * Actions */ @@ -657,43 +654,53 @@ if (empty($reshook)) else if ($action == 'updateline' && $user->rights->contrat->creer && ! GETPOST('cancel','alpha')) { - if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) - { - setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); - $action = 'editline'; - $_GET['rowid'] = GETPOST('elrowid'); - $error++; - } + $error = 0; - if (!$error) { - $objectline = new ContratLigne($db); - if ($objectline->fetch(GETPOST('elrowid'))) - { - $db->begin(); + if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) + { + setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); + $action = 'editline'; + $_GET['rowid'] = GETPOST('elrowid'); + $error++; + } - if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; - if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; + if (! $error) + { + $objectline = new ContratLigne($db); + if ($objectline->fetch(GETPOST('elrowid')) < 0) + { + setEventMessages($objectline->error, $objectline->errors, 'errors'); + $error++; + } + } - $vat_rate = GETPOST('eltva_tx'); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) + $db->begin(); + + if (! $error) + { + if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture; + if ($date_end_real_update == '') $date_end_real_update=$objectline->date_cloture; + + $vat_rate = GETPOST('eltva_tx'); + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $vat_rate)) $info_bits |= 0x01; // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); - $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); + $localtax1_tx=get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); + $localtax2_tx=get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); - $txtva = $vat_rate; + $txtva = $vat_rate; // Clean vat code - $vat_src_code=''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + $vat_src_code=''; + if (preg_match('/\((.*)\)/', $txtva, $reg)) + { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. - } + } // ajout prix d'achat $fk_fournprice = $_POST['fournprice']; @@ -704,22 +711,22 @@ if (empty($reshook)) $fk_unit = GETPOST('unit', 'alpha'); - $objectline->description=GETPOST('product_desc','none'); - $objectline->price_ht=GETPOST('elprice'); - $objectline->subprice=GETPOST('elprice'); - $objectline->qty=GETPOST('elqty'); - $objectline->remise_percent=GETPOST('elremise_percent'); - $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 - $objectline->vat_src_code=$vat_src_code; - $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; - $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; - $objectline->date_ouverture_prevue=$date_start_update; - $objectline->date_ouverture=$date_start_real_update; - $objectline->date_fin_validite=$date_end_update; - $objectline->date_cloture=$date_end_real_update; - $objectline->fk_user_cloture=$user->id; - $objectline->fk_fournprice=$fk_fournprice; - $objectline->pa_ht=$pa_ht; + $objectline->description=GETPOST('product_desc','none'); + $objectline->price_ht=GETPOST('elprice'); + $objectline->subprice=GETPOST('elprice'); + $objectline->qty=GETPOST('elqty'); + $objectline->remise_percent=GETPOST('elremise_percent'); + $objectline->tva_tx=($txtva?$txtva:0); // Field may be disabled, so we use vat rate 0 + $objectline->vat_src_code=$vat_src_code; + $objectline->localtax1_tx=is_numeric($localtax1_tx)?$localtax1_tx:0; + $objectline->localtax2_tx=is_numeric($localtax2_tx)?$localtax2_tx:0; + $objectline->date_ouverture_prevue=$date_start_update; + $objectline->date_ouverture=$date_start_real_update; + $objectline->date_fin_validite=$date_end_update; + $objectline->date_cloture=$date_end_real_update; + $objectline->fk_user_cloture=$user->id; + $objectline->fk_fournprice=$fk_fournprice; + $objectline->pa_ht=$pa_ht; if ($fk_unit > 0) { $objectline->fk_unit = GETPOST('unit'); @@ -727,30 +734,30 @@ if (empty($reshook)) $objectline->fk_unit = null; } - // Extrafields - $extrafieldsline = new ExtraFields($db); - $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); - $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); - $objectline->array_options=$array_options; + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element); + $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + $objectline->array_options=$array_options; - // TODO verifier price_min si fk_product et multiprix + // TODO verifier price_min si fk_product et multiprix - $result=$objectline->update($user); - if ($result > 0) - { - $db->commit(); - } - else - { + $result=$objectline->update($user); + if ($result < 0) + { + $error++; setEventMessages($objectline->error, $objectline->errors, 'errors'); - $db->rollback(); - } - } - else - { - setEventMessages($objectline->error, $objectline->errors, 'errors'); - } - } + } + } + + if (! $error) + { + $db->commit(); + } + else + { + $db->rollback(); + } } else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) @@ -800,18 +807,30 @@ if (empty($reshook)) else if ($action == 'reopen' && $user->rights->contrat->creer) { $result = $object->reopen($user); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Close all lines else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->closeAll($user); + $result = $object->closeAll($user); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Close all lines else if ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->activateAll($user); + $result = $object->activateAll($user); + if ($result < 0) + { + setEventMessages($object->error, $object->errors, 'errors'); + } } else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) @@ -853,13 +872,15 @@ if (empty($reshook)) } else if ($action == 'update_extras') { + $object->oldcopy = dol_clone($object); + // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute','none')); if ($ret < 0) $error++; if (! $error) { - $result = $object->insertExtraFields(); + $result = $object->insertExtraFields('CONTRACT_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -876,10 +897,7 @@ if (empty($reshook)) $cancelbutton = GETPOST('cancel','alpha'); if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->oldcopy = dol_clone($object); $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); if ($result < 0) { @@ -901,10 +919,7 @@ if (empty($reshook)) if (!$cancelbutton) { - $result = $object->fetch($id); - if ($result < 0) { - setEventMessages($object->error, $object->errors, 'errors'); - } + $object->oldcopy = dol_clone($object); $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer','alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); if ($result < 0) { @@ -1262,7 +1277,7 @@ if ($action == 'create') print $hookmanager->resPrint; // Other attributes - if (empty($reshook) && ! empty($extrafields->attribute_label)) { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1517,8 +1532,10 @@ else // Title line for service $cursorline=1; + print '
'; while ($cursorline <= $nbofservices) { + print '
'; print ''; print ''; print ''; @@ -1527,6 +1544,7 @@ else print ''; // Area with common detail of line + print '
'; print ''; $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,"; @@ -1565,7 +1583,7 @@ else if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) { - print ''; + print ''; // Label if ($objp->fk_product > 0) { @@ -1629,13 +1647,14 @@ else print ''; + print ''; print ''; } - // Display lines extrafields if (is_array($extralabelslines) && count($extralabelslines)>0) { $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bcnd[$var], 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1); + $line->fetch_optionals($objp->rowid); + print $line->showOptionals($extrafieldsline, 'view', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1); } } // Ligne en mode update else { // Ligne carac - print ""; + print ''; print ''; + print ''; $colspan=6; if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; if($conf->global->PRODUCT_USE_UNITS) $colspan++; // Ligne dates prevues - print ""; + print ''; print ''; } $db->free($result); @@ -1786,12 +1803,13 @@ else if ($object->statut > 0) { - print ''; + print ''; print ''; print "\n"; } print "
'; if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) { - print ''; + print ''; + print ''; print img_picto($langs->trans("MoveToAnotherContract"),'uparrow'); print ''; } if ($user->rights->contrat->creer && ($object->statut >= 0)) { - print ''; + print ''; print img_edit(); print ''; } @@ -1660,7 +1679,7 @@ else $colspan = 7; } - print '
'; // Date planned @@ -1693,19 +1712,18 @@ else print '
'; if ($objp->fk_product) { @@ -1753,13 +1771,14 @@ else print ''; print '
'; print '
'; print $langs->trans("DateStartPlanned").' '; $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update"); @@ -1770,11 +1789,9 @@ else if (is_array($extralabelslines) && count($extralabelslines)>0) { $line = new ContratLigne($db); - $line->fetch_optionals($objp->rowid,$extralabelslines); - print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1); + $line->fetch_optionals($objp->rowid); + print $line->showOptionals($extrafieldsline, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD)?0:1); } - - print '

"; + print '
'; print "\n"; @@ -1861,9 +1879,9 @@ else // Area with status and activation info of line if ($object->statut > 0) { - print ''; + print '
'; - print ''; + print ''; print ''; print ''; print "\n"; - print ''; + print ''; print ''; print ''; @@ -1946,7 +1964,7 @@ else } } - print ''; + print ''; print ''; @@ -1958,7 +1976,7 @@ else print ''; - print ''; + print ''; print ''; print ''; - print ''; + print ''; print ''; print '
'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).''; if ($user->societe_id == 0) @@ -1890,7 +1908,7 @@ else print '
'; // Si pas encore active @@ -1912,7 +1930,7 @@ else print $langs->trans("DateEndReal").': '; print dol_print_date($objp->date_fin_reelle, 'day'); } - if (! empty($objp->comment)) print "
".$objp->comment; + if (! empty($objp->comment)) print "  -  ".$objp->comment; print '
 
'.$langs->trans("DateServiceActivate").''; print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active",1,0,1); print '
'.$langs->trans("Comment").''; print '   '; @@ -2003,7 +2021,7 @@ else $now=dol_now(); if ($dateactend > $now) $dateactend=$now; - print '
'; + print '
'; if ($objp->statut >= 4) { if ($objp->statut == 4) @@ -2016,7 +2034,7 @@ else print ''; print '
'.$langs->trans("Comment").''; print '   '; @@ -2028,9 +2046,10 @@ else print ''; } - + print ''; $cursorline++; } + print ''; // Form to add new line if ($user->rights->contrat->creer && ($object->statut == 0)) @@ -2055,8 +2074,6 @@ else // Form to add new line if ($action != 'editline') { - $var = true; - $forcetoshowtitlelines=1; // Add free products/services @@ -2093,9 +2110,9 @@ else // Send if ($object->statut == 1) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send)) { - print ''; + print ''; } else - print ''; + print ''; } if ($object->statut == 0 && $nbofservices) @@ -2109,7 +2126,7 @@ else else print ''; } - if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) + if (! empty($conf->facture->enabled) && $object->statut > 0) { $langs->load("bills"); if ($user->rights->facture->creer) print ''; @@ -2130,13 +2147,28 @@ else if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) { - print ''; + if ($user->rights->contrat->activer) + { + print ''; + } + else + { + print ''; + } } if ($object->nbofservicesclosed < $nbofservices) { + if ($user->rights->contrat->desactiver) + { + print ''; + } + else + { + print ''; + } + //if (! $numactive) //{ - print ''; //} //else //{ @@ -2178,7 +2210,6 @@ else $genallowed = $user->rights->contrat->lire; $delallowed = $user->rights->contrat->creer; - $var = true; print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php index 689b0465fd4..1bb17eb4352 100644 --- a/htdocs/contrat/class/api_contracts.class.php +++ b/htdocs/contrat/class/api_contracts.class.php @@ -182,7 +182,7 @@ class Contracts extends DolibarrApi * @param array $request_data Request data * @return int ID of contrat */ - function post($request_data = NULL) + function post($request_data = null) { if(! DolibarrApiAccess::$user->rights->contrat->creer) { throw new RestException(401, "Insuffisant rights"); @@ -247,7 +247,7 @@ class Contracts extends DolibarrApi * * @return int */ - function postLine($id, $request_data = NULL) { + function postLine($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->contrat->creer) { throw new RestException(401); } @@ -300,7 +300,7 @@ class Contracts extends DolibarrApi * * @return object */ - function putLine($id, $lineid, $request_data = NULL) { + function putLine($id, $lineid, $request_data = null) { if(! DolibarrApiAccess::$user->rights->contrat->creer) { throw new RestException(401); } @@ -359,7 +359,7 @@ class Contracts extends DolibarrApi * * @return object */ - function activateLine($id, $lineid, $datestart, $dateend = NULL, $comment = NULL) { + function activateLine($id, $lineid, $datestart, $dateend = null, $comment = null) { if(! DolibarrApiAccess::$user->rights->contrat->creer) { throw new RestException(401); } @@ -396,7 +396,7 @@ class Contracts extends DolibarrApi * * @return object */ - function unactivateLine($id, $lineid, $datestart, $comment = NULL) { + function unactivateLine($id, $lineid, $datestart, $comment = null) { if(! DolibarrApiAccess::$user->rights->contrat->creer) { throw new RestException(401); } @@ -470,7 +470,7 @@ class Contracts extends DolibarrApi * * @return int */ - function put($id, $request_data = NULL) { + function put($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->contrat->creer) { throw new RestException(401); } diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index a460f6aff51..291569270b3 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -9,6 +9,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2014-2015 Marcos García * Copyright (C) 2015-2017 Ferran Marcet + * Copyright (C) 2018 Nicolas ZABOURI * * 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 @@ -276,6 +277,7 @@ class Contrat extends CommonObject * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers * @param string $comment Comment * @return int <0 if KO, >0 if OK + * @see closeAll */ function activateAll($user, $date_start='', $notrigger=0, $comment='') { @@ -286,37 +288,39 @@ class Contrat extends CommonObject // Load lines $this->fetch_lines(); - $ok=true; + $error=0; + foreach($this->lines as $contratline) { // Open lines not already open - if ($contratline->statut != 4) + if ($contratline->statut != ContratLigne::STATUS_OPEN) { $contratline->context = $this->context; $result = $contratline->active_line($user, $date_start, -1, $comment); if ($result < 0) { - $ok=false; + $error++; + $this->error = $contratline->error; + $this->errors = $contratline->errors; break; } } } - if ($this->statut == 0) + if (! $error && $this->statut == 0) { - $result=$this->validate($user); - if ($result < 0) $ok=false; + $result=$this->validate($user, '', $notrigger); + if ($result < 0) $error++; } - if ($ok) + if (! $error) { $this->db->commit(); return 1; } else { - dol_print_error($this->db,'Error in activateAll function'); $this->db->rollback(); return -1; } @@ -326,10 +330,12 @@ class Contrat extends CommonObject * Close all lines of a contract * * @param User $user Object User making action - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @param string $comment Comment * @return int <0 if KO, >0 if OK + * @see activateAll */ - function closeAll(User $user, $notrigger=0) + function closeAll(User $user, $notrigger=0, $comment='') { $this->db->begin(); @@ -338,38 +344,40 @@ class Contrat extends CommonObject $now = dol_now(); - $ok=true; + $error = 0; + foreach($this->lines as $contratline) { // Close lines not already closed - if ($contratline->statut != 5) + if ($contratline->statut != ContratLigne::STATUS_CLOSED) { $contratline->date_cloture=$now; $contratline->fk_user_cloture=$user->id; - $contratline->statut='5'; - $result=$contratline->update($user); + $contratline->statut=ContratLigne::STATUS_CLOSED; + $result=$contratline->close_line($user, $now, $comment, $notrigger); if ($result < 0) { - $ok=false; + $error++; + $this->error = $contratline->error; + $this->errors = $contratline->errors; break; } } } - if ($this->statut == 0) + if (! $error && $this->statut == 0) { $result=$this->validate($user, '', $notrigger); - if ($result < 0) $ok=false; + if ($result < 0) $error++; } - if ($ok) + if (! $error) { $this->db->commit(); return 1; } else { - dol_print_error($this->db,'Error in closeAll function'); $this->db->rollback(); return -1; } @@ -399,7 +407,10 @@ class Contrat extends CommonObject $this->fetch_thirdparty(); // A contract is validated so we can move thirdparty to status customer - $result=$this->thirdparty->set_as_client(); + if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) + { + $result=$this->thirdparty->set_as_client(); + } // Define new ref if ($force_number) @@ -619,7 +630,7 @@ class Contrat extends CommonObject $this->mise_en_service = $this->db->jdate($result["datemise"]); $this->date_contrat = $this->db->jdate($result["datecontrat"]); - $this->date_creation = $this->db->jdate($result["datecontrat"]); + $this->date_creation = $this->db->jdate($result["datecontrat"]); $this->fin_validite = $this->db->jdate($result["fin_validite"]); $this->date_cloture = $this->db->jdate($result["date_cloture"]); @@ -644,16 +655,15 @@ class Contrat extends CommonObject $this->db->free($resql); - // Retreive all extrafield for thirdparty + + // Retreive all extrafield // fetch optionals attributes and labels - require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); + $this->fetch_optionals(); + /* * Lines - */ + */ $this->lines = array(); @@ -668,14 +678,14 @@ class Contrat extends CommonObject } else { - dol_syslog(get_class($this)."::Fetch Erreur contrat non trouve"); + dol_syslog(get_class($this)."::fetch Contract not found"); $this->error="Contract not found"; return 0; } } else { - dol_syslog(get_class($this)."::Fetch Erreur lecture contrat"); + dol_syslog(get_class($this)."::fetch Error searching contract"); $this->error=$this->db->error(); return -1; } @@ -683,7 +693,8 @@ class Contrat extends CommonObject } /** - * Load lines array into this->lines + * Load lines array into this->lines. + * This set also nbofserviceswait, nbofservicesopened, nbofservicesexpired and nbofservicesclosed * * @return ContratLigne[] Return array of contract lines */ @@ -772,17 +783,7 @@ class Contrat extends CommonObject $line->fk_user_cloture = $objp->fk_user_cloture; $line->fk_unit = $objp->fk_unit; - $line->ref = $objp->product_ref; // deprecated - if (empty($objp->fk_product)) - { - $line->label = ''; // deprecated - $line->libelle = $objp->description; // deprecated - } - else - { - $line->label = $objp->product_label; // deprecated - $line->libelle = $objp->product_label; // deprecated - } + $line->ref = $objp->product_ref; // deprecated $line->product_ref = $objp->product_ref; // Ref product $line->product_desc = $objp->product_desc; // Description product $line->product_label = $objp->product_label; // Label product @@ -805,7 +806,7 @@ class Contrat extends CommonObject // Retreive all extrafield for contract // fetch optionals attributes and labels - $line->fetch_optionals($line->id,$extralabelsline); + $line->fetch_optionals(); $this->lines[$pos] = $line; $this->lines_id_index_mapper[$line->id] = $pos; @@ -813,10 +814,10 @@ class Contrat extends CommonObject //dol_syslog("1 ".$line->desc); //dol_syslog("2 ".$line->product_desc); - if ($line->statut == 0) $this->nbofserviceswait++; - if ($line->statut == 4 && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++; - if ($line->statut == 4 && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++; - if ($line->statut == 5) $this->nbofservicesclosed++; + if ($line->statut == ContratLigne::STATUS_INITIAL) $this->nbofserviceswait++; + if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++; + if ($line->statut == ContratLigne::STATUS_OPEN && (! empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++; + if ($line->statut == ContratLigne::STATUS_CLOSED) $this->nbofservicesclosed++; $total_ttc+=$objp->total_ttc; // TODO Not saved into database $total_vat+=$objp->total_tva; @@ -907,30 +908,30 @@ class Contrat extends CommonObject if ($result > 0) { $modCodeContract = new $module(); - } - if (!empty($modCodeContract->code_auto)) { - // Mise a jour ref - $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; - if ($this->db->query($sql)) - { - if ($this->id) + if (!empty($modCodeContract->code_auto)) { + // Mise a jour ref + $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; + if ($this->db->query($sql)) { - $this->ref="(PROV".$this->id.")"; + if ($this->id) + { + $this->ref="(PROV".$this->id.")"; + } } + } else { + $error++; + $this->error='Failed to get PROV number'; } } - if (! $error) + if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } } // Insert contacts commerciaux ('SALESREPSIGN','contrat') @@ -1044,7 +1045,7 @@ class Contrat extends CommonObject } else { - $this->error="Failed to add contact"; + $this->error="Failed to add contract"; dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR); $this->db->rollback(); return -2; @@ -1279,44 +1280,41 @@ class Contrat extends CommonObject $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } - if (! $error) + if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) { - if (! $notrigger) + $result=$this->insertExtraFields(); + if ($result < 0) { - // Call triggers - $result=$this->call_trigger('CONTRACT_MODIFY',$user); - if ($result < 0) { $error++; } - // End call triggers - } - } - - if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } - - // Commit or rollback - if ($error) - { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } - $this->db->rollback(); - return -1*$error; - } - else - { - $this->db->commit(); - return 1; + $error++; } } + if (! $error && ! $notrigger) + { + // Call triggers + $result=$this->call_trigger('CONTRACT_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } + /** * Ajoute une ligne de contrat en base @@ -1344,13 +1342,14 @@ class Contrat extends CommonObject function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type='HT', $pu_ttc=0.0, $info_bits=0, $fk_fournprice=null, $pa_ht = 0,$array_options=0, $fk_unit = null, $rang=0) { global $user, $langs, $conf, $mysoc; + $error=0; dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); // Check parameters if ($fk_product <= 0 && empty($desc)) { - $this->error="DescRequiredForFreeProductLines"; + $this->error="ErrorDescRequiredForFreeProductLines"; return -1; } @@ -1552,6 +1551,8 @@ class Contrat extends CommonObject { global $user, $conf, $langs, $mysoc; + $error=0; + // Clean parameters $qty=trim($qty); $desc=trim($desc); @@ -1843,7 +1844,6 @@ class Contrat extends CommonObject } if ($mode == 4 || $mode == 6 || $mode == 7) { - $line=new ContratLigne($this->db); $text=''; if ($mode == 4) { @@ -1854,13 +1854,13 @@ class Contrat extends CommonObject $text.=''; } $text.=($mode == 7?'
':''); - $text.=($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.$line->LibStatut(0,3,-1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed)?'   ':'') : ''; + $text.=($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0,3,-1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed)?'   ':'') : ''; $text.=($mode == 7?'
':''); - $text.=($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.$line->LibStatut(4,3,0,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed)?'   ':'') : ''; + $text.=($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4,3,0,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed)?'   ':'') : ''; $text.=($mode == 7?'
':''); - $text.=($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.$line->LibStatut(4,3,1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesclosed)?'   ':'') : ''; + $text.=($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4,3,1,'class="paddingleft2 inline-block valigntextbottom"')).(($mode != 7 || $this->nbofservicesclosed)?'   ':'') : ''; $text.=($mode == 7?'
':''); - $text.=($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.$line->LibStatut(5,3,-1,'class="paddingleft2 inline-block valigntextbottom"')) : ''; + $text.=($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5,3,-1,'class="paddingleft2 inline-block valigntextbottom"')) : ''; $text.=($mode == 7?'
':''); return $text; } @@ -2301,9 +2301,10 @@ class Contrat extends CommonObject * @param int $hidedetails Hide details of lines * @param int $hidedesc Hide description * @param int $hideref Hide ref + * @param null|array $moreparams Array to provide more information * @return int 0 if KO, 1 if OK */ - public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null) { global $conf,$langs; @@ -2322,7 +2323,7 @@ class Contrat extends CommonObject $modelpath = "core/modules/contract/doc/"; - return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); } /** @@ -2430,17 +2431,6 @@ class Contrat extends CommonObject } - 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 @@ -2470,12 +2460,15 @@ class ContratLigne extends CommonObjectLine var $fk_contrat; var $fk_product; var $statut; // 0 inactive, 4 active, 5 closed - var $type; // 0 for product, 1 for service + var $type; // 0 for product, 1 for service + /** + * @var string + * @deprecated + */ var $label; /** * @var string - * @deprecated Use $label instead - * @see label + * @deprecated */ public $libelle; @@ -2531,6 +2524,11 @@ class ContratLigne extends CommonObjectLine var $fk_user_cloture; var $commentaire; + const STATUS_INITIAL = 0; + const STATUS_OPEN = 4; + const STATUS_CLOSED = 5; + + /** * Constructor @@ -2563,57 +2561,57 @@ class ContratLigne extends CommonObjectLine * @param string $moreatt More attribute * @return string Libelle */ - function LibStatut($statut,$mode,$expired=-1,$moreatt='') + static function LibStatut($statut,$mode,$expired=-1,$moreatt='') { global $langs; $langs->load("contracts"); if ($mode == 0) { - if ($statut == 0) { return $langs->trans("ServiceStatusInitial"); } - if ($statut == 4 && $expired == -1) { return $langs->trans("ServiceStatusRunning"); } - if ($statut == 4 && $expired == 0) { return $langs->trans("ServiceStatusNotLate"); } - if ($statut == 4 && $expired == 1) { return $langs->trans("ServiceStatusLate"); } - if ($statut == 5) { return $langs->trans("ServiceStatusClosed"); } + if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); } + if ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); } + if ($statut == self::STATUS_OPEN && $expired == 0) { return $langs->trans("ServiceStatusNotLate"); } + if ($statut == self::STATUS_OPEN && $expired == 1) { return $langs->trans("ServiceStatusLate"); } + if ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed"); } } if ($mode == 1) { - if ($statut == 0) { return $langs->trans("ServiceStatusInitial"); } - if ($statut == 4 && $expired == -1) { return $langs->trans("ServiceStatusRunning"); } - if ($statut == 4 && $expired == 0) { return $langs->trans("ServiceStatusNotLateShort"); } - if ($statut == 4 && $expired == 1) { return $langs->trans("ServiceStatusLateShort"); } - if ($statut == 5) { return $langs->trans("ServiceStatusClosed"); } + if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial"); } + if ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning"); } + if ($statut == self::STATUS_OPEN && $expired == 0) { return $langs->trans("ServiceStatusNotLateShort"); } + if ($statut == self::STATUS_OPEN && $expired == 1) { return $langs->trans("ServiceStatusLateShort"); } + if ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed"); } } if ($mode == 2) { - if ($statut == 0) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); } - if ($statut == 4 && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); } - if ($statut == 4 && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); } - if ($statut == 4 && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLateShort"); } - if ($statut == 5) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); } + if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); } + if ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); } + if ($statut == self::STATUS_OPEN && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLateShort"); } + if ($statut == self::STATUS_OPEN && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLateShort"); } + if ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); } } if ($mode == 3) { - if ($statut == 0) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0',$moreatt); } - if ($statut == 4 && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4',$moreatt); } - if ($statut == 4 && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4',$moreatt); } - if ($statut == 4 && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'),'statut3',$moreatt); } - if ($statut == 5) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6',$moreatt); } + if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0',$moreatt); } + if ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4',$moreatt); } + if ($statut == self::STATUS_OPEN && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4',$moreatt); } + if ($statut == self::STATUS_OPEN && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'),'statut3',$moreatt); } + if ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6',$moreatt); } } if ($mode == 4) { - if ($statut == 0) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); } - if ($statut == 4 && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); } - if ($statut == 4 && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLate"); } - if ($statut == 4 && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLate"); } - if ($statut == 5) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); } + if ($statut == self::STATUS_INITIAL) { return img_picto($langs->trans('ServiceStatusInitial'),'statut0').' '.$langs->trans("ServiceStatusInitial"); } + if ($statut == self::STATUS_OPEN && $expired == -1) { return img_picto($langs->trans('ServiceStatusRunning'),'statut4').' '.$langs->trans("ServiceStatusRunning"); } + if ($statut == self::STATUS_OPEN && $expired == 0) { return img_picto($langs->trans('ServiceStatusNotLate'),'statut4').' '.$langs->trans("ServiceStatusNotLate"); } + if ($statut == self::STATUS_OPEN && $expired == 1) { return img_picto($langs->trans('ServiceStatusLate'),'statut3').' '.$langs->trans("ServiceStatusLate"); } + if ($statut == self::STATUS_CLOSED) { return img_picto($langs->trans('ServiceStatusClosed'),'statut6') .' '.$langs->trans("ServiceStatusClosed"); } } if ($mode == 5) { - if ($statut == 0) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'),'statut0'); } - if ($statut == 4 && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'),'statut4'); } - if ($statut == 4 && $expired == 0) { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'),'statut4'); } - if ($statut == 4 && $expired == 1) { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'),'statut3'); } - if ($statut == 5) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'),'statut6'); } + if ($statut == self::STATUS_INITIAL) { return $langs->trans("ServiceStatusInitial").' '.img_picto($langs->trans('ServiceStatusInitial'),'statut0'); } + if ($statut == self::STATUS_OPEN && $expired == -1) { return $langs->trans("ServiceStatusRunning").' '.img_picto($langs->trans('ServiceStatusRunning'),'statut4'); } + if ($statut == self::STATUS_OPEN && $expired == 0) { return $langs->trans("ServiceStatusNotLateShort").' '.img_picto($langs->trans('ServiceStatusNotLateShort'),'statut4'); } + if ($statut == self::STATUS_OPEN && $expired == 1) { return $langs->trans("ServiceStatusLateShort").' '.img_picto($langs->trans('ServiceStatusLate'),'statut3'); } + if ($statut == self::STATUS_CLOSED) { return $langs->trans("ServiceStatusClosed").' '.img_picto($langs->trans('ServiceStatusClosed'),'statut6'); } } } @@ -2865,6 +2863,9 @@ class ContratLigne extends CommonObjectLine $this->db->begin(); + $this->oldcopy = new ContratLigne($this->db); + $this->oldcopy->fetch($this->id); + // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET"; $sql.= " fk_contrat=".$this->fk_contrat.","; @@ -2904,22 +2905,14 @@ class ContratLigne extends CommonObjectLine dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - $contrat=new Contrat($this->db); - $contrat->fetch($this->fk_contrat); - $result=$contrat->update_statut($user); - } - else + if (! $resql) { $this->error="Error ".$this->db->lasterror(); $error++; - //return -1; } if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) // For avoid conflicts if trigger used { - $result=$this->insertExtraFields(); if ($result < 0) { @@ -2927,19 +2920,52 @@ class ContratLigne extends CommonObjectLine } } - if (empty($error)) { - if (! $notrigger) + // If we change a planned date (start or end), sync dates for all services + if (! $error && ! empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) { - // Call trigger - $result=$this->call_trigger('LINECONTRACT_UPDATE',$user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } - // End call triggers - } + if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue) + { + $sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET'; + $sql.= " date_ouverture_prevue = ".($this->date_ouverture_prevue!=''?"'".$this->db->idate($this->date_ouverture_prevue)."'":"null"); + $sql.= " WHERE fk_contrat = ".$this->fk_contrat; + + $resql = $this->db->query($sql); + if (! $resql) + { + $error++; + $this->error="Error ".$this->db->lasterror(); + } + } + if ($this->date_fin_validite != $this->oldcopy->date_fin_validite) + { + $sql ='UPDATE '.MAIN_DB_PREFIX.'contratdet SET'; + $sql.= " date_fin_validite = ".($this->date_fin_validite!=''?"'".$this->db->idate($this->date_fin_validite)."'":"null"); + $sql.= " WHERE fk_contrat = ".$this->fk_contrat; + + $resql = $this->db->query($sql); + if (! $resql) + { + $error++; + $this->error="Error ".$this->db->lasterror(); + } + } } - if (empty($error)) { - $this->db->commit(); - return 1; + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('LINECONTRACT_UPDATE', $user); + if ($result < 0) { $error++; $this->db->rollback(); } + // End call triggers + } + } + + if (! $error) + { + $this->db->commit(); + return 1; } else { $this->db->rollback(); $this->errors[]=$this->error; @@ -3081,25 +3107,25 @@ class ContratLigne extends CommonObjectLine $this->db->begin(); - $sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = 4,"; + $sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_OPEN.","; $sql .= " date_ouverture = " . (dol_strlen($date) != 0 ? "'" . $this->db->idate($date) . "'" : "null") . ","; if ($date_end >= 0) $sql .= " date_fin_validite = " . (dol_strlen($date_end) != 0 ? "'" . $this->db->idate($date_end) . "'" : "null") . ","; $sql .= " fk_user_ouverture = " . $user->id . ","; $sql .= " date_cloture = null,"; $sql .= " commentaire = '" . $this->db->escape($comment) . "'"; - $sql .= " WHERE rowid = " . $this->id . " AND (statut = 0 OR statut = 3 OR statut = 5)"; + $sql .= " WHERE rowid = " . $this->id . " AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")"; dol_syslog(get_class($this) . "::active_line", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { // Call trigger - $result = $this->call_trigger('CONTRACT_SERVICE_ACTIVATE', $user); + $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user); if ($result < 0) $error++; // End call triggers if (! $error) { - $this->statut = 4; + $this->statut = ContratLigne::STATUS_OPEN; $this->date_ouverture = $date; $this->date_fin_validite = $date_end; $this->fk_user_ouverture = $user->id; @@ -3124,12 +3150,13 @@ class ContratLigne extends CommonObjectLine /** * Close a contract line * - * @param User $user Objet User who close contract - * @param int $date_end Date end - * @param string $comment A comment typed by user - * @return int <0 if KO, >0 if OK + * @param User $user Objet User who close contract + * @param int $date_end Date end + * @param string $comment A comment typed by user + * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers + * @return int <0 if KO, >0 if OK */ - function close_line($user, $date_end, $comment = '') + function close_line($user, $date_end, $comment = '', $notrigger=0) { global $langs, $conf; @@ -3144,22 +3171,26 @@ class ContratLigne extends CommonObjectLine $this->db->begin(); - $sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = 5,"; + $sql = "UPDATE " . MAIN_DB_PREFIX . "contratdet SET statut = ".ContratLigne::STATUS_CLOSED.","; $sql .= " date_cloture = '" . $this->db->idate($date_end) . "',"; $sql .= " fk_user_cloture = " . $user->id . ","; $sql .= " commentaire = '" . $this->db->escape($comment) . "'"; - $sql .= " WHERE rowid = " . $this->id . " AND statut = 4"; + $sql .= " WHERE rowid = " . $this->id . " AND statut = ".ContratLigne::STATUS_OPEN; $resql = $this->db->query($sql); - if ($resql) { - // Call trigger - $result = $this->call_trigger('CONTRACT_SERVICE_CLOSE', $user); - if ($result < 0) { - $error++; - $this->db->rollback(); - return -1; + if ($resql) + { + if (! $notrigger) + { + // Call trigger + $result = $this->call_trigger('LINECONTRACT_CLOSE', $user); + if ($result < 0) { + $error++; + $this->db->rollback(); + return -1; + } + // End call triggers } - // End call triggers $this->db->commit(); return 1; diff --git a/htdocs/contrat/contact.php b/htdocs/contrat/contact.php index 64050c3512d..4d403198eb8 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -33,9 +33,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } - -$langs->load("contracts"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('contracts', 'companies')); $action=GETPOST('action','alpha'); $confirm=GETPOST('confirm','alpha'); @@ -49,8 +48,13 @@ $result=restrictedArea($user,'contrat',$id); $object = new Contrat($db); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('contractcard','globalcard')); -// Add new contact + +/* + * Actions + */ if ($action == 'addcontact' && $user->rights->contrat->creer) { diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index 32fcd5a64bd..0208d68f80d 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -37,9 +37,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load("other"); -$langs->load("products"); -$langs->load("contracts"); +// Load translation files required by the page +$langs->loadLangs(array('other', 'products', 'contracts')); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm','alpha'); @@ -77,10 +76,14 @@ if ($object->id > 0) $upload_dir = $conf->contrat->dir_output.'/'.dol_sanitizeFileName($object->ref); $modulepart='contract'; +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('contractcard','globalcard')); + /* * Actions */ + include_once DOL_DOCUMENT_ROOT . '/core/actions_linkedfiles.inc.php'; @@ -177,7 +180,7 @@ if ($object->id) print ''; print ''; - print ''; + print ''; print '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'.$langs->trans("TotalSizeOfAttachedFiles").''.dol_print_size($totalsize,1,1).'
'; print ''; diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 5d3a3603b8f..b78bf52b6be 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -28,9 +28,8 @@ require ("../main.inc.php"); require_once (DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php"); require_once (DOL_DOCUMENT_ROOT."/product/class/product.class.php"); -$langs->load("products"); -$langs->load("companies"); -$langs->load("contracts"); +// Load translation files required by the page +$langs->loadLangs(array('products', 'companies', 'contracts')); $sortfield=GETPOST('sortfield','alpha'); $sortorder=GETPOST('sortorder','alpha'); diff --git a/htdocs/contrat/info.php b/htdocs/contrat/info.php index 10f31ac1612..8899351c284 100644 --- a/htdocs/contrat/info.php +++ b/htdocs/contrat/info.php @@ -30,6 +30,7 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } +// Load translation files required by the page $langs->load("contracts"); $action = GETPOST('action','alpha'); @@ -41,6 +42,17 @@ $ref = GETPOST('ref','alpha'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'contrat', $id, ''); +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('contractcard','globalcard')); + + +/* + * Actions + */ + +// None + + /* * View diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index cdafbd6c2fd..18e78c7ff0a 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -6,7 +6,7 @@ * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Claudio Aschieri * Copyright (C) 2015 Jean-François Ferry - * Copyright (C) 2016 Ferran Marcet + * Copyright (C) 2016-2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -35,16 +35,15 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; -$langs->load("contracts"); -$langs->load("products"); -$langs->load("companies"); -$langs->load("compta"); +// Load translation files required by the page +$langs->loadLangs(array('contracts', 'products', 'companies', 'compta')); $action=GETPOST('action','alpha'); $massaction=GETPOST('massaction','alpha'); $show_files=GETPOST('show_files','int'); $confirm=GETPOST('confirm','alpha'); $toselect = GETPOST('toselect', 'array'); +$contextpage= GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'contractlist'; // To manage different context of search $search_name=GETPOST('search_name'); $search_email=GETPOST('search_email'); @@ -95,10 +94,8 @@ $staticcontratligne=new ContratLigne($db); if ($search_status == '') $search_status=1; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$contextpage='contractlist'; - -// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array($contextpage)); +$object = new Contrat($db); +$hookmanager->initHooks(array('contractlist')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -205,8 +202,6 @@ $formother = new FormOther($db); $socstatic = new Societe($db); $contracttmp = new Contrat($db); -llxHeader('', $langs->trans("Contracts")); - $sql = 'SELECT'; $sql.= " c.rowid, c.ref, c.datec as date_creation, c.tms as date_update, c.date_contrat, c.statut, c.ref_customer, c.ref_supplier, c.note_private, c.note_public,"; $sql.= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; @@ -304,500 +299,523 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql.= $db->plimit($limit + 1, $offset); $resql=$db->query($sql); -if ($resql) +if (! $resql) { - $num = $db->num_rows($resql); - $i = 0; + dol_print_error($db); + exit; +} - $arrayofselected=is_array($toselect)?$toselect:array(); +$num = $db->num_rows($resql); - if ($socid > 0) +// Direct jump if only one record found +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.'/contrat/card.php?id='.$id); + exit; +} + + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $langs->trans("Contracts")); + +$i = 0; + +$arrayofselected=is_array($toselect)?$toselect:array(); + +if ($socid > 0) +{ + $soc = new Societe($db); + $soc->fetch($socid); + if (empty($search_name)) $search_name = $soc->name; +} + +$param=''; +if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; +if ($sall != '') $param.='&sall='.urlencode($sall); +if ($search_contract != '') $param.='&search_contract='.urlencode($search_contract); +if ($search_name != '') $param.='&search_name='.urlencode($search_name); +if ($search_email != '') $param.='&search_email='.urlencode($search_email); +if ($search_ref_customer != '') $param.='&search_ref_customer='.urlencode($search_ref_customer); +if ($search_ref_supplier != '') $param.='&search_ref_supplier='.urlencode($search_ref_supplier); +if ($search_op2df != '') $param.='&search_op2df='.urlencode($search_op2df); +if ($search_dfyear != '') $param.='&search_dfyear='.urlencode($search_dfyear); +if ($search_dfmonth != '') $param.='&search_dfmonth='.urlencode($search_dfmonth); +if ($search_sale != '') $param.='&search_sale=' .urlencode($search_sale); +if ($search_user != '') $param.='&search_user=' .urlencode($search_user); +if ($search_product_category != '') $param.='&search_product_category=' .urlencode($search_product_category); +if ($show_files) $param.='&show_files=' .urlencode($show_files); +if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + +// List of mass actions available +$arrayofmassactions = array( + 'presend'=>$langs->trans("SendByMail"), + 'builddoc'=>$langs->trans("PDFMerge"), +); +if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); +if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + +$newcardbutton=''; +if ($user->rights->contrat->creer) +{ + $newcardbutton=''.$langs->trans('NewContractSubscription').''; + $newcardbutton.= ''; + $newcardbutton.= ''; +} + +print '
'; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, $newcardbutton, '', $limit); + +$topicmail="SendContractRef"; +$modelmail="contract"; +$objecttmp=new Contrat($db); +$trackid='con'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($sall) +{ + foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'
'; +} + +$moreforfilter=''; + +// If the user can view prospects other than his' +if ($user->rights->societe->client->voir || $socid) +{ + $langs->load("commercial"); + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; + $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); + $moreforfilter.='
'; +} +// If the user can view other users +if ($user->rights->user->user->lire) +{ + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; + $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + $moreforfilter.='
'; +} +// If the user can view categories of products +if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) +{ + include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + $moreforfilter.='
'; + $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; + $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); + $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 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 +if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + +print '
'; +print ''."\n"; + +print ''; +if (! empty($arrayfields['c.ref']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['c.ref_customer']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['c.ref_supplier']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['s.nom']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['s.email']['checked'])) +{ + print ''; +} +// Town +if (! empty($arrayfields['s.town']['checked'])) print ''; +// Zip +if (! empty($arrayfields['s.zip']['checked'])) print ''; +// State +if (! empty($arrayfields['state.nom']['checked'])) +{ + print ''; +} +// Country +if (! empty($arrayfields['country.code_iso']['checked'])) +{ + print ''; +} +// Company type +if (! empty($arrayfields['typent.code']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['sale_representative']['checked'])) +{ + print ''; +} +if (! empty($arrayfields['c.date_contrat']['checked'])) +{ + // Date contract + print ''; +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// 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['c.datec']['checked'])) +{ + print ''; +} +// Date modification +if (! empty($arrayfields['c.tms']['checked'])) +{ + print ''; +} +// First end date +if (! empty($arrayfields['lower_planned_end_date']['checked'])) +{ + print ''; +} +// Status +if (! empty($arrayfields['status']['checked'])) +{ + print ''; +} +print ''; +print "\n"; + +print ''; +if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); +if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); +if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); +if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); +if (! empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email","","$param",'',$sortfield,$sortorder); +if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); +if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); +if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); +if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); +$reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +if (! empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['lower_planned_end_date']['checked'])) print_liste_field_titre($arrayfields['lower_planned_end_date']['label'],$_SERVER["PHP_SELF"],"lower_planned_end_date","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); +if (! empty($arrayfields['status']['checked'])) +{ + print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); + print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); +} +print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); +print "\n"; + +while ($i < min($num,$limit)) +{ + $obj = $db->fetch_object($resql); + + $contracttmp->ref=$obj->ref; + $contracttmp->id=$obj->rowid; + $contracttmp->ref_customer=$obj->ref_customer; + $contracttmp->ref_supplier=$obj->ref_supplier; + + if ($obj->socid > 0) { - $soc = new Societe($db); - $soc->fetch($socid); - if (empty($search_name)) $search_name = $soc->name; + $result=$socstatic->fetch($obj->socid); } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.$limit; - if ($sall != '') $param.='&sall='.urlencode($sall); - if ($search_contract != '') $param.='&search_contract='.urlencode($search_contract); - if ($search_name != '') $param.='&search_name='.urlencode($search_name); - if ($search_email != '') $param.='&search_email='.urlencode($search_email); - if ($search_ref_customer != '') $param.='&search_ref_customer='.urlencode($search_ref_customer); - if ($search_ref_supplier != '') $param.='&search_ref_supplier='.urlencode($search_ref_supplier); - if ($search_op2df != '') $param.='&search_op2df='.urlencode($search_op2df); - if ($search_dfyear != '') $param.='&search_dfyear='.urlencode($search_dfyear); - if ($search_dfmonth != '') $param.='&search_dfmonth='.urlencode($search_dfmonth); - if ($search_sale != '') $param.='&search_sale=' .urlencode($search_sale); - if ($search_user != '') $param.='&search_user=' .urlencode($search_user); - if ($search_product_category != '') $param.='&search_product_category=' .urlencode($search_product_category); - if ($show_files) $param.='&show_files=' .urlencode($show_files); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); - // Add $param from extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - - // List of mass actions available - $arrayofmassactions = array( - 'presend'=>$langs->trans("SendByMail"), - 'builddoc'=>$langs->trans("PDFMerge"), - ); - if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete']=$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); - - print ''; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $totalnboflines, 'title_commercial.png', 0, '', '', $limit); - - $topicmail="SendContractRef"; - $modelmail="contract"; - $objecttmp=new Contrat($db); - $trackid='con'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - - if ($sall) - { - foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); - } - - $moreforfilter=''; - - // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': '; - $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user,0,1,'maxwidth200'); - $moreforfilter.='
'; - } - // If the user can view other users - if ($user->rights->user->user->lire) - { - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': '; - $moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter.='
'; - } - // If the user can view categories of products - if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) - { - include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - $moreforfilter.='
'; - $moreforfilter.=$langs->trans('IncludingProductWithTag'). ': '; - $cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1); - $moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 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 - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); - - print '
'; - print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; + //print $langs->trans('Month').': '; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + //print ' '.$langs->trans('Year').': '; + $syear = $year; + print $formother->selectyear($syear,'year',1, 20, 5); + print ''; + print ''; + print ''; + $arrayofoperators=array('0'=>'','='=>'=','<='=>'<=','>='=>'>='); + print $form->selectarray('search_op2df',$arrayofoperators,$search_op2df,0); + print '
'; + print $formother->select_month($search_dfmonth, 'search_dfmonth', 1, 0, 'valignmiddle'); + print ' '; + $formother->select_year($search_dfyear, 'search_dfyear', 1, 20, 5, 0, 0, '', 'valignmiddle'); + print '
'; +$searchpicto=$form->showFilterButtons(); +print $searchpicto; +print '
'."\n"; - - print ''; + print ''; if (! empty($arrayfields['c.ref']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['c.ref_customer']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['c.ref_supplier']['checked'])) { - print ''; + print ''; } if (! empty($arrayfields['s.nom']['checked'])) { - print ''; } if (! empty($arrayfields['s.email']['checked'])) { - print ''; + print ''; } // Town - if (! empty($arrayfields['s.town']['checked'])) print ''; + if (! empty($arrayfields['s.town']['checked'])) + { + print ''; + if (! $i) $totalarray['nbfield']++; + } // Zip - if (! empty($arrayfields['s.zip']['checked'])) print ''; + if (! empty($arrayfields['s.zip']['checked'])) + { + 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']++; } - // Company type + // Type ent if (! empty($arrayfields['typent.code']['checked'])) { - print ''; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['sale_representative']['checked'])) { - print ''; - } - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - // Date contract - print ''; } + // Date + if (! empty($arrayfields['c.date_contrat']['checked'])) + { + print ''; + } // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; - + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // 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['c.datec']['checked'])) { - print ''; + if (! $i) $totalarray['nbfield']++; } // Date modification if (! empty($arrayfields['c.tms']['checked'])) { - print ''; + if (! $i) $totalarray['nbfield']++; } - // First end date + // Date lower end date if (! empty($arrayfields['lower_planned_end_date']['checked'])) { - print ''; + print ''; + if (! $i) $totalarray['nbfield']++; } // Status if (! empty($arrayfields['status']['checked'])) { - print ''; + print ''; + print ''; + print ''; + print ''; + } + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + print "\n"; - - print ''; - if (! empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'],$_SERVER["PHP_SELF"],'s.town','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'],$_SERVER["PHP_SELF"],'s.zip','',$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); - if (! empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'],$_SERVER["PHP_SELF"],"country.code_iso","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'],$_SERVER["PHP_SELF"],"typent.code","",$param,'align="center"',$sortfield,$sortorder); - if (! empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "","","$param",'',$sortfield,$sortorder); - if (! empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - // 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['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'],$_SERVER["PHP_SELF"],"c.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'],$_SERVER["PHP_SELF"],"c.tms","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['lower_planned_end_date']['checked'])) print_liste_field_titre($arrayfields['lower_planned_end_date']['label'],$_SERVER["PHP_SELF"],"lower_planned_end_date","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); - if (! empty($arrayfields['status']['checked'])) - { - print_liste_field_titre($staticcontratligne->LibStatut(0,3), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,0), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(4,3,1), '', '', '', '', 'width="16"'); - print_liste_field_titre($staticcontratligne->LibStatut(5,3), '', '', '', '', 'width="16"'); - } - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"],"",'','','align="center"',$sortfield,$sortorder,'maxwidthsearch '); - print "\n"; - - while ($i < min($num,$limit)) - { - $obj = $db->fetch_object($resql); - - $contracttmp->ref=$obj->ref; - $contracttmp->id=$obj->rowid; - $contracttmp->ref_customer=$obj->ref_customer; - $contracttmp->ref_supplier=$obj->ref_supplier; - - if ($obj->socid > 0) - { - $result=$socstatic->fetch($obj->socid); - } - - print ''; - if (! empty($arrayfields['c.ref']['checked'])) - { - print ''; - - print ''; - } - if (! empty($arrayfields['c.ref_customer']['checked'])) - { - print ''; - } - if (! empty($arrayfields['c.ref_supplier']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.nom']['checked'])) - { - print ''; - } - if (! empty($arrayfields['s.email']['checked'])) - { - print ''; - } - // Town - if (! empty($arrayfields['s.town']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Zip - if (! empty($arrayfields['s.zip']['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']++; - } - // Type ent - if (! empty($arrayfields['typent.code']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - if (! empty($arrayfields['sale_representative']['checked'])) - { - // Sales representatives - print ''; - } - // Date - if (! empty($arrayfields['c.date_contrat']['checked'])) - { - print ''; - } - // Extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - // 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['c.datec']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date modification - if (! empty($arrayfields['c.tms']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Date lower end date - if (! empty($arrayfields['lower_planned_end_date']['checked'])) - { - print ''; - if (! $i) $totalarray['nbfield']++; - } - // Status - if (! empty($arrayfields['status']['checked'])) - { - print ''; - print ''; - print ''; - print ''; - } - // Action column - print ''; - if (! $i) $totalarray['nbfield']++; - - print "\n"; - $i++; - } - $db->free($resql); - - print '
'; - print ''; + print ''; + print $contracttmp->getNomUrl(1); + if ($obj->nb_late) print img_warning($langs->trans("Late")); + if (!empty($obj->note_private) || !empty($obj->note_public)) + { + print ' '; + print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; + print ''; + } + + $filename=dol_sanitizeFileName($obj->ref); + $filedir=$conf->contrat->dir_output . '/' . dol_sanitizeFileName($obj->ref); + $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; + print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); + print ''; - print ''; - print ''.$obj->ref_customer.''; - print ''; - print ''.$obj->ref_supplier.''; - print ''; + print ''; + //print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; + if ($obj->socid > 0) + { + print $socstatic->getNomUrl(1, ''); + } print ''; - print ''; - print ''.$obj->email.''; + print $obj->town; + print ''; + print $obj->zip; + print ''; - print ''; - print '".$obj->state_name."'; - print $form->select_country($search_country,'search_country','',0,'maxwidth100'); + print ''; + $tmparray=getCountry($obj->fk_pays,'all'); + print $tmparray['label']; print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT)?'ASC':$conf->global->SOCIETE_SORT_ON_TYPEENT)); + print ''; + if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); + print $typenArray[$obj->typent_code]; print ''; - //print $langs->trans('Month').': '; - if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - //print ' '.$langs->trans('Year').': '; - $syear = $year; - $formother->select_year($syear,'year',1, 20, 5); + // Sales representatives + print ''; + if ($obj->socid > 0) + { + $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); + if ($listsalesrepresentatives < 0) dol_print_error($db); + $nbofsalesrepresentative=count($listsalesrepresentatives); + if ($nbofsalesrepresentative > 3) // We print only number + { + print ''; + print $nbofsalesrepresentative; + print ''; + } + else if ($nbofsalesrepresentative > 0) + { + $userstatic=new User($db); + $j=0; + foreach($listsalesrepresentatives as $val) + { + $userstatic->id=$val['id']; + $userstatic->lastname=$val['lastname']; + $userstatic->firstname=$val['firstname']; + $userstatic->email=$val['email']; + $userstatic->statut=$val['statut']; + $userstatic->entity=$val['entity']; + $userstatic->photo=$val['photo']; + + //print '
': + print $userstatic->getNomUrl(-2); + $j++; + if ($j < $nbofsalesrepresentative) print ' '; + //print '
'; + } + } + //else print $langs->trans("NoSalesRepresentativeAffected"); + } + else + { + print ' '; + } print '
'.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzuser').''; + print ''; + print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; + print ''; + print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; - $arrayofoperators=array('0'=>'','='=>'=','<='=>'<=','>='=>'>='); - print $form->selectarray('search_op2df',$arrayofoperators,$search_op2df,0); - print '
'; - print $formother->select_month($search_dfmonth, 'search_dfmonth', 1); - print ' '; - $formother->select_year($search_dfyear, 'search_dfyear', 1, 20, 5); - print '
'; + print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day', 'tzuser'); + print ''.($obj->nb_initial>0?$obj->nb_initial:'').''.($obj->nb_running>0?$obj->nb_running:'').''.($obj->nb_expired>0?$obj->nb_expired:'').''.($obj->nb_closed>0 ?$obj->nb_closed:'').''; + 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 ''; - $searchpicto=$form->showFilterButtons(); - print $searchpicto; print '
'; - print $contracttmp->getNomUrl(1); - if ($obj->nb_late) print img_warning($langs->trans("Late")); - if (!empty($obj->note_private) || !empty($obj->note_public)) - { - print ' '; - print ''.img_picto($langs->trans("ViewPrivateNote"),'object_generic').''; - print ''; - } - - $filename=dol_sanitizeFileName($obj->ref); - $filedir=$conf->contrat->dir_output . '/' . dol_sanitizeFileName($obj->ref); - $urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid; - print $formfile->getDocumentsLink($contracttmp->element, $filename, $filedir); - print ''.$obj->ref_customer.''.$obj->ref_supplier.''; - //print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; - if ($obj->socid > 0) - { - print $socstatic->getNomUrl(1, ''); - } - print ''.$obj->email.''; - print $obj->town; - print ''; - print $obj->zip; - print '".$obj->state_name."'; - $tmparray=getCountry($obj->fk_pays,'all'); - print $tmparray['label']; - print ''; - if (count($typenArray)==0) $typenArray = $formcompany->typent_array(1); - print $typenArray[$obj->typent_code]; - print ''; - if ($obj->socid > 0) - { - $listsalesrepresentatives=$socstatic->getSalesRepresentatives($user); - if ($listsalesrepresentatives < 0) dol_print_error($db); - $nbofsalesrepresentative=count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) // We print only number - { - print ''; - print $nbofsalesrepresentative; - print ''; - } - else if ($nbofsalesrepresentative > 0) - { - $userstatic=new User($db); - $j=0; - foreach($listsalesrepresentatives as $val) - { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['lastname']; - $userstatic->firstname=$val['firstname']; - $userstatic->email=$val['email']; - $userstatic->statut=$val['statut']; - $userstatic->entity=$val['entity']; - $userstatic->photo=$val['photo']; - - //print '
': - print $userstatic->getNomUrl(-2); - $j++; - if ($j < $nbofsalesrepresentative) print ' '; - //print '
'; - } - } - //else print $langs->trans("NoSalesRepresentativeAffected"); - } - else - { - print ' '; - } - print '
'.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzuser').''; - print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); - print ''; - print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); - print ''; - print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day', 'tzuser'); - print ''.($obj->nb_initial>0?$obj->nb_initial:'').''.($obj->nb_running>0?$obj->nb_running:'').''.($obj->nb_expired>0?$obj->nb_expired:'').''.($obj->nb_closed>0 ?$obj->nb_closed:'').''; - 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 '
'; - print '
'; - - print '
'; - - 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->contrat->lire; - $delallowed=$user->rights->contrat->lire; - - print $formfile->showdocuments('massfilesarea_contract','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,''); - } - else - { - print '
'.$langs->trans("ShowTempMassFilesArea").''; - } -} -else -{ - dol_print_error($db); + $i++; } +$db->free($resql); + +print '
'; +print '
'; + +print ''; + +$hidegeneratedfilelistifempty=1; +if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty=0; + +// Show list of available documents +$urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; +$urlsource.=str_replace('&','&',$param); + +$filedir=$diroutputmassaction; +$genallowed=$user->rights->contrat->lire; +$delallowed=$user->rights->contrat->lire; + +print $formfile->showdocuments('massfilesarea_contract','',$filedir,$urlsource,0,$delallowed,'',1,1,0,48,1,$param,$title,'','','',null,$hidegeneratedfilelistifempty); llxFooter(); diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php index 9a6d28dd4c9..c160201191a 100644 --- a/htdocs/contrat/note.php +++ b/htdocs/contrat/note.php @@ -31,8 +31,8 @@ if (! empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; } -$langs->load("companies"); -$langs->load("contracts"); +// Load translation files required by the page +$langs->loadLangs(array('companies', 'contracts')); $action=GETPOST('action','alpha'); $confirm=GETPOST('confirm','alpha'); @@ -49,6 +49,10 @@ $object->fetch($id,$ref); $permissionnote=$user->rights->contrat->creer; // Used by the include of actions_setnotes.inc.php +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('contractcard','globalcard')); + + /* * Actions diff --git a/htdocs/contrat/services_list.php b/htdocs/contrat/services_list.php index 108fb6d4403..66c56e2a162 100644 --- a/htdocs/contrat/services_list.php +++ b/htdocs/contrat/services_list.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2016 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2018 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -29,9 +30,8 @@ require_once (DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php"); require_once (DOL_DOCUMENT_ROOT."/product/class/product.class.php"); require_once (DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"); -$langs->load("products"); -$langs->load("contracts"); -$langs->load("companies"); +// Load translation files required by the page +$langs->loadLangs(array('products', 'contracts', 'companies')); $limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit; $sortfield = GETPOST("sortfield",'alpha'); @@ -53,6 +53,7 @@ $search_status=GETPOST("search_status","alpha"); $statut=GETPOST('statut')?GETPOST('statut'):1; $search_product_category=GETPOST('search_product_category','int'); $socid=GETPOST('socid','int'); +$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'contractservicelist'.$mode; $opouvertureprevuemonth=GETPOST('opouvertureprevuemonth'); $opouvertureprevueday=GETPOST('opouvertureprevueday'); @@ -74,11 +75,10 @@ $opclotureday=GETPOST('opclotureday'); $opclotureyear=GETPOST('opclotureyear'); $filter_opcloture=GETPOST('filter_opcloture'); -// Initialize context for list -$contextpage=GETPOST('contextpage','aZ')?GETPOST('contextpage','aZ'):'contractservicelist'.$mode; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array($contextpage)); +$object = new ContratLigne($db); +$hookmanager->initHooks(array('contractservicelist')); $extrafields = new ExtraFields($db); // fetch optionals attributes and labels @@ -197,13 +197,14 @@ $now=dol_now(); $form=new Form($db); $sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut,"; -$sql.= " s.rowid as socid, s.nom as name,"; +$sql.= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,"; $sql.= " cd.rowid, cd.description, cd.statut,"; $sql.= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; $sql.= " cd.date_ouverture_prevue,"; $sql.= " cd.date_ouverture,"; $sql.= " cd.date_fin_validite,"; +$sql.= " cd.date_cloture,"; $sql.= " cd.qty,"; $sql.= " cd.total_ht,"; $sql.= " cd.total_tva,"; @@ -255,6 +256,11 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 + { + $page = 0; + $offset = 0; + } } $sql .= $db->plimit($limit + 1, $offset); @@ -330,7 +336,7 @@ print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sort if ($sall) { foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall); + print '
'.$langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall).'
'; } $morefilter = ''; @@ -382,7 +388,7 @@ if (! empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields -$parameters=array('arrayfields'=>$arrayfields); +$parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); $reshook=$hookmanager->executeHooks('printFieldListTitle',$parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (! empty($arrayfields['cd.datec']['checked'])) print_liste_field_titre($arrayfields['cd.datec']['label'],$_SERVER["PHP_SELF"],"cd.datec","",$param,'align="center" class="nowrap"',$sortfield,$sortorder); @@ -525,7 +531,8 @@ print "\n"; $contractstatic=new Contrat($db); $productstatic=new Product($db); -$var=True; $i=0; +$i=0; +$totalarray=array(); while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); @@ -533,6 +540,11 @@ while ($i < min($num,$limit)) $contractstatic->id=$obj->cid; $contractstatic->ref=$obj->ref?$obj->ref:$obj->cid; + $companystatic->id=$obj->socid; + $companystatic->name=$obj->name; + $companystatic->email=$obj->email; + $companystatic->client=$obj->client; + $companystatic->fournisseur=$obj->fournisseur; print ''; @@ -542,12 +554,13 @@ while ($i < min($num,$limit)) print ''; print $contractstatic->getNomUrl(1,16); print ''; + if (! $i) $totalarray['nbfield']++; } // Service if (! empty($arrayfields['p.description']['checked'])) { print ''; - if ($obj->pid) + if ($obj->pid > 0) { $productstatic->id=$obj->pid; $productstatic->type=$obj->ptype; @@ -563,6 +576,7 @@ while ($i < min($num,$limit)) if ($obj->type == 1) print img_object($obj->description,'service').' '.dol_trunc($obj->description,24); } print ''; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['cd.qty']['checked'])) @@ -570,30 +584,45 @@ while ($i < min($num,$limit)) print ''; print $obj->qty; print ''; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['cd.total_ht']['checked'])) { - print ''; + print ''; print price($obj->total_ht); print ''; - } + $totalarray['totalht'] += $obj->total_ht; + if (! $i) { + $totalarray['displaytotalline']++; + $totalarray['nbfield']++; + $totalarray['totalhtfield']=$totalarray['nbfield']; + } + } if (! empty($arrayfields['cd.total_tva']['checked'])) { - print ''; + print ''; print price($obj->total_tva); print ''; - } + $totalarray['totalvat'] += $obj->total_tva; + if (! $i) { + $totalarray['nbfield']++; + $totalarray['totalvatfield']=$totalarray['nbfield']; + $totalarray['displaytotalline']++; + } + } if (! empty($arrayfields['cd.tva_tx']['checked'])) { - print ''; + print ''; print price2num($obj->tva_tx).'%'; print ''; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['cd.subprice']['checked'])) { - print ''; + print ''; print price($obj->subprice); print ''; + if (! $i) $totalarray['nbfield']++; } @@ -601,31 +630,31 @@ while ($i < min($num,$limit)) if (! empty($arrayfields['s.nom']['checked'])) { print ''; - $companystatic->id=$obj->socid; - $companystatic->name=$obj->name; - $companystatic->client=1; print $companystatic->getNomUrl(1,'customer',28); print ''; + if (! $i) $totalarray['nbfield']++; } // Start date if (! empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print ''; - print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue)):' '); + print ($obj->date_ouverture_prevue?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour'):' '); if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) print ' '.img_picto($langs->trans("Late"),"warning"); else print '    '; print ''; + if (! $i) $totalarray['nbfield']++; } if (! empty($arrayfields['cd.date_ouverture']['checked'])) { - print ''.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture)):' ').''; + print ''.($obj->date_ouverture?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour'):' ').''; + if (! $i) $totalarray['nbfield']++; } // End date if (! empty($arrayfields['cd.date_fin_validite']['checked'])) { - print ''.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite)):' '); + print ''.($obj->date_fin_validite?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour'):' '); if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) { $warning_delay=$conf->contrat->services->expires->warning_delay / 3600 / 24; @@ -634,10 +663,13 @@ while ($i < min($num,$limit)) } else print '    '; print ''; + if (! $i) $totalarray['nbfield']++; } + // Close date (real end date) if (! empty($arrayfields['cd.date_cloture']['checked'])) { - print ''.dol_print_date($db->jdate($obj->date_cloture)).''; + print ''.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').''; + if (! $i) $totalarray['nbfield']++; } // Extra fields @@ -675,6 +707,7 @@ while ($i < min($num,$limit)) print $staticcontratligne->LibStatut($obj->statut,5,($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now)?1:0); } print ''; + if (! $i) $totalarray['nbfield']++; } // Action column print ''; @@ -690,6 +723,25 @@ while ($i < min($num,$limit)) print "\n"; $i++; } + +// Show total line +if (isset($totalarray['displaytotalline'])) { + print ''; + $i=0; + while ($i < $totalarray['nbfield']) { + $i++; + if ($i == 1) { + if ($num < $limit && empty($offset)) print ''.$langs->trans("Total").''; + else print ''.$langs->trans("Totalforthispage").''; + } + elseif ($totalarray['totalhtfield'] == $i) print ''.price($totalarray['totalht']).''; + elseif ($totalarray['totalvatfield'] == $i) print ''.price($totalarray['totalvat']).''; + elseif ($totalarray['totalttcfield'] == $i) print ''.price($totalarray['totalttc']).''; + else print ''; + } + print ''; +} + $db->free($resql); $parameters=array('sql' => $sql); diff --git a/htdocs/contrat/tpl/linkedobjectblock.tpl.php b/htdocs/contrat/tpl/linkedobjectblock.tpl.php index a44f20679b8..328be816327 100644 --- a/htdocs/contrat/tpl/linkedobjectblock.tpl.php +++ b/htdocs/contrat/tpl/linkedobjectblock.tpl.php @@ -35,15 +35,15 @@ global $noMoreLinkedObjectBlockAfter; $langs = $GLOBALS['langs']; $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; +// Load translation files required by the page $langs->load("contracts"); $total=0; $ilink=0; -$var=true; foreach($linkedObjectBlock as $key => $objectlink) { $ilink++; - $trclass=($var?'pair':'impair'); + $trclass='oddeven'; if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass.=' liste_sub_total'; ?> @@ -52,10 +52,10 @@ foreach($linkedObjectBlock as $key => $objectlink) date_contrat,'day'); ?> rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) + if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) { $totalcontrat = 0; foreach ($objectlink->lines as $linecontrat) { @@ -65,7 +65,7 @@ foreach($linkedObjectBlock as $key => $objectlink) echo price($totalcontrat); } ?> getLibStatut(7); ?> - ">transnoentitiesnoconv("RemoveLink")); ?> + ">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?> diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index ac9c80b37a5..c7cb1dc6f78 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -18,7 +18,7 @@ /** * \file htdocs/core/actions_addupdatedelete.inc.php - * \brief Code for common actions cancel / add / update / delete + * \brief Code for common actions cancel / add / update / delete / clone */ @@ -28,6 +28,7 @@ // $permissiontodelete must be defined // $backurlforlist must be defined // $backtopage may be defined +// $triggermodname may be defined if ($cancel) { @@ -75,7 +76,7 @@ if ($action == 'add' && ! empty($permissiontoadd)) if ($result > 0) { // Creation OK - $urltogo=$backtopage?$backtopage:$backurlforlist; + $urltogo=$backtopage?str_replace('__ID__', $result, $backtopage):$backurlforlist; header("Location: ".$urltogo); exit; } @@ -134,8 +135,7 @@ if ($action == 'update' && ! empty($permissiontoadd)) else { // Creation KO - if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); $action='edit'; } } @@ -145,6 +145,27 @@ if ($action == 'update' && ! empty($permissiontoadd)) } } +// Action to update one extrafield +if ($action == "update_extras" && ! empty($permissiontoadd)) +{ + $object->fetch(GETPOST('id','int')); + $attributekey = GETPOST('attribute','alpha'); + $attributekeylong = 'options_'.$attributekey; + $object->array_options['options_'.$attributekey] = GETPOST($attributekeylong,' alpha'); + + $result = $object->insertExtraFields(empty($triggermodname)?'':$triggermodname, $user); + if ($result > 0) + { + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); + $action = 'view'; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'edit_extras'; + } +} + // Action to delete if ($action == 'confirm_delete' && ! empty($permissiontodelete)) { @@ -162,3 +183,36 @@ if ($action == 'confirm_delete' && ! empty($permissiontodelete)) else setEventMessages($object->error, null, 'errors'); } } + +// Action clone object +if ($action == 'confirm_clone' && $confirm == 'yes' && ! empty($permissiontoadd)) +{ + if (1==0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) + { + setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); + } + else + { + if ($object->id > 0) + { + // Because createFromClone modifies the object, we must clone it so that we can restore it later + $orig = clone $object; + + $result=$object->createFromClone($user, $object->id); + if ($result > 0) + { + $newid = 0; + if (is_object($result)) $newid = $result->id; + else $newid = $result; + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$newid); // Open record of new object + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $object = $orig; + $action=''; + } + } + } +} diff --git a/htdocs/core/actions_linkedfiles.inc.php b/htdocs/core/actions_linkedfiles.inc.php index affbd1ec964..297f7821599 100644 --- a/htdocs/core/actions_linkedfiles.inc.php +++ b/htdocs/core/actions_linkedfiles.inc.php @@ -176,59 +176,91 @@ elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('l } elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha')) { - // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. + // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. if (! empty($upload_dir)) { - $reshook=$hookmanager->initHooks(array('actionlinkedfiles')); - $filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha'), '_', 0); // Do not remove accents $filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha'), '_', 0); // Do not remove accents - $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir); - $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object); + if ($filenamefrom != $filenameto) + { + // Security: + // Disallow file with some extensions. We rename them. + // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code. + if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) + { + $filenameto.= '.noexe'; + } - if (empty($reshook)) - { - // Security: - // Disallow file with some extensions. We rename them. - // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code. - if (preg_match('/\.htm|\.html|\.php|\.pl|\.cgi$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) - { - $filenameto.= '.noexe'; - } + if ($filenamefrom && $filenameto) + { + $srcpath = $upload_dir.'/'.$filenamefrom; + $destpath = $upload_dir.'/'.$filenameto; - if ($filenamefrom && $filenameto) - { - $srcpath = $upload_dir.'/'.$filenamefrom; - $destpath = $upload_dir.'/'.$filenameto; + $reshook=$hookmanager->initHooks(array('actionlinkedfiles')); + $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir); + $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object); - if (!file_exists($destpath)) - { - $result = dol_move($srcpath, $destpath); - if ($result) - { - if ($object->id) - { - $object->addThumbs($destpath); - } + if (empty($reshook)) + { + if (! file_exists($destpath)) + { + $result = dol_move($srcpath, $destpath); + if ($result) + { + if ($object->id) + { + $object->addThumbs($destpath); + } - // TODO Add revert function of addThumbs to remove for old name - //$object->delThumbs($srcpath); + // TODO Add revert function of addThumbs to remove for old name + //$object->delThumbs($srcpath); - setEventMessages($langs->trans("FileRenamed"), null); - } - else - { - $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now. - setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors'); - } - } - else - { - $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now. - setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors'); - } - } - } + setEventMessages($langs->trans("FileRenamed"), null); + } + else + { + $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now. + setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors'); + } + } + else + { + $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now. + setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors'); + } + } + } + } + } + + // Update properties in ECM table + if (GETPOST('ecmfileid', 'int') > 0) + { + $shareenabled = GETPOST('shareenabled', 'alpha'); + + include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; + $ecmfile=new EcmFiles($db); + $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int')); + if ($result > 0) + { + if ($shareenabled) + { + if (empty($ecmfile->share)) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; + $ecmfile->share = getRandomPassword(true); + } + } + else + { + $ecmfile->share = ''; + } + $result = $ecmfile->update($user); + if ($result < 0) + { + setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); + } + } } } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 979dc7945fa..4126fc44826 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -1,5 +1,6 @@ + * Copyright (C) 2018 Nicolas ZABOURI * Copyright (C) 2018 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -357,6 +358,14 @@ if (! $error && $massaction == 'confirm_presend') $substitutionarray['__CHECK_READ__'] = ''; $parameters=array('mode'=>'formemail'); + + if ( ! empty( $listofobjectthirdparties ) ) { + $parameters['listofobjectthirdparties'] = $listofobjectthirdparties; + } + if ( ! empty( $listofobjectref ) ) { + $parameters['listofobjectref'] = $listofobjectref; + } + complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters); $subject=make_substitutions($subject, $substitutionarray); @@ -736,6 +745,56 @@ if ($massaction == 'confirm_createbills') } } +if (!$error && $massaction == 'cancelorders') +{ + + $db->begin(); + + $nbok = 0; + + + $orders = GETPOST('toselect', 'array'); + foreach ($orders as $id_order) + { + + $cmd = new Commande($db); + if ($cmd->fetch($id_order) <= 0) + continue; + + if ($cmd->statut != Commande::STATUS_VALIDATED) + { + $langs->load('errors'); + setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors'); + $error++; + break; + } + else + $result = $cmd->cancel(); + + if ($result < 0) + { + setEventMessages($cmd->error, $cmd->errors, 'errors'); + $error++; + break; + } + else + $nbok++; + } + if (!$error) + { + if ($nbok > 1) + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + else + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + $db->commit(); + } + else + { + $db->rollback(); + } +} + + if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search')) { if (empty($diroutputmassaction)) @@ -982,7 +1041,41 @@ if (! $error && $massaction == 'validate' && $permtocreate) //var_dump($listofobjectthirdparties);exit; } } +// Closed records +if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permtoclose) { + $db->begin(); + $objecttmp = new $objectclass($db); + $nbok = 0; + foreach ($toselect as $toselectid) { + $result = $objecttmp->fetch($toselectid); + if ($result > 0) { + $result = $objecttmp->cloture($user, 3); + if ($result <= 0) { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } else + $nbok++; + } + else { + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; + } + } + + if (!$error) { + if ($nbok > 1) + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + else + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + $db->commit(); + } + else { + $db->rollback(); + } +} // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before) if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete) { @@ -995,24 +1088,23 @@ if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == $result=$objecttmp->fetch($toselectid); if ($result > 0) { - // Refuse deletion for some status ? - /* - if ($objectclass == 'Facture' && $objecttmp->status == Facture::STATUS_DRAFT) - { - $langs->load("errors"); - $nbignored++; - $resaction.='
'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'

'; - continue; - }*/ + // Refuse deletion for some objects/status + if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) + { + $langs->load("errors"); + $nbignored++; + $resaction.='
'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'

'; + continue; + } - if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); + if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); else $result = $objecttmp->delete($user); if ($result <= 0) { - setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); - $error++; - break; + setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); + $error++; + break; } else $nbok++; } diff --git a/htdocs/core/actions_printing.inc.php b/htdocs/core/actions_printing.inc.php index 62b61e531bf..302ad161241 100644 --- a/htdocs/core/actions_printing.inc.php +++ b/htdocs/core/actions_printing.inc.php @@ -1,6 +1,6 @@ - * Copyright (C) 2014 Frederic France + * Copyright (C) 2014-2018 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 @@ -28,7 +28,7 @@ // Filename to print must be provided into 'file' parameter // Print file -if ($action == 'print_file' and $user->rights->printing->read) +if ($action == 'print_file' && $user->rights->printing->read) { $langs->load("printing"); require_once DOL_DOCUMENT_ROOT . '/core/modules/printing/modules_printing.php'; diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 67ac879ebf5..8c81c0efc6a 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -106,7 +106,6 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $subject='';$actionmsg='';$actionmsg2=''; - if (! empty($conf->dolimail->enabled)) $langs->load("dolimail@dolimail"); $langs->load('mails'); if (is_object($object)) @@ -130,38 +129,14 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO { $thirdparty=$object; if ($thirdparty->id > 0) $sendtosocid=$thirdparty->id; - elseif (! empty($conf->dolimail->enabled)) - { - $dolimail = new Dolimail($db); - $possibleaccounts=$dolimail->get_societe_by_email($_POST['sendto'],"1"); - $possibleuser=$dolimail->get_from_user_by_mail($_POST['sendto'],"1"); // suche in llx_societe and socpeople - if (!$possibleaccounts && !$possibleuser) - { - setEventMessages($langs->trans('ErrorFailedToFindSocieteRecord',$_POST['sendto']), null, 'errors'); - } - elseif (count($possibleaccounts)>1) - { - $sendtosocid=$possibleaccounts[1]['id']; - $result=$object->fetch($sendtosocid); - - setEventMessages($langs->trans('ErrorFoundMoreThanOneRecordWithEmail',$_POST['sendto'],$object->name), null, 'mesgs'); - } - else - { - if($possibleaccounts){ - $sendtosocid=$possibleaccounts[1]['id']; - $result=$object->fetch($sendtosocid); - }elseif($possibleuser){ - $sendtosocid=$possibleuser[0]['id']; - - $result=$uobject->fetch($sendtosocid); - $object=$uobject; - } - - } - } } else dol_print_error('','Use actions_sendmails.in.php for an element/object that is not supported'); + + if (is_object($hookmanager)) + { + $parameters=array(); + $reshook=$hookmanager->executeHooks('initSendToSocid',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + } } else $thirdparty = $mysoc; @@ -171,6 +146,8 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $sendtocc=''; $sendtobcc=''; $sendtoid = array(); + $sendtouserid=array(); + $sendtoccuserid=array(); // Define $sendto $receiver=$_POST['receiver']; @@ -192,7 +169,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // Recipient was provided from combo list if ($val == 'thirdparty') // Id of third party { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + $tmparray[] = dol_string_nospecial($thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>'; } elseif ($val) // Id du contact { @@ -201,6 +178,20 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO } } } + if (!empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) + { + $receiveruser=$_POST['receiveruser']; + if (is_array($receiveruser) && count($receiveruser)>0) + { + $fuserdest = new User($db); + foreach($receiveruser as $key=>$val) + { + $tmparray[] = $fuserdest->user_get_property($val,'email'); + $sendtouserid[] = $val; + } + } + } + $sendto=implode(',',$tmparray); // Define $sendtocc @@ -222,7 +213,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // Recipient was provided from combo list if ($val == 'thirdparty') // Id of third party { - $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; + $tmparray[] = dol_string_nospecial($thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>'; } elseif ($val) // Id du contact { @@ -231,6 +222,19 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO } } } + if (!empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) { + $receiverccuser=$_POST['receiverccuser']; + + if (is_array($receiverccuser) && count($receiverccuser)>0) + { + $fuserdest = new User($db); + foreach($receiverccuser as $key=>$val) + { + $tmparray[] = $fuserdest->user_get_property($val,'email'); + $sendtoccuserid[] = $val; + } + } + } $sendtocc=implode(',',$tmparray); if (dol_strlen($sendto)) @@ -246,13 +250,13 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $fromtype = GETPOST('fromtype','alpha'); if ($fromtype === 'robot') { - $from = $conf->global->MAIN_MAIL_EMAIL_FROM .' <'.$conf->global->MAIN_MAIL_EMAIL_FROM.'>'; + $from = dol_string_nospecial($conf->global->MAIN_MAIL_EMAIL_FROM, ' ', array(",")) .' <'.$conf->global->MAIN_MAIL_EMAIL_FROM.'>'; } elseif ($fromtype === 'user') { - $from = $user->getFullName($langs) .' <'.$user->email.'>'; + $from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")) .' <'.$user->email.'>'; } elseif ($fromtype === 'company') { - $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; + $from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")) .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>'; } elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) { $tmp=explode(',', $user->email_aliases); @@ -268,14 +272,14 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $obj = $db->fetch_object($resql); if ($obj) { - $from = $obj->label.' <'.$obj->email.'>'; + $from = dol_string_nospecial($obj->label, ' ', array(",")).' <'.$obj->email.'>'; } } else { - $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; + $from = dol_string_nospecial($_POST['fromname'], ' ', array(",")) . ' <' . $_POST['frommail'] .'>'; } - $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; + $replyto = dol_string_nospecial($_POST['replytoname'], ' ', array(",")). ' <' . $_POST['replytomail'].'>'; $message = GETPOST('message','none'); $subject = GETPOST('subject','none'); @@ -320,6 +324,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $mimetype = $attachedfiles['mimes']; // Feature to push mail sent into Sent folder + /* This code must be now included into the hook mail, method sendMailAfter if (! empty($conf->dolimail->enabled)) { $mailfromid = explode("#", $_POST['frommail'],3); // $_POST['frommail'] = 'aaa#Sent# ' // TODO Use a better way to define Sent dir. @@ -328,7 +333,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO { $mbid = $mailfromid[1]; - /*IMAP Postbox*/ + // IMAP Postbox $mailboxconfig = new IMAP($db); $mailboxconfig->fetch($mbid); if ($mailboxconfig->mailbox_imap_host) $ref=$mailboxconfig->get_ref(); @@ -343,9 +348,9 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if (!$folder) $folder = "Sent"; // Default Sent folder $mailboxconfig->mbox = imap_open($mailboxconfig->get_connector_url().$folder, $mailboxconfig->mailbox_imap_login, $mailboxconfig->mailbox_imap_password); - if (FALSE === $mailboxconfig->mbox) + if (false === $mailboxconfig->mbox) { - $info = FALSE; + $info = false; $err = $langs->trans('Error3_Imap_Connection_Error'); setEventMessages($err,$mailboxconfig->element, null, 'errors'); } @@ -360,6 +365,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO } } } + */ // Make substitution in email content $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $object); @@ -392,7 +398,8 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $result=$mailfile->sendfile(); if ($result) { - // FIXME This must be moved into the trigger for action $trigger_name + // Two hooks are available into method $mailfile->sendfile, so dedicated code is no more required + /* if (! empty($conf->dolimail->enabled)) { $mid = (GETPOST('mid','int') ? GETPOST('mid','int') : 0); // Original mail id is set ? @@ -410,9 +417,9 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if ($movemail) setEventMessages($langs->trans("MailMovedToImapFolder",$folder), null, 'mesgs'); else setEventMessages($langs->trans("MailMovedToImapFolder_Warning",$folder), null, 'warnings'); } - } + }*/ - // Initialisation of datas + // Initialisation of datas of object to call trigger if (is_object($object)) { if (empty($actiontypecode)) $actiontypecode='AC_OTH_AUTO'; // Event insert into agenda automatically @@ -428,6 +435,9 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if (is_array($attachedfiles) && count($attachedfiles)>0) { $object->attachedfiles = $attachedfiles; } + if (is_array($sendtouserid) && count($sendtouserid)>0 && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) { + $object->sendtouserid = $sendtouserid; + } // Call of triggers if (! empty($trigger_name)) @@ -445,13 +455,11 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // This avoid sending mail twice if going out and then back to page $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)); setEventMessages($mesg, null, 'mesgs'); - if ($conf->dolimail->enabled) - { - header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.(is_object($object)?$object->id:'').'&'.($paramname2?$paramname2:'mid').'='.$parm2val); - exit; - } - header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.(is_object($object)?$object->id:'')); - exit; + + $moreparam=''; + if (isset($paramname2) || isset($paramval2)) $moreparam.= '&'.($paramname2?$paramname2:'mid').'='.$paramval2; + header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname?$paramname:'id').'='.(is_object($object)?$object->id:'').$moreparam); + exit; } else { diff --git a/htdocs/core/actions_setmoduleoptions.inc.php b/htdocs/core/actions_setmoduleoptions.inc.php index eadce1dc74c..03ff1491e49 100644 --- a/htdocs/core/actions_setmoduleoptions.inc.php +++ b/htdocs/core/actions_setmoduleoptions.inc.php @@ -31,13 +31,13 @@ if ($action == 'update' && is_array($arrayofparameters)) { $db->begin(); - $ok=True; + $ok=true; foreach($arrayofparameters as $key => $val) { $result=dolibarr_set_const($db,$key,GETPOST($key, 'alpha'),'chaine',0,'',$conf->entity); if ($result < 0) { - $ok=False; + $ok=false; break; } } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index 4d72b576429..f69cc85e026 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -93,7 +93,7 @@ if (empty($url)) else $url=DOL_URL_ROOT.'/ecm/index.php'; } -// Load traductions files +// Load translation files required by the page $langs->loadLangs(array("ecm","companies","other")); // Security check diff --git a/htdocs/core/ajax/ajaxdirtree.php b/htdocs/core/ajax/ajaxdirtree.php index 796ced332ab..cfff81749de 100644 --- a/htdocs/core/ajax/ajaxdirtree.php +++ b/htdocs/core/ajax/ajaxdirtree.php @@ -53,6 +53,7 @@ else // For no ajax call if (empty($url)) $url=DOL_URL_ROOT.'/ecm/index.php'; } +// Load translation files required by the page $langs->load("ecm"); // Define fullpathselecteddir. @@ -201,7 +202,7 @@ if (! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE print ''.img_view($langs->trans("Edit").' - '.$langs->trans("View"), 0, 'class="valignmiddle"').''; + print '">'.img_edit($langs->trans("Edit").' - '.$langs->trans("View"), 0, 'class="valignmiddle opacitymedium"').''; // Add link //print ''.img_edit_add().''; @@ -320,10 +321,8 @@ if (empty($conf->use_javascript_ajax) || ! empty($conf->global->MAIN_ECM_DISABLE $nbofentries=0; $oldvallevel=0; - $var=true; foreach($sqltree as $key => $val) { - $var=false; $ecmdirstatic->id=$val['id']; $ecmdirstatic->ref=$val['label']; diff --git a/htdocs/core/ajax/box.php b/htdocs/core/ajax/box.php index 612f38bb05b..f6bd5b5214a 100644 --- a/htdocs/core/ajax/box.php +++ b/htdocs/core/ajax/box.php @@ -26,8 +26,6 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOREQUIREHOOK')) define('NOREQUIREHOOK','1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; @@ -70,7 +68,7 @@ if ($boxorder && $zone != '' && $userid > 0) dol_syslog("AjaxBox boxorder=".$boxorder." zone=".$zone." userid=".$userid, LOG_DEBUG); $result=InfoBox::saveboxorder($db,$zone,$boxorder,$userid); - if ($result > 0) + if ($result > 0) { $langs->load("boxes"); if (! GETPOST('closing')) diff --git a/htdocs/core/ajax/constantonoff.php b/htdocs/core/ajax/constantonoff.php index f79753260d7..9e9f8a0d799 100644 --- a/htdocs/core/ajax/constantonoff.php +++ b/htdocs/core/ajax/constantonoff.php @@ -26,7 +26,6 @@ if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOREQUIREHOOK')) define('NOREQUIREHOOK','1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; diff --git a/htdocs/core/ajax/contacts.php b/htdocs/core/ajax/contacts.php index 1c7c7a56e4b..b03b9f128cf 100644 --- a/htdocs/core/ajax/contacts.php +++ b/htdocs/core/ajax/contacts.php @@ -23,10 +23,7 @@ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); require '../../main.inc.php'; diff --git a/htdocs/core/ajax/extraparams.php b/htdocs/core/ajax/extraparams.php index f8a636e52a5..908c1ef9f11 100644 --- a/htdocs/core/ajax/extraparams.php +++ b/htdocs/core/ajax/extraparams.php @@ -25,7 +25,6 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); include '../../main.inc.php'; diff --git a/htdocs/core/ajax/fileupload.php b/htdocs/core/ajax/fileupload.php index 6eb4d5836b8..9405aa26cf1 100644 --- a/htdocs/core/ajax/fileupload.php +++ b/htdocs/core/ajax/fileupload.php @@ -21,16 +21,10 @@ * \brief File to return Ajax response on file upload */ -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); -//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no menu to show if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php -//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) require '../../main.inc.php'; diff --git a/htdocs/core/ajax/getaccountcurrency.php b/htdocs/core/ajax/getaccountcurrency.php index 40e52672c0e..2289d8e1c0f 100644 --- a/htdocs/core/ajax/getaccountcurrency.php +++ b/htdocs/core/ajax/getaccountcurrency.php @@ -22,10 +22,7 @@ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); require '../../main.inc.php'; diff --git a/htdocs/core/ajax/loadinplace.php b/htdocs/core/ajax/loadinplace.php index 7e9e541c768..099f66ba3de 100644 --- a/htdocs/core/ajax/loadinplace.php +++ b/htdocs/core/ajax/loadinplace.php @@ -22,10 +22,8 @@ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php'; diff --git a/htdocs/core/ajax/price.php b/htdocs/core/ajax/price.php index d4a101fb497..577f659b2cc 100644 --- a/htdocs/core/ajax/price.php +++ b/htdocs/core/ajax/price.php @@ -22,10 +22,8 @@ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); require('../../main.inc.php'); diff --git a/htdocs/core/ajax/row.php b/htdocs/core/ajax/row.php index 71a5a0aac88..98f18df8a68 100644 --- a/htdocs/core/ajax/row.php +++ b/htdocs/core/ajax/row.php @@ -28,7 +28,6 @@ if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOREQUIREHOOK')) define('NOREQUIREHOOK','1'); // Disable "main.inc.php" hooks require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php'; @@ -63,7 +62,7 @@ if ((isset($_POST['roworder']) && ! empty($_POST['roworder'])) && (isset($_POST[ $row->table_element_line = $table_element_line; $row->fk_element = $fk_element; $row->id = $element_id; - $row->line_ajaxorder($newrowordertab); // This update field rank or position in table table_element_line + $row->line_ajaxorder($newrowordertab); // This update field rank or position in table row->table_element_line // Reorder line to have position of children lines sharing same counter than parent lines // This should be useless because there is no need to have children sharing same counter than parent, but well, it's cleaner into database. diff --git a/htdocs/core/ajax/saveinplace.php b/htdocs/core/ajax/saveinplace.php index 61c2dca675b..7070d1a8799 100644 --- a/htdocs/core/ajax/saveinplace.php +++ b/htdocs/core/ajax/saveinplace.php @@ -22,10 +22,8 @@ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php'; diff --git a/htdocs/core/ajax/security.php b/htdocs/core/ajax/security.php index cc7335618d0..fa1ce2103d4 100644 --- a/htdocs/core/ajax/security.php +++ b/htdocs/core/ajax/security.php @@ -27,7 +27,6 @@ if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); -if (! defined('NOREQUIREHOOK')) define('NOREQUIREHOOK','1'); require '../../main.inc.php'; diff --git a/htdocs/core/ajax/selectsearchbox.php b/htdocs/core/ajax/selectsearchbox.php index 4256d14f203..57483848c4e 100644 --- a/htdocs/core/ajax/selectsearchbox.php +++ b/htdocs/core/ajax/selectsearchbox.php @@ -27,10 +27,9 @@ if (! isset($usedbyinclude) || empty($usedbyinclude)) { if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal - //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); - if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); - if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); - if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); + if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); + if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); + if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); if (! defined('NOREDIRECTBYMAINTOLOGIN')) define('NOREDIRECTBYMAINTOLOGIN','1'); $res=@include '../../main.inc.php'; @@ -126,7 +125,7 @@ if (! empty($conf->ficheinter->enabled) && empty($conf->global->MAIN_SEARCHFORM_ // HR if (! empty($conf->user->enabled) && empty($conf->global->MAIN_SEARCHFORM_USER_DISABLED) && $user->rights->user->user->lire) { - $arrayresult['searchintouser']=array('position'=>200, 'shortcut'=>'U', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/index.php'.($search_boxvalue?'?sall='.urlencode($search_boxvalue):'')); + $arrayresult['searchintouser']=array('position'=>200, 'shortcut'=>'U', 'img'=>'object_user', 'label'=>$langs->trans("SearchIntoUsers", $search_boxvalue), 'text'=>img_picto('','object_user').' '.$langs->trans("SearchIntoUsers", $search_boxvalue), 'url'=>DOL_URL_ROOT.'/user/list.php'.($search_boxvalue?'?sall='.urlencode($search_boxvalue):'')); } if (! empty($conf->expensereport->enabled) && empty($conf->global->MAIN_SEARCHFORM_EXPENSEREPORT_DISABLED) && $user->rights->expensereport->lire) { diff --git a/htdocs/core/ajax/vatrates.php b/htdocs/core/ajax/vatrates.php index ac9691bfa25..3826e521d06 100644 --- a/htdocs/core/ajax/vatrates.php +++ b/htdocs/core/ajax/vatrates.php @@ -22,10 +22,7 @@ if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); -//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); -//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); -//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); require '../../main.inc.php'; diff --git a/htdocs/core/ajax/ziptown.php b/htdocs/core/ajax/ziptown.php index 9fa475039d9..2100d3d3600 100644 --- a/htdocs/core/ajax/ziptown.php +++ b/htdocs/core/ajax/ziptown.php @@ -120,6 +120,7 @@ if (! empty($_GET['zipcode']) || ! empty($_GET['town'])) $row_array['selectcountry_id'] = $row['fk_country']; $row_array['state_id'] = $row['fk_county']; + // TODO Use a cache here to avoid to make select_state in each pass (this make a SQL and lot of logs) $row_array['states'] = $formcompany->select_state('',$row['fk_country'],''); array_push($return_arr,$row_array); diff --git a/htdocs/core/boxes/box_clients.php b/htdocs/core/boxes/box_clients.php index a293b5166a2..7ab2de66a7b 100644 --- a/htdocs/core/boxes/box_clients.php +++ b/htdocs/core/boxes/box_clients.php @@ -87,7 +87,10 @@ class box_clients extends ModeleBoxes $sql.= ", s.client"; $sql.= ", s.code_fournisseur"; $sql.= ", s.fournisseur"; + $sql.= ", s.code_compta"; + $sql.= ", s.code_compta_fournisseur"; $sql.= ", s.logo"; + $sql.= ", s.email"; $sql.= ", s.datec, s.tms, s.status"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -114,9 +117,12 @@ class box_clients extends ModeleBoxes $thirdpartystatic->name = $objp->name; $thirdpartystatic->code_client = $objp->code_client; $thirdpartystatic->code_fournisseur = $objp->code_fournisseur; + $thirdpartystatic->code_compta = $objp->code_compta; + $thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur; $thirdpartystatic->client = $objp->client; $thirdpartystatic->fournisseur = $objp->fournisseur; $thirdpartystatic->logo = $objp->logo; + $thirdpartystatic->email = $objp->email; $this->info_box_contents[$line][] = array( 'td' => '', diff --git a/htdocs/core/boxes/box_contacts.php b/htdocs/core/boxes/box_contacts.php index a67d2c3ac02..a8dc7f1231d 100644 --- a/htdocs/core/boxes/box_contacts.php +++ b/htdocs/core/boxes/box_contacts.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2015 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2015 Frederic France + * Copyright (C) 2018 Josep Lluís Amador * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +21,7 @@ /** * \file htdocs/core/boxes/box_contacts.php - * \ingroup societes + * \ingroup contacts * \brief Module to show box of contacts */ @@ -57,7 +58,7 @@ class box_contacts extends ModeleBoxes $this->db=$db; - $this->hidden=! ($user->rights->societe->lire); + $this->hidden=! ($user->rights->societe->lire && $user->rights->societe->contact->lire); } /** @@ -75,114 +76,113 @@ class box_contacts extends ModeleBoxes $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedContacts",$max)); - if ($user->rights->societe->lire) + if ($user->rights->societe->lire && $user->rights->societe->contact->lire) { $sql = "SELECT sp.rowid as id, sp.lastname, sp.firstname, sp.civility as civility_id, sp.datec, sp.tms, sp.fk_soc, sp.statut as status"; $sql.= ", sp.address, sp.zip, sp.town, sp.phone, sp.phone_perso, sp.phone_mobile"; $sql.= ", s.nom as socname, s.name_alias"; - $sql.= ", s.client, s.fournisseur, s.code_client, s.code_fournisseur"; + $sql.= ", s.client, s.fournisseur, s.code_client, s.code_fournisseur"; $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON sp.fk_soc = s.rowid"; if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE sp.entity IN (".getEntity('societe').")"; + $sql.= " WHERE sp.entity IN (".getEntity('socpeople').")"; if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " AND sp.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($user->societe_id) $sql.= " AND sp.fk_soc = ".$user->societe_id; $sql.= " ORDER BY sp.tms DESC"; $sql.= $db->plimit($max, 0); $result = $db->query($sql); - if ($result) { + if ($result) { $num = $db->num_rows($result); $contactstatic=new Contact($db); $societestatic=new Societe($db); $line = 0; - while ($line < $num) - { + while ($line < $num) + { $objp = $db->fetch_object($result); $datec=$db->jdate($objp->datec); $datem=$db->jdate($objp->tms); - $contactstatic->id=$objp->id; + $contactstatic->id=$objp->id; $contactstatic->lastname=$objp->lastname; - $contactstatic->firstname=$objp->firstname; - $contactstatic->civility_id=$objp->civility_id; + $contactstatic->firstname=$objp->firstname; + $contactstatic->civility_id=$objp->civility_id; $contactstatic->statut=$objp->status; - $contactstatic->phone_pro = $objp->phone; - $contactstatic->phone_perso = $objp->phone_perso; - $contactstatic->phone_mobile = $objp->phone_mobile; - $contactstatic->address = $objp->address; - $contactstatic->zip = $objp->zip; - $contactstatic->town = $objp->town; + $contactstatic->phone_pro = $objp->phone; + $contactstatic->phone_perso = $objp->phone_perso; + $contactstatic->phone_mobile = $objp->phone_mobile; + $contactstatic->address = $objp->address; + $contactstatic->zip = $objp->zip; + $contactstatic->town = $objp->town; $societestatic->id = $objp->fk_soc; - $societestatic->name = $objp->socname; - $societestatic->name_alias = $objp->name_alias; - $societestatic->code_client = $objp->code_client; - $societestatic->code_fournisseur = $objp->code_fournisseur; - $societestatic->client = $objp->client; - $societestatic->fournisseur = $objp->fournisseur; + $societestatic->name = $objp->socname; + $societestatic->name_alias = $objp->name_alias; + $societestatic->code_client = $objp->code_client; + $societestatic->code_fournisseur = $objp->code_fournisseur; + $societestatic->client = $objp->client; + $societestatic->fournisseur = $objp->fournisseur; - $this->info_box_contents[$line][] = array( - 'td' => '', - 'text' => $contactstatic->getNomUrl(1), - 'asis' => 1, - ); + $this->info_box_contents[$line][] = array( + 'td' => '', + 'text' => $contactstatic->getNomUrl(1), + 'asis' => 1, + ); - $this->info_box_contents[$line][] = array( - 'td' => '', - 'text' => ($objp->fk_soc > 0 ? $societestatic->getNomUrl(1) : ''), - 'asis' => 1, - ); + $this->info_box_contents[$line][] = array( + 'td' => '', + 'text' => ($objp->fk_soc > 0 ? $societestatic->getNomUrl(1) : ''), + 'asis' => 1, + ); - $this->info_box_contents[$line][] = array( - 'td' => 'class="right"', - 'text' => dol_print_date($datem, "day"), - ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => dol_print_date($datem, "day"), + ); - $this->info_box_contents[$line][] = array( - 'td' => 'align="right" class="nowrap" width="18"', - 'text' => $contactstatic->getLibStatut(3), - 'asis'=>1, - ); + $this->info_box_contents[$line][] = array( + 'td' => 'align="right" class="nowrap" width="18"', + 'text' => $contactstatic->getLibStatut(3), + 'asis'=>1, + ); - $line++; - } + $line++; + } - if ($num==0) - $this->info_box_contents[$line][0] = array( - 'td' => 'align="center"', - 'text'=>$langs->trans("NoRecordedContacts"), - ); + if ($num==0) + $this->info_box_contents[$line][0] = array( + 'td' => 'align="center"', + 'text'=>$langs->trans("NoRecordedContacts"), + ); - $db->free($result); - } else { - $this->info_box_contents[0][0] = array( - 'td' => '', - 'maxlength'=>500, - 'text' => ($db->error().' sql='.$sql), - ); - } - } else { - $this->info_box_contents[0][0] = array( - 'td' => 'align="left" class="nohover opacitymedium"', - 'text' => $langs->trans("ReadPermissionNotAllowed") - ); - } - - } + $db->free($result); + } else { + $this->info_box_contents[0][0] = array( + 'td' => '', + 'maxlength'=>500, + 'text' => ($db->error().' sql='.$sql), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'align="left" class="nohover opacitymedium"', + 'text' => $langs->trans("ReadPermissionNotAllowed") + ); + } + } /** * Method to show box * - * @param array $head Array with properties of box title - * @param array $contents Array with properties of box lines - * @param int $nooutput No print, only return string + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string * @return string */ - function showBox($head = null, $contents = null, $nooutput=0) - { + function showBox($head = null, $contents = null, $nooutput=0) + { return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); } diff --git a/htdocs/core/boxes/box_graph_invoices_permonth.php b/htdocs/core/boxes/box_graph_invoices_permonth.php index 8b5bfbc817d..abbdc7b7c71 100644 --- a/htdocs/core/boxes/box_graph_invoices_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_permonth.php @@ -91,6 +91,8 @@ class box_graph_invoices_permonth extends ModeleBoxes if ($user->rights->facture->lire) { + $mesg = ''; + $param_year='DOLUSERCOOKIE_box_'.$this->boxcode.'_year'; $param_shownb='DOLUSERCOOKIE_box_'.$this->boxcode.'_shownb'; $param_showtot='DOLUSERCOOKIE_box_'.$this->boxcode.'_showtot'; @@ -220,13 +222,14 @@ class box_graph_invoices_permonth extends ModeleBoxes $stringtoshow.='
'; // hideobject is to start hidden $stringtoshow.='
'; $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.=''; $stringtoshow.=' '.$langs->trans("NumberOfBillsByMonth"); $stringtoshow.='   '; $stringtoshow.=' '.$langs->trans("AmountOfBillsByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.='
'; if ($shownb && $showtot) @@ -246,13 +249,11 @@ class box_graph_invoices_permonth extends ModeleBoxes $stringtoshow.='
'; $stringtoshow.='
'; } - $this->info_box_contents[0][0] = array('td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); } else { - $this->info_box_contents[0][0] = array( 'td' => 'align="left" class="nohover"', - 'maxlength'=>500, - 'text' => $mesg); + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="left" class="nohover"', 'maxlength'=>500, 'text' => $mesg); } } diff --git a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php index 436343a56dc..53d9ce08059 100644 --- a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php @@ -219,13 +219,14 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes $stringtoshow.='
'; // hideobject is to start hidden $stringtoshow.='
'; $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.=''; $stringtoshow.=' '.$langs->trans("NumberOfBillsByMonth"); $stringtoshow.='   '; $stringtoshow.=' '.$langs->trans("AmountOfBillsByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.='
'; if ($shownb && $showtot) @@ -245,11 +246,11 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes $stringtoshow.='
'; $stringtoshow.=''; } - $this->info_box_contents[0][0] = array('td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"','td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); } else { - $this->info_box_contents[0][0] = array( 'td' => 'align="left" class="nohover"', + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="left" class="nohover"', 'maxlength'=>500, 'text' => $mesg); } diff --git a/htdocs/core/boxes/box_graph_orders_permonth.php b/htdocs/core/boxes/box_graph_orders_permonth.php index 7e60e00a2fc..05a0ff498ec 100644 --- a/htdocs/core/boxes/box_graph_orders_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_permonth.php @@ -218,13 +218,14 @@ class box_graph_orders_permonth extends ModeleBoxes $stringtoshow.='
'; // hideobject is to start hidden $stringtoshow.='
'; $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.=''; $stringtoshow.=' '.$langs->trans("NumberOfOrdersByMonth"); $stringtoshow.='   '; $stringtoshow.=' '.$langs->trans("AmountOfOrdersByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.='
'; if ($shownb && $showtot) @@ -244,11 +245,11 @@ class box_graph_orders_permonth extends ModeleBoxes $stringtoshow.=''; $stringtoshow.=''; } - $this->info_box_contents[0][0] = array('td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); } else { - $this->info_box_contents[0][0] = array( 'td' => 'align="left" class="nohover"', + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="left" class="nohover"', 'maxlength'=>500, 'text' => $mesg); } diff --git a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php index 6f8ebf39001..e88ed46be72 100644 --- a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php @@ -217,13 +217,14 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $stringtoshow.='
'; // hideobject is to start hidden $stringtoshow.='
'; $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.=''; $stringtoshow.=' '.$langs->trans("NumberOfOrdersByMonth"); $stringtoshow.='   '; $stringtoshow.=' '.$langs->trans("AmountOfOrdersByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.='
'; if ($shownb && $showtot) @@ -243,11 +244,11 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $stringtoshow.=''; $stringtoshow.=''; } - $this->info_box_contents[0][0] = array('td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); } else { - $this->info_box_contents[0][0] = array( 'td' => 'align="left" class="nohover"', + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="left" class="nohover"', 'maxlength'=>500, 'text' => $mesg); } diff --git a/htdocs/core/boxes/box_graph_product_distribution.php b/htdocs/core/boxes/box_graph_product_distribution.php index bac56d8006b..39a7a3984d2 100644 --- a/htdocs/core/boxes/box_graph_product_distribution.php +++ b/htdocs/core/boxes/box_graph_product_distribution.php @@ -338,6 +338,7 @@ class box_graph_product_distribution extends ModeleBoxes $stringtoshow.='
'; // hideobject is to start hidden $stringtoshow.='
'; $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.=''; if (! empty($conf->facture->enabled) || ! empty($user->rights->facture->lire)) { @@ -355,7 +356,7 @@ class box_graph_product_distribution extends ModeleBoxes } $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.='
'; @@ -386,7 +387,7 @@ class box_graph_product_distribution extends ModeleBoxes $stringtoshow.=$px3->show(); $stringtoshow.=''; } - $this->info_box_contents[0][0] = array('td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); } else { diff --git a/htdocs/core/boxes/box_graph_propales_permonth.php b/htdocs/core/boxes/box_graph_propales_permonth.php index 690df3d41fa..4f05e186b43 100644 --- a/htdocs/core/boxes/box_graph_propales_permonth.php +++ b/htdocs/core/boxes/box_graph_propales_permonth.php @@ -71,6 +71,8 @@ class box_graph_propales_permonth extends ModeleBoxes //include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; //$propalstatic=new Propal($db); + $langs->load("propal"); + $text = $langs->trans("BoxProposalsPerMonth",$max); $this->info_box_head = array( 'text' => $text, @@ -219,13 +221,14 @@ class box_graph_propales_permonth extends ModeleBoxes $stringtoshow.='
'; // hideobject is to start hidden $stringtoshow.='
'; $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.=''; $stringtoshow.=' '.$langs->trans("NumberOfProposalsByMonth"); $stringtoshow.='   '; $stringtoshow.=' '.$langs->trans("AmountOfProposalsByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.='
'; if ($shownb && $showtot) @@ -245,11 +248,11 @@ class box_graph_propales_permonth extends ModeleBoxes $stringtoshow.=''; $stringtoshow.=''; } - $this->info_box_contents[0][0] = array('td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="center" class="nohover"','textnoformat'=>$stringtoshow); } else { - $this->info_box_contents[0][0] = array( 'td' => 'align="left" class="nohover"', + $this->info_box_contents[0][0] = array('tr'=>'class="oddeven nohover"', 'td' => 'align="left" class="nohover"', 'maxlength'=>500, 'text' => $mesg); } diff --git a/htdocs/core/boxes/box_last_modified_ticket.php b/htdocs/core/boxes/box_last_modified_ticket.php new file mode 100644 index 00000000000..a0613d58f3e --- /dev/null +++ b/htdocs/core/boxes/box_last_modified_ticket.php @@ -0,0 +1,189 @@ + + * 2016 Christophe Battarel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file core/boxes/box_last_modified_ticket.php + * \ingroup ticket + * \brief This box shows latest modified tickets + */ +require_once DOL_DOCUMENT_ROOT . "/core/boxes/modules_boxes.php"; + +/** + * Class to manage the box + */ +class box_last_modified_ticket extends ModeleBoxes +{ + + public $boxcode = "box_last_modified_ticket"; + public $boximg = "ticket"; + public $boxlabel; + public $depends = array("ticket"); + public $db; + public $param; + public $info_box_head = array(); + public $info_box_contents = array(); + + /** + * Constructor + */ + public function __construct() + { + global $langs; + $langs->load("boxes"); + + $this->boxlabel = $langs->transnoentitiesnoconv("BoxLastModifiedTicket"); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs, $db; + + $this->max = $max; + + dol_include_once("/ticket/class/ticket.class.php"); + + $text = $langs->trans("BoxLastModifiedTicketDescription", $max); + $this->info_box_head = array( + 'text' => $text, + 'limit' => dol_strlen($text) + ); + + $this->info_box_contents[0][0] = array('td' => 'align="left"', + 'text' => $langs->trans("BoxLastModifiedTicketContent")); + + if ($user->rights->ticket->read) { + $sql = "SELECT t.rowid as id, t.ref, t.track_id, t.fk_soc, t.fk_user_create, t.fk_user_assign, t.subject, t.message, t.fk_statut, t.type_code, t.category_code, t.severity_code, t.datec, t.date_read, t.date_close, t.origin_email "; + $sql.= ", type.label as type_label, category.label as category_label, severity.label as severity_label"; + $sql.= ", s.nom as company_name"; + $sql.= " FROM ".MAIN_DB_PREFIX."ticket as t"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_type as type ON type.code=t.type_code"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_category as category ON category.code=t.category_code"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_ticket_severity as severity ON severity.code=t.severity_code"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=t.fk_soc"; + + $sql.= " WHERE t.entity = ".$conf->entity; + // $sql.= " AND e.rowid = er.fk_event"; + //if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " WHERE s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + if ($user->societe_id) { + $sql.= " AND t.fk_soc= ".$user->societe_id; + } + + $sql.= " ORDER BY t.tms DESC, t.rowid DESC "; + $sql.= $db->plimit($max, 0); + + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $now=gmmktime(); + + $i = 0; + + while ($i < $num) { + $objp = $db->fetch_object($resql); + $datec=$db->jdate($objp->datec); + $dateterm=$db->jdate($objp->fin_validite); + $dateclose=$db->jdate($objp->date_cloture); + $late = ''; + + $ticket = new Ticket($this->db); + + + $r=0; + + // Picto + $this->info_box_contents[$i][0] = array( + 'td' => 'align="left" width="16"', + 'logo' => $this->boximg, + 'url' => dol_buildpath("/ticket/card.php?track_id=".$objp->track_id, 1)); + $r++; + + // Id + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="left"', + 'text' => $objp->ref, + 'url' => dol_buildpath("/ticket/card.php?track_id=".$objp->track_id, 1)); + $r++; + + // Subject + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="left"', + 'text' => $objp->subject, // Some event have no ref + 'url' => dol_buildpath("/ticket/card.php?track_id=".$objp->track_id, 1)); + $r++; + + // Customer + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="left"', + 'logo' => ($objp->fk_soc>0?'company':''), + 'text' => ($objp->company_name?$objp->company_name:$objp->origin_email), + 'url' => ($objp->fk_soc>0?DOL_URL_ROOT."/comm/card.php?socid=".$objp->fk_soc:'') + ); + $r++; + + + // Date creation + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="right"', + 'text' => dol_print_date($db->idate($objp->datec), 'dayhour') + ); + $r++; + + // Statut + $ticketstat = new Ticket($this->db); + $ticketstat->fk_statut = $objp->fk_statut; + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="right"', + 'text' => $ticketstat->getLibStatut(3) + ); + $r++; + + $i++; + } + + if ($num==0) { + $this->info_box_contents[$i][0] = array('td' => 'align="center"','text'=>$langs->trans("BoxLastModifiedTicketNoRecordedTickets")); + } + } else { + dol_print_error($db); + } + } else { + $this->info_box_contents[0][0] = array('td' => 'align="left"', + 'text' => $langs->trans("ReadPermissionNotAllowed")); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + function showBox($head = null, $contents = null, $nooutput=0) + { + parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_last_ticket.php b/htdocs/core/boxes/box_last_ticket.php new file mode 100644 index 00000000000..2dfa71af904 --- /dev/null +++ b/htdocs/core/boxes/box_last_ticket.php @@ -0,0 +1,189 @@ + + * 2016 Christophe Battarel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file core/boxes/box_ticket_latest.php + * \ingroup ticket + * \brief This box shows latest created tickets + */ +require_once DOL_DOCUMENT_ROOT . "/core/boxes/modules_boxes.php"; + +/** + * Class to manage the box + */ +class box_last_ticket extends ModeleBoxes +{ + + public $boxcode = "box_last_ticket"; + public $boximg = "ticket"; + public $boxlabel; + public $depends = array("ticket"); + public $db; + public $param; + public $info_box_head = array(); + public $info_box_contents = array(); + + /** + * Constructor + */ + public function __construct() + { + global $langs; + $langs->load("boxes"); + + $this->boxlabel = $langs->transnoentitiesnoconv("BoxLastTicket"); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs, $db; + + $this->max = $max; + + dol_include_once("/ticket/class/ticket.class.php"); + + $text = $langs->trans("BoxLastTicketDescription", $max); + $this->info_box_head = array( + 'text' => $text, + 'limit' => dol_strlen($text), + ); + + $this->info_box_contents[0][0] = array('td' => 'align="left"', + 'text' => $langs->trans("BoxLastTicketContent")); + + if ($user->rights->ticket->read) { + $sql = "SELECT t.rowid as id, t.ref, t.track_id, t.fk_soc, t.fk_user_create, t.fk_user_assign, t.subject, t.message, t.fk_statut, t.type_code, t.category_code, t.severity_code, t.datec, t.date_read, t.date_close, t.origin_email "; + $sql .= ", type.label as type_label, category.label as category_label, severity.label as severity_label"; + $sql .= ", s.nom as company_name"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticket as t"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticket_type as type ON type.code=t.type_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticket_category as category ON category.code=t.category_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_ticket_severity as severity ON severity.code=t.severity_code"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid=t.fk_soc"; + + $sql .= " WHERE t.entity = " . $conf->entity; + // $sql.= " AND e.rowid = er.fk_event"; + //if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " WHERE s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + if ($user->societe_id) { + $sql .= " AND t.fk_soc= " . $user->societe_id; + } + + //$sql.= " AND t.fk_statut > 9"; + + $sql .= " ORDER BY t.datec DESC, t.rowid DESC "; + $sql .= $db->plimit($max, 0); + + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $now = gmmktime(); + + $i = 0; + + while ($i < $num) { + $objp = $db->fetch_object($resql); + $datec = $db->jdate($objp->datec); + $dateterm = $db->jdate($objp->fin_validite); + $dateclose = $db->jdate($objp->date_cloture); + $late = ''; + + $ticket = new Ticket($this->db); + + $r = 0; + + // Picto + $this->info_box_contents[$i][0] = array( + 'td' => 'align="left" width="16"', + 'logo' => $this->boximg, + 'url' => dol_buildpath("/ticket/card.php?track_id=" . $objp->track_id, 1)); + $r++; + + // Id + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="left"', + 'text' => $objp->ref, + 'url' => dol_buildpath("/ticket/card.php?track_id=" . $objp->track_id, 1)); + $r++; + + // Subject + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="left"', + 'text' => $objp->subject, // Some event have no ref + 'url' => dol_buildpath("/ticket/card.php?track_id=" . $objp->track_id, 1)); + $r++; + + // Customer + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="left"', + 'logo' => ($objp->fk_soc > 0 ? 'company' : ''), + 'text' => ($objp->company_name ? $objp->company_name : $objp->origin_email), + 'url' => ($objp->fk_soc > 0 ? DOL_URL_ROOT . "/comm/card.php?socid=" . $objp->fk_soc : ''), + ); + $r++; + + // Date creation + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="right"', + 'text' => dol_print_date($db->idate($objp->datec), 'dayhour'), + ); + $r++; + + // Statut + $ticketstat = new Ticket($this->db); + $ticketstat->fk_statut = $objp->fk_statut; + $this->info_box_contents[$i][$r] = array( + 'td' => 'align="right"', + 'text' => $ticketstat->getLibStatut(3), + ); + $r++; + + $i++; + } + + if ($num == 0) { + $this->info_box_contents[$i][0] = array('td' => 'align="center"', 'text' => $langs->trans("BoxLastTicketNoRecordedTickets")); + } + } else { + dol_print_error($db); + } + } else { + $this->info_box_contents[0][0] = array('td' => 'align="left"', + 'text' => $langs->trans("ReadPermissionNotAllowed")); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + function showBox($head = null, $contents = null, $nooutput=0) + { + parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index 74f0ffc9d9d..61af58a4b8b 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -261,17 +261,17 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" { $sublink=''; if (! empty($head['sublink'])) $sublink.= ''; - if (! empty($head['subpicto'])) $sublink.= img_picto($head['subtext'], $head['subpicto'], 'class="'.(empty($head['subclass'])?'':$head['subclass']).'" id="idsubimg'.$this->boxcode.'"'); + if (! empty($head['subpicto'])) $sublink.= img_picto($head['subtext'], $head['subpicto'], 'class="opacitymedium '.(empty($head['subclass'])?'':$head['subclass']).'" id="idsubimg'.$this->boxcode.'"'); if (! empty($head['sublink'])) $sublink.= ''; $out.= ''; $out.=$sublink; // The image must have the class 'boxhandle' beause it's value used in DOM draggable objects to define the area used to catch the full object - $out.= img_picto($langs->trans("MoveBox",$this->box_id),'grip_title','class="boxhandle hideonsmartphone cursormove"'); - $out.= img_picto($langs->trans("CloseBox",$this->box_id),'close_title','class="boxclose cursorpointer" rel="x:y" id="imgclose'.$this->box_id.'"'); + $out.= img_picto($langs->trans("MoveBox",$this->box_id),'grip_title','class="opacitymedium boxhandle hideonsmartphone cursormove"'); + $out.= img_picto($langs->trans("CloseBox",$this->box_id),'close_title','class="opacitymedium boxclose cursorpointer" rel="x:y" id="imgclose'.$this->box_id.'"'); $label=$head['text']; //if (! empty($head['graph'])) $label.=' ('.$langs->trans("Graph").')'; - if (! empty($head['graph'])) $label.=' '; + if (! empty($head['graph'])) $label.=' '; $out.= ''; $out.= ''; } diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index fe8ca1f2352..f5382a91550 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -80,14 +80,16 @@ class CMailFile var $atleastoneimage=0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used). var $html_images=array(); var $images_encoded=array(); - var $image_types = array('gif' => 'image/gif', - 'jpg' => 'image/jpeg', - 'jpeg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'bmp' => 'image/bmp', - 'png' => 'image/png', - 'tif' => 'image/tiff', - 'tiff' => 'image/tiff'); + var $image_types = array( + 'gif' => 'image/gif', + 'jpg' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'bmp' => 'image/bmp', + 'png' => 'image/png', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + ); /** @@ -109,13 +111,16 @@ class CMailFile * @param string $trackid Tracking string (contains type and id of related element) * @param string $moreinheader More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'phpmail' and 'smtps' for the moment) * @param string $sendcontext 'standard', 'emailing', ... (used to define with sending mode and parameters to use) + * @param string $replyto Reply-to email (will be set to same value than From by default if not provided) */ - function __construct($subject,$to,$from,$msg,$filename_list=array(),$mimetype_list=array(),$mimefilename_list=array(),$addr_cc="",$addr_bcc="",$deliveryreceipt=0,$msgishtml=0,$errors_to='',$css='',$trackid='',$moreinheader='',$sendcontext='standard') + function __construct($subject,$to,$from,$msg,$filename_list=array(),$mimetype_list=array(),$mimefilename_list=array(),$addr_cc="",$addr_bcc="",$deliveryreceipt=0,$msgishtml=0,$errors_to='',$css='',$trackid='',$moreinheader='',$sendcontext='standard',$replyto='') { global $conf, $dolibarr_main_data_root; $this->sendcontext = $sendcontext; + if (empty($replyto)) $replyto=$from; + // Define this->sendmode $this->sendmode = ''; if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') @@ -208,12 +213,15 @@ class CMailFile } // Define if there is at least one file - foreach ($filename_list as $i => $val) + if (is_array($filename_list)) { - if ($filename_list[$i]) + foreach ($filename_list as $i => $val) { - $this->atleastonefile=1; - dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG); + if ($filename_list[$i]) + { + $this->atleastonefile=1; + dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG); + } } } @@ -234,7 +242,7 @@ class CMailFile // Define smtp_headers $this->subject = $subject; $this->addr_from = $from; - $this->reply_to = $from; // Set this property after constructor if you want to use another value + $this->reply_to = $replyto; $this->errors_to = $errors_to; $this->addr_to = $to; $this->addr_cc = $addr_cc; @@ -293,7 +301,7 @@ class CMailFile $smtps->setTO($this->getValidAddress($to,0,1)); $smtps->setFrom($this->getValidAddress($from,0,1)); $smtps->setTrackId($trackid); - $smtps->setReplyTo($this->getValidAddress($from,0,1)); // Set property with this->smtps->setReplyTo after constructor if you want to use another value than the From + $smtps->setReplyTo($this->getValidAddress($replyto,0,1)); if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader); @@ -335,71 +343,39 @@ class CMailFile $this->smtps=$smtps; } - // TODO not stable, in progress - else if ($this->sendmode == 'phpmailer') - { - // Use PHPMailer library - // ------------------------------------------ - - require_once DOL_DOCUMENT_ROOT.'/includes/phpmailer/class.phpmailer.php'; - $this->phpmailer = new PHPMailer(); - $this->phpmailer->CharSet = $conf->file->character_set_client; - - $this->phpmailer->Subject($this->encodetorfc2822($subject)); - $this->phpmailer->setTO($this->getValidAddress($to,0,1)); - $this->phpmailer->SetFrom($this->getValidAddress($from,0,1)); - $this->phpmailer->SetReplyTo($this->getValidAddress($from,0,1)); // Set property with this->phpmailer->setReplyTo after constructor if you want to use another value than the From - // TODO Add trackid into smtp header - // TODO if (! empty($moreinheader)) ... - - if (! empty($this->html)) - { - if (!empty($css)) - { - $this->css = $css; - $this->buildCSS(); - } - $msg = $this->html; - $msg = $this->checkIfHTML($msg); - } - - if ($this->msgishtml) $smtps->setBodyContent($msg,'html'); - else $smtps->setBodyContent($msg,'plain'); - - if ($this->atleastoneimage) - { - foreach ($this->images_encoded as $img) - { - $smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']); - } - } - - if ($this->atleastonefile) - { - foreach ($filename_list as $i => $val) - { - $content=file_get_contents($filename_list[$i]); - $smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]); - } - } - - $this->phpmailer->setCC($addr_cc); - $this->phpmailer->setBCC($addr_bcc); - $this->phpmailer->setErrorsTo($errors_to); - $this->phpmailer->setDeliveryReceipt($deliveryreceipt); - } else if ($this->sendmode == 'swiftmailer') { // Use Swift Mailer library // ------------------------------------------ - $host = dol_getprefix('email'); + $host = dol_getprefix('email'); + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php'; + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php'; + + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/InputByteStream.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signer.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php'; + //require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/SignedMessage.php'; require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Create the message - $this->message = Swift_Message::newInstance(); - - // Adding a trackid header to a message + //$this->message = Swift_Message::newInstance(); + $this->message = new Swift_Message(); + //$this->message = new Swift_SignedMessage(); + // Adding a trackid header to a message $headers = $this->message->getHeaders(); $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid); $headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host; @@ -413,12 +389,30 @@ class CMailFile // Set the From address with an associative array //$this->message->setFrom(array('john@doe.com' => 'John Doe')); - if (! empty($from)) $this->message->setFrom($this->getArrayAddress($from)); + if (! empty($from)) { + try { + $this->message->setFrom($this->getArrayAddress($from)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } // Set the To addresses with an associative array - if (! empty($to)) $this->message->setTo($this->getArrayAddress($to)); + if (! empty($to)) { + try { + $this->message->setTo($this->getArrayAddress($to)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } - if (! empty($from)) $this->message->SetReplyTo($this->getArrayAddress($from)); + if (! empty($replyto)) { + try { + $this->message->SetReplyTo($this->getArrayAddress($replyto)); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } $this->message->setCharSet($conf->file->character_set_client); @@ -449,11 +443,11 @@ class CMailFile if ($this->msgishtml) { $this->message->setBody($msg,'text/html'); // And optionally an alternative body - //$this->message->addPart('Here is the message itself', 'text/plain'); + $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain'); } else { $this->message->setBody($msg,'text/plain'); // And optionally an alternative body - //$this->message->addPart('Here is the message itself', 'text/html'); + $this->message->addPart($msg, 'text/html'); } if ($this->atleastonefile) @@ -482,7 +476,7 @@ class CMailFile /** - * Send mail that was prepared by constructor + * Send mail that was prepared by constructor. * * @return boolean True if mail sent, false otherwise */ @@ -491,23 +485,29 @@ class CMailFile global $conf,$db,$langs; $errorlevel=error_reporting(); - error_reporting($errorlevel ^ E_WARNING); // Desactive warnings + //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings $res=false; - if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) + if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) { require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; $hookmanager = new HookManager($db); - $hookmanager->initHooks(array('maildao')); - $reshook = $hookmanager->executeHooks('doactions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if (! empty($reshook)) + $hookmanager->initHooks(array('mail')); + + $parameters=array(); $action=''; + $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) { - $this->error = "Error in hook maildao doactions " . $reshook; + $this->error = "Error in hook maildao sendMail " . $reshook; dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR); return $reshook; } + if ($reshook == 1) // Hook replace standard code + { + return true; + } // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10; @@ -558,6 +558,12 @@ class CMailFile $keyforstarttls ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING'; } + if(!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) { + $this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO; + $this->addr_cc = ''; + $this->addr_bcc = ''; + } + // Action according to choosed sending method if ($this->sendmode == 'mail') { @@ -578,13 +584,22 @@ class CMailFile if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver); if (! empty($conf->global->$keyforsmtpport)) ini_set('smtp_port',$conf->global->$keyforsmtpport); + $res=true; + if ($res && ! $this->subject) + { + $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
Subject is empty"; + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); + $res=false; + } $dest=$this->getValidAddress($this->addr_to,2); - if (! $dest) + if ($res && ! $dest) { $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); + $res=false; } - else + + if ($res) { $additionnalparam = ''; // By default if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) @@ -643,6 +658,12 @@ class CMailFile } else if ($this->sendmode == 'smtps') { + if (! is_object($this->smtps)) + { + $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Constructor of object CMailFile was not initialized without errors."; + dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); + return false; + } // Use SMTPS library // ------------------------------------------ @@ -678,14 +699,14 @@ class CMailFile $res=true; $from=$this->smtps->getFrom('org'); - if (! $from) + if ($res && ! $from) { $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Sender address '$from' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res=false; } $dest=$this->smtps->getTo(); - if (! $dest) + if ($res && ! $dest) { $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); @@ -722,21 +743,30 @@ class CMailFile if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport=ini_get('smtp_port'); // If we use SSL/TLS - $server=$conf->global->$keyforsmtpserver; - $secure=''; + $server = $conf->global->$keyforsmtpserver; + $secure = ''; if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl'; if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls'; - $this->transport = Swift_SmtpTransport::newInstance($server, $conf->global->$keyforsmtpport, $secure); + $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure); if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); //$smtps->_msgReplyTo = 'reply@web.com'; // Create the Mailer using your created Transport - $this->mailer = Swift_Mailer::newInstance($this->transport); + $this->mailer = new Swift_Mailer($this->transport); - if (! empty($conf->global->MAIN_MAIL_DEBUG)) { + // DKIM SIGN + if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { + $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; + $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; + $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; + $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector); + $this->message->attachSigner($signer->ignoreHeader('Return-Path')); + } + + if (! empty($conf->global->MAIN_MAIL_DEBUG)) { // To use the ArrayLogger $this->logger = new Swift_Plugins_Loggers_ArrayLogger(); // Or to use the Echo Logger @@ -752,22 +782,28 @@ class CMailFile if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); $res = true; - if (! empty($this->error) && ! $result) { + if (! empty($this->error) || ! $result) { dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res=false; - } else { - $this->error = sprintf ("Sent %d messages\n", $result); } } else { - // Send mail method not correctly defined // -------------------------------------- return 'Bad value for sendmode'; } + $parameters=array(); $action=''; + $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) + { + $this->error = "Error in hook maildao sendMailAfter " . $reshook; + dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR); + + return $reshook; + } } else { @@ -1032,7 +1068,9 @@ class CMailFile $strContentAltText = ''; if ($this->msgishtml) { - $strContentAltText = html_entity_decode(strip_tags($strContent)); + // Similar code to forge a text from html is also in CMailFile.class.php + $strContentAltText = preg_replace("/]*>/"," ", $strContent); + $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); $strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n")); // Check if html header already in message, if not complete the message diff --git a/htdocs/core/class/antivir.class.php b/htdocs/core/class/antivir.class.php index b5f4f0e5539..1c3ea5a07b6 100644 --- a/htdocs/core/class/antivir.class.php +++ b/htdocs/core/class/antivir.class.php @@ -62,7 +62,7 @@ class AntiVir if (preg_match('/\.virus$/i', $file)) { - $this->errors='File has an extension saying file is a virus'; + $this->errors[] = 'File has an extension saying file is a virus'; return -97; } diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index e4cc748f4f2..e944467ca27 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -44,7 +44,6 @@ abstract class CommonDocGenerator */ public function __construct($db) { $this->db = $db; - return 1; } @@ -203,7 +202,7 @@ abstract class CommonDocGenerator require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label('societe',true); - $object->fetch_optionals($object->id,$extralabels); + $object->fetch_optionals(); foreach($extrafields->attribute_label as $key=>$label) { @@ -274,7 +273,7 @@ abstract class CommonDocGenerator require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label('socpeople', true); - $object->fetch_optionals($object->id, $extralabels); + $object->fetch_optionals(); foreach($extrafields->attribute_label as $key => $label) { @@ -316,6 +315,14 @@ abstract class CommonDocGenerator 'current_server_datehour_locale'=>dol_print_date($now,'dayhour','tzserver',$outputlangs), ); + + foreach($conf->global as $key => $val) + { + if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****'; + else $newval = $val; + $array_other['__['.$key.']__'] = $newval; + } + return $array_other; } @@ -345,17 +352,19 @@ abstract class CommonDocGenerator $sumcreditnote = $object->getSumCreditNotesUsed(); } + $date = ($object->element == 'contrat' ? $object->date_contrat : $object->date); + $resarray=array( $array_key.'_id'=>$object->id, $array_key.'_ref'=>$object->ref, $array_key.'_ref_ext'=>$object->ref_ext, - $array_key.'_ref_customer'=>$object->ref_client, - $array_key.'_ref_supplier'=>(! empty($object->ref_fournisseur)?$object->ref_fournisseur:''), + $array_key.'_ref_customer'=>(! empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)), + $array_key.'_ref_supplier'=>(! empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)), $array_key.'_source_invoice_ref'=>$invoice_source->ref, // Dates - $array_key.'_hour'=>dol_print_date($object->date,'hour'), - $array_key.'_date'=>dol_print_date($object->date,'day'), - $array_key.'_date_rfc'=>dol_print_date($object->date,'dayrfc'), + $array_key.'_hour'=>dol_print_date($date,'hour'), + $array_key.'_date'=>dol_print_date($date,'day'), + $array_key.'_date_rfc'=>dol_print_date($date,'dayrfc'), $array_key.'_date_limit'=>(! empty($object->date_lim_reglement)?dol_print_date($object->date_lim_reglement,'day'):''), $array_key.'_date_end'=>(! empty($object->fin_validite)?dol_print_date($object->fin_validite,'day'):''), $array_key.'_date_creation'=>dol_print_date($object->date_creation,'day'), @@ -425,7 +434,7 @@ abstract class CommonDocGenerator { $object->fetch_projet(); } - + $resarray[$array_key.'_project_ref'] = $object->project->ref; $resarray[$array_key.'_project_title'] = $object->project->title; $resarray[$array_key.'_project_description'] = $object->project->description; @@ -457,7 +466,7 @@ abstract class CommonDocGenerator require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true); - $object->fetch_optionals($object->id,$extralabels); + $object->fetch_optionals(); $resarray = $this->fill_substitutionarray_with_extrafields($object,$resarray,$extrafields,$array_key,$outputlangs); } @@ -510,7 +519,7 @@ abstract class CommonDocGenerator 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), ); - + // Units if ($conf->global->PRODUCT_USE_UNITS) { @@ -524,10 +533,19 @@ abstract class CommonDocGenerator require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true); - $line->fetch_optionals($line->rowid,$extralabels); + $line->fetch_optionals(); $resarray = $this->fill_substitutionarray_with_extrafields($line,$resarray,$extrafields,$array_key=$array_key,$outputlangs); + // Load product data optional fields to the line -> enables to use "line_options_{extrafield}" + if (isset($line->fk_product) && $line->fk_product > 0) + { + $tmpproduct = new Product($this->db); + $result = $tmpproduct->fetch($line->fk_product); + foreach($tmpproduct->array_options as $key=>$label) + $resarray["line_".$key] = $label; + } + return $resarray; } @@ -578,15 +596,16 @@ abstract class CommonDocGenerator } // Retrieve extrafields - if(is_array($object->array_options) && count($object->array_options)) + if (is_array($object->array_options) && count($object->array_options)) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label('expedition',true); - $object->fetch_optionals($object->id,$extralabels); + $object->fetch_optionals(); $array_shipment = $this->fill_substitutionarray_with_extrafields($object,$array_shipment,$extrafields,$array_key,$outputlangs); } + return $array_shipment; } @@ -594,11 +613,11 @@ abstract class CommonDocGenerator /** * Define array with couple substitution key => substitution value * - * @param array $line Array of lines + * @param ExpeditionLigne $line Object line * @param Translate $outputlangs Lang object to use for output * @return array Substitution array */ - function get_substitutionarray_shipment_lines($line,$outputlangs) + function get_substitutionarray_shipment_lines($line, $outputlangs) { global $conf; dol_include_once('/core/lib/product.lib.php'); @@ -629,7 +648,7 @@ abstract class CommonDocGenerator require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey, true); - $line->fetch_optionals($line->rowid, $extralabels); + $line->fetch_optionals(); $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index af9d694e5e6..9bab103d2e4 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -180,12 +180,6 @@ abstract class CommonInvoice extends CommonObject */ function getSumCreditNotesUsed($multicurrency=0) { - if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') - { - // TODO - return 0; - } - require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discountstatic=new DiscountAbsolute($this->db); @@ -602,9 +596,11 @@ abstract class CommonInvoice extends CommonObject $sqltemp = 'SELECT c.type_cdr,c.nbjour,c.decalage'; $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c'; - $sqltemp.= " WHERE c.entity IN (" . getEntity('c_payment_term').")"; - if (is_numeric($cond_reglement)) $sqltemp.= " AND c.rowid=".$cond_reglement; - else $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'"; + if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement; + else { + $sqltemp.= " WHERE c.entity IN (".getEntity('c_payment_term').")"; + $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'"; + } dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG); $resqltemp=$this->db->query($sqltemp); @@ -680,7 +676,7 @@ abstract class CommonInvoiceLine extends CommonObjectLine { /** * Quantity - * @var int + * @var double */ public $qty; diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index b4426a02f74..dae9827e0e4 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -5,7 +5,7 @@ * Copyright (C) 2012 Christophe Battarel * Copyright (C) 2010-2015 Juanjo Menent * Copyright (C) 2012-2013 Christophe Battarel - * Copyright (C) 2011-2014 Philippe Grand + * Copyright (C) 2011-2018 Philippe Grand * Copyright (C) 2012-2015 Marcos García * Copyright (C) 2012-2015 Raphaël Doursenaud * Copyright (C) 2012 Cedric Salvador @@ -13,6 +13,8 @@ * Copyright (C) 2016 Bahfir abbes * Copyright (C) 2017 ATM Consulting * Copyright (C) 2017 Nicolas ZABOURI + * Copyright (C) 2017 Rui Strecht + * Copyright (C) 2018 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 @@ -44,47 +46,58 @@ abstract class CommonObject * @var DoliDb Database handler (result of a new DoliDB) */ public $db; + /** * @var int The object identifier */ public $id; + /** * @var string Error string * @see errors */ public $error; + /** * @var string[] Array of error strings */ public $errors=array(); + /** * @var string */ public $element; + /** * @var string */ public $table_element; + /** * @var */ public $table_element_line; + /** * @var string Key value used to track if data is coming from import wizard */ public $import_key; + /** * @var mixed Contains data to manage extrafields */ public $array_options=array(); + /** * @var int[][] Array of linked objects ids. Loaded by ->fetchObjectLinked */ public $linkedObjectsIds; + /** * @var mixed Array of linked objects. Loaded by ->fetchObjectLinked */ public $linkedObjects; + /** * @var Object To store a cloned copy of object before to edit it and keep track of old properties */ @@ -114,11 +127,13 @@ abstract class CommonObject * @see fetch_projet() */ public $project; + /** * @var int The related project ID * @see setProject(), project */ public $fk_project; + /** * @deprecated * @see project @@ -130,6 +145,7 @@ abstract class CommonObject * @see fetch_contact() */ public $contact; + /** * @var int The related contact ID * @see fetch_contact() @@ -163,14 +179,17 @@ abstract class CommonObject * @var string The object's reference */ public $ref; + /** * @var string The object's previous reference */ public $ref_previous; + /** * @var string The object's next reference */ public $ref_next; + /** * @var string An external reference for the object */ @@ -187,32 +206,67 @@ abstract class CommonObject * @see getFullAddress() */ public $country; + /** * @var int * @see getFullAddress(), country */ public $country_id; + /** * @var string * @see getFullAddress(), isInEEC(), country */ - public $country_code; + public $country_code; + + /** + * @var string + * @see getFullAddress() + */ + public $state; + + /** + * @var int + * @see getFullAddress(), state + */ + public $state_id; + + /** + * @var string + * @see getFullAddress(), state + */ + public $state_code; + + /** + * @var string + * @see getFullAddress(), region + */ + public $region; + + /** + * @var string + * @see getFullAddress(), region + */ + public $region_code; /** * @var int * @see fetch_barcode() */ public $barcode_type; + /** * @var string * @see fetch_barcode(), barcode_type */ public $barcode_type_code; + /** * @var string * @see fetch_barcode(), barcode_type */ public $barcode_type_label; + /** * @var string * @see fetch_barcode(), barcode_type @@ -230,6 +284,7 @@ abstract class CommonObject * @see setPaymentTerms() */ public $cond_reglement_id; + /** * @var int Payment terms ID * @deprecated Kept for compatibility @@ -267,11 +322,13 @@ abstract class CommonObject * @see update_note() */ public $note_public; + /** * @var string Private note * @see update_note() */ public $note_private; + /** * @deprecated * @see note_public @@ -283,21 +340,25 @@ abstract class CommonObject * @see update_price() */ public $total_ht; + /** * @var float Total VAT amount * @see update_price() */ public $total_tva; + /** * @var float Total local tax 1 amount * @see update_price() */ public $total_localtax1; + /** * @var float Total local tax 2 amount * @see update_price() */ public $total_localtax2; + /** * @var float Total amount with taxes * @see update_price() @@ -320,11 +381,13 @@ abstract class CommonObject * @see setIncoterms() */ public $fk_incoterms; + /** * @var string * @see SetIncoterms() */ public $libelle_incoterms; + /** * @var string * @see display_incoterms() @@ -421,9 +484,10 @@ abstract class CommonObject * * @param int $withcountry 1=Add country into address string * @param string $sep Separator to use to build string + * @param int $withregion 1=Add region into address string * @return string Full address string */ - function getFullAddress($withcountry=0,$sep="\n") + function getFullAddress($withcountry=0, $sep="\n", $withregion=0) { if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country))) { @@ -433,6 +497,16 @@ abstract class CommonObject $this->country =$tmparray['label']; } + if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde))) + { + require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php'; + $tmparray=getState($this->state_id,'all',0,1); + $this->state_code =$tmparray['code']; + $this->state =$tmparray['label']; + $this->region_code =$tmparray['region_code']; + $this->region =$tmparray['region']; + } + return dol_format_address($this, $withcountry, $sep); } @@ -470,7 +544,7 @@ abstract class CommonObject $out=''; $outdone=0; - $coords = $this->getFullAddress(1,', '); + $coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); if ($coords) { if (! empty($conf->use_javascript_ajax)) @@ -488,7 +562,12 @@ abstract class CommonObject if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS) // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) { - $out.=($outdone?' - ':'').$this->state; + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) { + $out.=($outdone?' - ':'').$this->region.' - '.$this->state; + } + else { + $out.=($outdone?' - ':'').$this->state; + } $outdone++; } @@ -547,15 +626,16 @@ abstract class CommonObject * * @param string $modulepart Module related to document * @param int $initsharekey Init the share key if it was not yet defined + * @param int $relativelink 0=Return full external link, 1=Return link relative to root of file * @return string Link or empty string if there is no download link */ - function getLastMainDocLink($modulepart, $initsharekey=0) + function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0) { global $user, $dolibarr_main_url_root; if (empty($this->last_main_doc)) { - return ''; // No known last doc + return ''; // No way to known which document name to use } include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; @@ -620,10 +700,17 @@ abstract class CommonObject if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share; // Hash for public share if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1'; - $fulllink=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:''); + if ($relativelink) + { + $linktoreturn='document.php'.($paramlink?'?'.$paramlink:''); + } + else + { + $linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:''); + } // Here $ecmfile->share is defined - return $fulllink; + return $linktoreturn; } @@ -666,7 +753,7 @@ abstract class CommonObject } else { - // On recherche id type_contact + // We look for id type_contact $sql = "SELECT tc.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'"; @@ -684,13 +771,13 @@ abstract class CommonObject if ($id_type_contact == 0) { $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT'; - dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT"); + dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it"); return -3; } $datecreate = dol_now(); - // Socpeople must have already been added by some a trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error + // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error $TListeContacts=$this->liste_contact(-1, $source); $already_added=false; if(!empty($TListeContacts)) { @@ -706,7 +793,7 @@ abstract class CommonObject $this->db->begin(); - // Insertion dans la base + // Insert into database $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ; @@ -781,7 +868,7 @@ abstract class CommonObject */ function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0) { - // Insertion dans la base + // Insert into database $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set"; $sql.= " statut = ".$statut; if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'"; @@ -1065,7 +1152,7 @@ abstract class CommonObject $sql.= " WHERE ec.element_id = ".$id; $sql.= " AND ec.fk_socpeople = c.rowid"; if ($source == 'internal') $sql.= " AND c.entity IN (0,".$conf->entity.")"; - if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")"; + if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('socpeople').")"; $sql.= " AND ec.fk_c_type_contact = tc.rowid"; $sql.= " AND tc.element = '".$element."'"; $sql.= " AND tc.source = '".$source."'"; @@ -1222,7 +1309,7 @@ abstract class CommonObject } /** - * Charge le projet d'id $this->fk_project dans this->projet + * Load the project with id $this->fk_project into this->project * * @return int <0 if KO, >=0 if OK */ @@ -1242,7 +1329,25 @@ abstract class CommonObject } /** - * Charge le user d'id userid dans this->user + * Load the product with id $this->fk_product into this->product + * + * @return int <0 if KO, >=0 if OK + */ + function fetch_product() + { + include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + + if (empty($this->fk_product)) return 0; + + $product = new Product($this->db); + $result = $product->fetch($this->fk_product); + + $this->product = $product; + return $result; + } + + /** + * Load the user with id $userid into this->user * * @param int $userid Id du contact * @return int <0 if KO, >0 if OK @@ -1339,17 +1444,19 @@ abstract class CommonObject * Setter generic. Update a specific field into database. * Warning: Trigger is run only if param trigkey is provided. * - * @param string $field Field to update - * @param mixed $value New value - * @param string $table To force other table element or element line (should not be used) - * @param int $id To force other object id (should not be used) - * @param string $format Data format ('text', 'date'). 'text' is used if not defined - * @param string $id_field To force rowid field name. 'rowid' is used if not defined - * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none' - * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') - * @return int <0 if KO, >0 if OK + * @param string $field Field to update + * @param mixed $value New value + * @param string $table To force other table element or element line (should not be used) + * @param int $id To force other object id (should not be used) + * @param string $format Data format ('text', 'date'). 'text' is used if not defined + * @param string $id_field To force rowid field name. 'rowid' is used if not defined + * @param User|string $fuser Update the user of last update field with this user. If not provided, current user is used except if value is 'none' + * @param string $trigkey Trigger key to run (in most cases something like 'XXX_MODIFY') + * @param string $fk_user_field Name of field to save user id making change + * @return int <0 if KO, >0 if OK + * @see updateExtraField */ - function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='') + function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif') { global $user,$langs,$conf; @@ -1358,24 +1465,26 @@ abstract class CommonObject if (empty($format)) $format='text'; if (empty($id_field)) $id_field='rowid'; - $fk_user_field = 'fk_user_modif'; - $error=0; $this->db->begin(); // Special case if ($table == 'product' && $field == 'note_private') $field='note'; - if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) { - $fk_user_field = 'fk_user_mod'; - } + if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod'; $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET "; + if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'"; else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value); else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null"); - if (! empty($fuser) && is_object($fuser)) $sql.=", ".$fk_user_field." = ".$fuser->id; - elseif (empty($fuser) || $fuser != 'none') $sql.=", ".$fk_user_field." = ".$user->id; + + if ($fk_user_field) + { + if (! empty($fuser) && is_object($fuser)) $sql.=", ".$fk_user_field." = ".$fuser->id; + elseif (empty($fuser) || $fuser != 'none') $sql.=", ".$fk_user_field." = ".$user->id; + } + $sql.= " WHERE ".$id_field." = ".$id; dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); @@ -1384,7 +1493,16 @@ abstract class CommonObject { if ($trigkey) { - $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors + // call trigger with updated object values + if (empty($this->fields) && method_exists($this, 'fetch')) + { + $result = $this->fetch($id); + } + else + { + $result = $this->fetchCommon($id); + } + if ($result >= 0) $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors if ($result < 0) $error++; } @@ -1418,7 +1536,7 @@ abstract class CommonObject */ function load_previous_next_ref($filter, $fieldid, $nodbprefix=0) { - global $user; + global $conf, $user; if (! $this->table_element) { @@ -1438,6 +1556,9 @@ abstract class CommonObject $sql = "SELECT MAX(te.".$fieldid.")"; $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; + if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug"; + } if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid @@ -1452,7 +1573,18 @@ abstract class CommonObject } if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql.= " AND te.entity IS NOT NULL"; // Show all users + } else { + $sql.= " AND ug.fk_user = te.rowid"; + $sql.= " AND ug.entity IN (".getEntity($this->element).")"; + } + } else { + $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; + } + } if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid; if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)'; if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid; @@ -1470,6 +1602,9 @@ abstract class CommonObject $sql = "SELECT MIN(te.".$fieldid.")"; $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te"; + if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug"; + } if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid @@ -1484,7 +1619,18 @@ abstract class CommonObject } if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid - if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; + if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) { + if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { + if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql.= " AND te.entity IS NOT NULL"; // Show all users + } else { + $sql.= " AND ug.fk_user = te.rowid"; + $sql.= " AND ug.entity IN (".getEntity($this->element).")"; + } + } else { + $sql.= ' AND te.entity IN ('.getEntity($this->element).')'; + } + } if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid; if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)'; if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid; @@ -1505,11 +1651,11 @@ abstract class CommonObject /** - * Return list of id of contacts of project + * Return list of id of contacts of object * * @param string $source Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe) * @return array Array of id of contacts (if source=external or internal) - * Array of id of third parties with at least one contact on project (if source=thirdparty) + * Array of id of third parties with at least one contact on object (if source=thirdparty) */ function getListContactId($source='external') { @@ -1684,22 +1830,50 @@ abstract class CommonObject switch ($this->element) { case 'propal': - $this->updateline($line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); + $this->updateline( + $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, + ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, + $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, + $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice + ); break; case 'commande': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); + $this->updateline( + $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, + $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, + $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, + $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice + ); break; case 'facture': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice); + $this->updateline( + $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, + $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, + $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, + $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice + ); break; case 'supplier_proposal': - $this->updateline($line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options, $line->ref_fourn, $line->multicurrency_subprice); + $this->updateline( + $line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, + ($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, + $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options, + $line->ref_fourn, $line->multicurrency_subprice + ); break; case 'order_supplier': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); + $this->updateline( + $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent, + $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false, + $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice + ); break; case 'invoice_supplier': - $this->updateline($line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); + $this->updateline( + $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx, + $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false, + $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice + ); break; default: dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG); @@ -1802,29 +1976,57 @@ abstract class CommonObject * Change the shipping method * * @param int $shipping_method_id Id of shipping method + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @param User $userused Object user + * * @return int 1 if OK, 0 if KO */ - function setShippingMethod($shipping_method_id) + function setShippingMethod($shipping_method_id, $notrigger=false, $userused=null) { + global $user; + + if (empty($userused)) $userused=$user; + + $error = 0; + if (! $this->table_element) { dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR); return -1; } + + $this->db->begin(); + if ($shipping_method_id<0) $shipping_method_id='NULL'; dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql.= " SET fk_shipping_method = ".$shipping_method_id; $sql.= " WHERE rowid=".$this->id; - - if ($this->db->query($sql)) { - $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; - return 1; - } else { + $resql = $this->db->query($sql); + if (! $resql) { dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); - $this->error=$this->db->error(); - return 0; - } + $this->error = $this->db->lasterror(); + $error++; + } else { + if (!$notrigger) + { + // Call trigger + $this->context=array('shippingmethodupdate'=>1); + $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused); + if ($result < 0) $error++; + // End call trigger + } + } + if ($error) + { + $this->db->rollback(); + return -1; + } else { + $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; + $this->db->commit(); + return 1; + } + } @@ -1900,14 +2102,24 @@ abstract class CommonObject * Change the bank account * * @param int $fk_account Id of bank account + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @param User $userused Object user * @return int 1 if OK, 0 if KO */ - function setBankAccount($fk_account) + function setBankAccount($fk_account, $notrigger=false, $userused=null) { + global $user; + + if (empty($userused)) $userused=$user; + + $error = 0; + if (! $this->table_element) { dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR); return -1; } + $this->db->begin(); + if ($fk_account<0) $fk_account='NULL'; dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); @@ -1915,15 +2127,37 @@ abstract class CommonObject $sql.= " SET fk_account = ".$fk_account; $sql.= " WHERE rowid=".$this->id; - if ($this->db->query($sql)) { - $this->fk_account = ($fk_account=='NULL')?null:$fk_account; - return 1; - } else { - dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); - $this->error=$this->db->error(); - return 0; - } - } + $resql = $this->db->query($sql); + if (! $resql) + { + dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); + $this->error = $this->db->lasterror(); + $error++; + } + else + { + if (!$notrigger) + { + // Call trigger + $this->context=array('bankaccountupdate'=>1); + $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused); + if ($result < 0) $error++; + // End call trigger + } + } + if ($error) + { + $this->db->rollback(); + return -1; + } + else + { + $this->fk_account = ($fk_account=='NULL')?null:$fk_account; + $this->db->commit(); + return 1; + } + } + // TODO: Move line related operations to CommonObjectLine? @@ -2527,7 +2761,7 @@ abstract class CommonObject $this->multicurrency_total_ttc += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0; // Situations totals - if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits')) + if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE ) { $prev_sits = $this->get_prev_sits(); @@ -2571,7 +2805,7 @@ abstract class CommonObject $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'"; $sql .= ' WHERE rowid = '.$this->id; - //print "xx".$sql; + dol_syslog(get_class($this)."::update_price", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) @@ -2657,11 +2891,12 @@ abstract class CommonObject * @param int $targetid Object target id (if not defined, id of object) * @param string $targettype Object target type (if not defined, elemennt name of object) * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided - * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type. - * @return void + * @param int $alsosametype 0=Return only links to object that differs from source. 1=Include also link to objects of same type. + * @param string $orderby SQL 'ORDER BY' clause + * @return int <0 if KO, >0 if OK * @see add_object_linked, updateObjectLinked, deleteObjectLinked */ - function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1) + function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype') { global $conf; @@ -2717,8 +2952,7 @@ abstract class CommonObject $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')"; $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')"; } - $sql .= ' ORDER BY sourcetype'; - //print $sql; + $sql .= ' ORDER BY '.$orderby; dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG); $resql = $this->db->query($sql); @@ -2839,10 +3073,12 @@ abstract class CommonObject } } } + return 1; } else { dol_print_error($this->db); + return -1; } } @@ -2961,9 +3197,10 @@ abstract class CommonObject * @param int $status Status to set * @param int $elementId Id of element to force (use this->id by default) * @param string $elementType Type of element to force (use this->table_element by default) + * @param string $trigkey Trigger key to use for trigger * @return int <0 if KO, >0 if OK */ - function setStatut($status,$elementId=null,$elementType='') + function setStatut($status, $elementId=null, $elementType='', $trigkey='') { global $user,$langs,$conf; @@ -2975,7 +3212,9 @@ abstract class CommonObject $this->db->begin(); $fieldstatus="fk_statut"; + if ($elementTable == 'facture_rec') $fieldstatus="suspended"; if ($elementTable == 'mailing') $fieldstatus="statut"; + if ($elementTable == 'cronjob') $fieldstatus="status"; if ($elementTable == 'user') $fieldstatus="statut"; if ($elementTable == 'expensereport') $fieldstatus="fk_statut"; if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status"; @@ -2991,13 +3230,16 @@ abstract class CommonObject { $error = 0; - $trigkey=''; - if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class - if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class - if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; - if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; - if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; + // Try autoset of trigkey + if (empty($trigkey)) + { + if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class + if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class + if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE'; + if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; + if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; + } if ($trigkey) { @@ -3144,7 +3386,14 @@ abstract class CommonObject $langs->load("errors"); //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild; $haschild += $obj->nb; - $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); + if (is_numeric($elementname)) // old usage + { + $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table); + } + else // new usage: $elementname=Translation key + { + $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname)); + } break; // We found at least one, we stop here } } @@ -3439,19 +3688,6 @@ abstract class CommonObject } - /** - * Return if a country is inside the EEC (European Economic Community) - * @deprecated Use function isInEEC function instead - * - * @return boolean true = country inside EEC, false = country outside EEC - */ - function isInEEC() - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; - return isInEEC($this); - } - - // -------------------- // TODO: All functions here must be redesigned and moved as they are not business functions but output functions // -------------------- @@ -3466,12 +3702,12 @@ abstract class CommonObject * @param Societe $buyer Object thirdparty who buy * @return void */ - function formAddObjectLine($dateSelector,$seller,$buyer) + function formAddObjectLine($dateSelector, $seller, $buyer) { global $conf,$user,$langs,$object,$hookmanager; global $form,$bcnd,$var; - //Line extrafield + // Line extrafield require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafieldsline = new ExtraFields($this->db); $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line); @@ -3500,7 +3736,7 @@ abstract class CommonObject * Return HTML table for object lines * TODO Move this into an output class file (htmlline.class.php) * If lines are into a template, title must also be into a template - * But for the moment we don't know if it'st possible as we keep a method available on overloaded objects. + * But for the moment we don't know if it's possible as we keep a method available on overloaded objects. * * @param string $action Action code * @param string $seller Object of seller third party @@ -3521,7 +3757,7 @@ abstract class CommonObject $num = count($this->lines); - //Line extrafield + // Line extrafield require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafieldsline = new ExtraFields($this->db); $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line); @@ -3530,6 +3766,9 @@ abstract class CommonObject $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { + // Title line + print "\n"; + print ''; if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ' '; @@ -3549,7 +3788,7 @@ abstract class CommonObject print ''.$langs->trans('PriceUHT').''; // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''; + if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print ''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''; if ($inputalsopricewithtax) print ''.$langs->trans('PriceUTTC').''; @@ -3588,7 +3827,7 @@ abstract class CommonObject print ''.$langs->trans('TotalHTShort').''; // Multicurrency - if (!empty($conf->multicurrency->enabled)) print ''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''; + if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print ''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''; if ($outputalsopricetotalwithtax) print ''.$langs->trans('TotalTTCShort').''; @@ -3598,18 +3837,26 @@ abstract class CommonObject print ''; + if($action == 'selectlines') + { + print ''; + print ''; + print ''; + print ''; + } + print "\n"; + print "\n"; } $var = true; $i = 0; + print "\n"; foreach ($this->lines as $line) { //Line extrafield - $line->fetch_optionals($line->id,$extralabelslines); - - + $line->fetch_optionals(); //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) if (is_object($hookmanager)) // Old code is commented on preceding line. @@ -3632,6 +3879,7 @@ abstract class CommonObject $i++; } + print "\n"; } /** @@ -3654,7 +3902,7 @@ abstract class CommonObject { global $conf,$langs,$user,$object,$hookmanager; global $form,$bc,$bcdd; - global $object_rights, $disableedit, $disablemove; // TODO We should not use global var for this ! + global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this ! $object_rights = $this->getRights(); @@ -3788,23 +4036,26 @@ abstract class CommonObject $var = true; $i = 0; - foreach ($this->lines as $line) + if (! empty($this->lines)) { - if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) + foreach ($this->lines as $line) { - if (empty($line->fk_parent_line)) + if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line))) { - $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); - $action=''; - $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if (empty($line->fk_parent_line)) + { + $parameters=array('line'=>$line,'var'=>$var,'i'=>$i); + $action=''; + $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + } + } + else + { + $this->printOriginLine($line, $var, $restrictlist); } - } - else - { - $this->printOriginLine($line, $var, $restrictlist); - } - $i++; + $i++; + } } } @@ -3901,6 +4152,12 @@ abstract class CommonObject $discount->fetch($line->fk_remise_except); $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0)); } + elseif ($line->desc == '(EXCESS PAID)') + { + $discount=new DiscountAbsolute($this->db); + $discount->fetch($line->fk_remise_except); + $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0)); + } else { $this->tpl['description'] = dol_trunc($line->desc,60); @@ -4054,6 +4311,7 @@ abstract class CommonObject * @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 + * @see addFileIntoDatabaseIndex */ protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null) { @@ -4206,8 +4464,10 @@ abstract class CommonObject if ($useonlinesignature) $setsharekey=true; if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; } - if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; - if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'commande' && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'facture' && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true; + if ($setsharekey) { if (empty($ecmfile->share)) // Because object not found or share not set yet @@ -4240,6 +4500,9 @@ abstract class CommonObject $ecmfile->gen_or_uploaded = 'generated'; $ecmfile->description = ''; // indexed content $ecmfile->keyword = ''; // keyword content + $ecmfile->src_object_type = $this->table_element; + $ecmfile->src_object_id = $this->id; + $result = $ecmfile->create($user); if ($result < 0) { @@ -4292,6 +4555,7 @@ abstract class CommonObject /** * Build thumb + * @TODO Move this into files.lib.php * * @param string $file Path file in UTF8 to original file to create thumbs from. * @return void @@ -4415,6 +4679,8 @@ abstract class CommonObject return 0; } + $this->array_options=array(); + if (! is_array($optionsArray)) { // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page. @@ -4431,10 +4697,11 @@ abstract class CommonObject { $extrafields->fetch_name_optionals_label($this->table_element); } - $optionsArray = $extrafields->attributes[$this->table_element]['label']; + $optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null); } else { + global $extrafields; dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING); } @@ -4455,7 +4722,7 @@ abstract class CommonObject $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields"; $sql.= " WHERE fk_object = ".$rowid; - dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); + //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG); // Too verbose $resql=$this->db->query($sql); if ($resql) { @@ -4535,8 +4802,9 @@ abstract class CommonObject * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY) * @param User $userused Object user * @return int -1=error, O=did nothing, 1=OK + * @see updateExtraField, setValueFrom */ - function insertExtraFields($trigger='',$userused=null) + function insertExtraFields($trigger='', $userused=null) { global $conf,$langs,$user; @@ -4566,10 +4834,10 @@ abstract class CommonObject foreach($new_array_options as $key => $value) { $attributeKey = substr($key,8); // Remove 'options_' prefix - $attributeType = $extrafields->attribute_type[$attributeKey]; - $attributeLabel = $extrafields->attribute_label[$attributeKey]; - $attributeParam = $extrafields->attribute_param[$attributeKey]; - $attributeRequired = $extrafields->attribute_required[$attributeKey]; + $attributeType = $extrafields->attributes[$this->table_element]['type'][$attributeKey]; + $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$attributeKey]; + $attributeParam = $extrafields->attributes[$this->table_element]['param'][$attributeKey]; + $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey]; if ($attributeRequired) { @@ -4602,7 +4870,44 @@ abstract class CommonObject $this->array_options[$key] = null; } break;*/ - case 'price': + case 'password': + $algo=''; + if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) + { + // If there is an encryption choice, we use it to crypt data before insert + $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']); + $algo=reset($tmparrays); + if ($algo != '') + { + //global $action; // $action may be 'create', 'update', 'update_extras'... + //var_dump($action); + //var_dump($this->oldcopy);exit; + if (is_object($this->oldcopy)) // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value + { + //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]); + if ($this->array_options[$key] == $this->oldcopy->array_options[$key]) // If old value crypted in database is same than submited new value, it means we don't change it, so we don't update. + { + $new_array_options[$key] = $this->array_options[$key]; // Value is kept + } + else + { + // var_dump($algo); + $newvalue = dol_hash($this->array_options[$key], $algo); + $new_array_options[$key] = $newvalue; + } + } + else + { + $new_array_options[$key] = $this->array_options[$key]; // Value is kept + } + } + } + else // Common usage + { + $new_array_options[$key] = $this->array_options[$key]; + } + break; + case 'price': $new_array_options[$key] = price2num($this->array_options[$key]); break; case 'date': @@ -4664,7 +4969,7 @@ abstract class CommonObject { $attributeKey = substr($key,8); // Remove 'options_' prefix // Add field of attribut - if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate + if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator $sql.=",".$attributeKey; } $sql .= ") VALUES (".$this->id; @@ -4672,8 +4977,8 @@ abstract class CommonObject foreach($new_array_options as $key => $value) { $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field o fattribut - if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) + // Add field of attribute + if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator) { if ($new_array_options[$key] != '') { @@ -4694,16 +4999,14 @@ abstract class CommonObject $this->error=$this->db->lasterror(); $error++; } - else + + if (! $error && $trigger) { - if ($trigger) - { - // Call trigger - $this->context=array('extrafieldaddupdate'=>1); - $result=$this->call_trigger($trigger, $userused); - if ($result < 0) $error++; - // End call trigger - } + // Call trigger + $this->context=array('extrafieldaddupdate'=>1); + $result=$this->call_trigger($trigger, $userused); + if ($result < 0) $error++; + // End call trigger } if ($error) @@ -4721,16 +5024,20 @@ abstract class CommonObject } /** - * Update an exta field value for the current object. - * Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) - * This function delte record with all extrafields and insert them again from the array $this->array_options. + * Update an extra field value for the current object. + * Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) * - * @param string $key Key of the extrafield - * @return int -1=error, O=did nothing, 1=OK + * @param string $key Key of the extrafield (without starting 'options_') + * @param string $trigger If defined, call also the trigger (for example COMPANY_MODIFY) + * @param User $userused Object user + * @return int -1=error, O=did nothing, 1=OK + * @see setValueFrom, insertExtraFields */ - function updateExtraField($key) + function updateExtraField($key, $trigger, $userused) { - global $conf,$langs; + global $conf,$langs,$user; + + if (empty($userused)) $userused=$user; $error=0; @@ -4745,9 +5052,12 @@ abstract class CommonObject $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element); $value=$this->array_options["options_".$key]; - $attributeType = $extrafields->attribute_type[$key]; - $attributeLabel = $extrafields->attribute_label[$key]; - $attributeParam = $extrafields->attribute_param[$key]; + + $attributeType = $extrafields->attributes[$this->table_element]['type'][$key]; + $attributeLabel = $extrafields->attributes[$this->table_element]['label'][$key]; + $attributeParam = $extrafields->attributes[$this->table_element]['param'][$key]; + $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key]; + switch ($attributeType) { case 'int': @@ -4777,7 +5087,7 @@ abstract class CommonObject $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]); break; case 'link': - $param_list=array_keys($attributeParam ['options']); + $param_list=array_keys($attributeParam['options']); // 0 : ObjectName // 1 : classPath $InfoFieldList = explode(":", $param_list[0]); @@ -4797,7 +5107,21 @@ abstract class CommonObject $resql = $this->db->query($sql); if (! $resql) { + $error++; $this->error=$this->db->lasterror(); + } + + if (! $error && $trigger) + { + // Call trigger + $this->context=array('extrafieldupdate'=>1); + $result=$this->call_trigger($trigger, $userused); + if ($result < 0) $error++; + // End call trigger + } + + if ($error) + { dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR); $this->db->rollback(); return -1; @@ -4819,7 +5143,7 @@ abstract class CommonObject * @param array $val Array of properties for field to show * @param string $key Key of attribute * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) - * @param string $moreparam To add more parametes on html input tag + * @param string $moreparam To add more parameters on html input tag * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names) * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names) * @param string|int $showsize Value for css to define size. May also be a numeric. @@ -4852,7 +5176,6 @@ abstract class CommonObject if (is_array($val['arrayofkeyval'])) $type='select'; if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; - //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used $default=$val['default']; $computed=$val['computed']; $unique=$val['unique']; @@ -4875,7 +5198,7 @@ abstract class CommonObject else return ''; } - // Use in priorit showsize from parameters, then $val['css'] then autodefine + // Use in priority showsize from parameters, then $val['css'] then autodefine if (empty($showsize) && ! empty($val['css'])) { $showsize = $val['css']; @@ -5345,6 +5668,41 @@ abstract class CommonObject // If prefix is 'search_', field is used as a filter, we use a common text field. $out=''; } + elseif ($type == 'array') + { + $newval = $val; + $newval['type'] = 'varchar(256)'; + + $out=''; + + $inputs = array(); + if(! empty($value)) { + foreach($value as $option) { + $out.= ' '; + $out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'
'; + } + } + + $out.= ''; + + $newInput = ' '; + $newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'
'; + + if(! empty($conf->use_javascript_ajax)) { + $out.= ' + '; + } + } if (!empty($hidden)) { $out=''; } @@ -5394,7 +5752,6 @@ abstract class CommonObject if (is_array($val['arrayofkeyval'])) $type='select'; if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link'; - //$elementtype=$this->attribute_elementtype[$key]; // seems to not be used $default=$val['default']; $computed=$val['computed']; $unique=$val['unique']; @@ -5717,6 +6074,10 @@ abstract class CommonObject { $value=preg_replace('/./i','*',$value); } + elseif ($type == 'array') + { + $value = implode('
', $value); + } //print $type.'-'.$size; $out=$value; @@ -5738,21 +6099,35 @@ abstract class CommonObject */ function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0) { - global $_POST, $conf, $langs, $action; + global $db, $conf, $langs, $action, $form; + + if (! is_object($form)) $form=new Form($db); $out = ''; - if (count($extrafields->attribute_label) > 0) + if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0) { $out .= "\n"; $out .= ' '; $out .= "\n"; $e = 0; - foreach($extrafields->attribute_label as $key=>$label) + foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label) { - if (empty($extrafields->attribute_list[$key])) continue; // 0 = Never visible field - if (($mode == 'create' || $mode == 'edit') && abs($extrafields->attribute_list[$key]) != 1 && abs($extrafields->attribute_list[$key]) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list + $enabled = 1; + if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key])) + { + $enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1); + } + + $perms = 1; + if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key])) + { + $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1); + } + + if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list + if (empty($perms)) continue; // Load language if required if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]); @@ -5787,28 +6162,38 @@ abstract class CommonObject break; } - if ($extrafields->attribute_type[$key] == 'separate') + if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') { - $out .= $extrafields->showSeparator($key); + $out .= $extrafields->showSeparator($key, $this); } else { $csstyle=''; - $class=(!empty($extrafields->attribute_hidden[$key]) ? 'class="hideobject" ' : ''); + $class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : ''); if (is_array($params) && count($params)>0) { if (array_key_exists('style',$params)) { $csstyle=$params['style']; } } - $out .= ''; - if (empty($onetrtd)) + // add html5 elements + $domData = ' data-element="extrafield"'; + $domData .= ' data-targetelement="'.$this->element.'"'; + $domData .= ' data-targetid="'.$this->id.'"'; + + $html_id = !empty($this->id) ? 'extrarow-'.$this->element.'_'.$key.'_'.$this->id : ''; + + $out .= ''; + + if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan='0'; } } + if ($action == 'selectlines') { $colspan++; } + // Convert date into timestamp format (value in memory must be a timestamp) - if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) + if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime'))) { $datenotinstring = $this->array_options['options_' . $key]; if (! is_numeric($this->array_options['options_' . $key])) // For backward compatibility @@ -5818,28 +6203,23 @@ abstract class CommonObject $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min",'int',3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year",'int',3)):$datenotinstring; } // Convert float submited string into real php numeric (value in memory must be a php numeric) - if (in_array($extrafields->attribute_type[$key],array('price','double'))) + if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double'))) { $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key]; } $labeltoshow = $langs->trans($label); - if($extrafields->attribute_required[$key]) - { - $labeltoshow = ''.$labeltoshow.''; - } - - if (empty($onetrtd)) $out .= ''; - else $out .= ''; - - $out .= $labeltoshow; - - if (empty($onetrtd)) $out .= ''; - else $out.=' '; + $out .= ''; + if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]); + else $out .= $labeltoshow; + $out .= ''; $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : ''; - $out .=''; + $out .=''; switch($mode) { case "view": @@ -5851,8 +6231,9 @@ abstract class CommonObject } $out .= ''; - $out .= ''; + if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= ''; + else $out .= ''; $e++; } } @@ -5864,7 +6245,7 @@ abstract class CommonObject jQuery(document).ready(function() { function showOptions(child_list, parent_list) { - var val = $("select[name="+parent_list+"]").val(); + var val = $("select[name=\"options_"+parent_list+"\"]").val(); var parentVal = parent_list + ":" + val; if(val > 0) { $("select[name=\""+child_list+"\"] option[parent]").hide(); @@ -6019,6 +6400,243 @@ abstract class CommonObject return $buyPrice; } + /** + * Show photos of an object (nbmax maximum), into several columns + * + * @param string $modulepart 'product', 'ticket', ... + * @param string $sdir Directory to scan (full absolute path) + * @param int $size 0=original size, 1='small' use thumbnail if possible + * @param int $nbmax Nombre maximum de photos (0=pas de max) + * @param int $nbbyrow Number of image per line or -1 to use div. Used only if size=1. + * @param int $showfilename 1=Show filename + * @param int $showaction 1=Show icon with action links (resize, delete) + * @param int $maxHeight Max height of original image when size='small' (so we can use original even if small requested). If 0, always use 'small' thumb image. + * @param int $maxWidth Max width of original image when size='small' + * @param int $nolink Do not add a href link to view enlarged imaged into a new tab + * @param int $notitle Do not add title tag on image + * @param int $usesharelink Use the public shared link of image (if not available, the 'nophoto' image will be shown instead) + * @return string Html code to show photo. Number of photos shown is saved in this->nbphoto + */ + function show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $notitle=0, $usesharelink=0) + { + global $conf,$user,$langs; + + include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php'; + + $sortfield='position_name'; + $sortorder='asc'; + + $dir = $sdir . '/'; + $pdir = '/'; + if ($modulepart == 'ticket') + { + $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/'; + $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/'; + } + else + { + $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/'; + $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/'; + } + + // For backward compatibility + if ($modulepart == 'product' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) + { + $dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/"; + $pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/"; + } + + // Defined relative dir to DOL_DATA_ROOT + $relativedir = ''; + if ($dir) + { + $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir); + $relativedir = preg_replace('/^[\\/]/','',$relativedir); + $relativedir = preg_replace('/[\\/]$/','',$relativedir); + } + + $dirthumb = $dir.'thumbs/'; + $pdirthumb = $pdir.'thumbs/'; + + $return =''."\n"; + $nbphoto=0; + + $filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); + + /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs + { + $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); + $filearray=array_merge($filearray, $filearrayold); + }*/ + + completeFileArrayWithDatabaseInfo($filearray, $relativedir); + + if (count($filearray)) + { + if ($sortfield && $sortorder) + { + $filearray=dol_sort_array($filearray, $sortfield, $sortorder); + } + + foreach($filearray as $key => $val) + { + $photo=''; + $file = $val['name']; + + //if (! utf8_check($file)) $file=utf8_encode($file); // To be sure file is stored in UTF8 in memory + + //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) + if (image_format_supported($file) >= 0) + { + $nbphoto++; + $photo = $file; + $viewfilename = $file; + + if ($size == 1 || $size == 'small') { // Format vignette + + // Find name of thumb file + $photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small')); + if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette=''; + + // Get filesize of original file + $imgarray=dol_getImageSize($dir.$photo); + + if ($nbbyrow > 0) + { + if ($nbphoto == 1) $return.= ''; + + if ($nbphoto % $nbbyrow == 1) $return.= ''; + $return.= ''; + if (($nbphoto % $nbbyrow) == 0) $return.= ''; + } + else if ($nbbyrow < 0) $return.=''; + } + + if (empty($size)) { // Format origine + $return.= ''; + + if ($showfilename) $return.= '
'.$viewfilename; + if ($showaction) + { + // Special case for product + if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) + { + // Link to resize + $return.= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; + + // Link to delete + $return.= ''; + $return.= img_delete().''; + } + } + } + + // On continue ou on arrete de boucler ? + if ($nbmax && $nbphoto >= $nbmax) break; + } + } + + if ($size==1 || $size=='small') + { + if ($nbbyrow > 0) + { + // Ferme tableau + while ($nbphoto % $nbbyrow) + { + $return.= ''; + $nbphoto++; + } + + if ($nbphoto) $return.= '
'; + } + else if ($nbbyrow < 0) $return .= '
'; + + $return.= "\n"; + + $relativefile=preg_replace('/^\//', '', $pdir.$photo); + if (empty($nolink)) + { + $urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity); + if ($urladvanced) $return.=''; + else $return.= ''; + } + + // Show image (width height=$maxHeight) + // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine + $alt=$langs->transnoentitiesnoconv('File').': '.$relativefile; + $alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height']; + if ($notitle) $alt=''; + + if ($usesharelink) + { + if ($val['share']) + { + if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) + { + $return.= ''; + $return.= ''; + } + else { + $return.= ''; + $return.= ''; + } + } + else + { + $return.= ''; + $return.= ''; + } + } + else + { + if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight) + { + $return.= ''; + $return.= ''; + } + else { + $return.= ''; + $return.= ''; + } + } + + if (empty($nolink)) $return.= ''; + $return.="\n"; + + if ($showfilename) $return.= '
'.$viewfilename; + if ($showaction) + { + $return.= '
'; + // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites + if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight)) + { + $return.= ''.img_picto($langs->trans('GenerateThumb'),'refresh').'  '; + } + // Special cas for product + if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer)) + { + // Link to resize + $return.= ''.img_picto($langs->trans("Resize"), 'resize', '').'   '; + + // Link to delete + $return.= ''; + $return.= img_delete().''; + } + } + $return.= "\n"; + + if ($nbbyrow > 0) + { + $return.= '
 
'; + } + } + } + + $this->nbphoto = $nbphoto; + + return $return; + } /** @@ -6053,7 +6671,6 @@ abstract class CommonObject else return false; } - /** * Function test if type is date * @@ -6148,7 +6765,7 @@ abstract class CommonObject { if(empty($this->{$field})) { - $queryarray[$field] = NULL; + $queryarray[$field] = null; } else { @@ -6157,7 +6774,14 @@ abstract class CommonObject } else if($this->isArray($info)) { - $queryarray[$field] = serialize($this->{$field}); + if(! empty($this->{$field})) { + if(! is_array($this->{$field})) { + $this->{$field} = array($this->{$field}); + } + $queryarray[$field] = serialize($this->{$field}); + } else { + $queryarray[$field] = null; + } } else if($this->isInt($info)) { @@ -6201,9 +6825,13 @@ abstract class CommonObject } elseif($this->isArray($info)) { - $this->{$field} = @unserialize($obj->{$field}); - // Hack for data not in UTF8 - if($this->{$field } === FALSE) @unserialize(utf8_decode($obj->{$field})); + if(! empty($obj->{$field})) { + $this->{$field} = @unserialize($obj->{$field}); + // Hack for data not in UTF8 + if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field})); + } else { + $this->{$field} = array(); + } } elseif($this->isInt($info)) { @@ -6354,19 +6982,23 @@ abstract class CommonObject /** * Load object in memory from the database * - * @param int $id Id object - * @param string $ref Ref - * @return int <0 if KO, 0 if not found, >0 if OK + * @param int $id Id object + * @param string $ref Ref + * @param string $morewhere More SQL filters (' AND ...') + * @return int <0 if KO, 0 if not found, >0 if OK */ - public function fetchCommon($id, $ref = null) + public function fetchCommon($id, $ref = null, $morewhere = '') { - if (empty($id) && empty($ref)) return false; + if (empty($id) && empty($ref) && empty($morewhere)) return -1; $sql = 'SELECT '.$this->getFieldList(); $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element; - if(!empty($id)) $sql.= ' WHERE rowid = '.$id; - else $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']); + if (!empty($id)) $sql.= ' WHERE rowid = '.$id; + elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']); + else $sql.=' WHERE 1 = 1'; // usage with empty id and empty ref is very rare + if ($morewhere) $sql.= $morewhere; + $sql.=' LIMIT 1'; // This is a fetch, to be sure to get only one record $res = $this->db->query($sql); if ($res) @@ -6448,15 +7080,12 @@ abstract class CommonObject } // Update extrafield - if (! $error) + if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0) { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + $result=$this->insertExtraFields(); + if ($result < 0) { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } + $error++; } } @@ -6548,6 +7177,9 @@ abstract class CommonObject // TODO... } + + /* Part for comments */ + /** * Load comments linked with current task * @return boolean 1 if ok diff --git a/htdocs/core/class/commonorder.class.php b/htdocs/core/class/commonorder.class.php index 8cacf7065b1..b3e5033330d 100644 --- a/htdocs/core/class/commonorder.class.php +++ b/htdocs/core/class/commonorder.class.php @@ -73,7 +73,7 @@ abstract class CommonOrderLine extends CommonObjectLine /** * Quantity - * @var int + * @var float */ public $qty; diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 0d67fa6b49c..3b33b1f16f1 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -39,6 +39,8 @@ class Conf var $db; //! To store properties found into database var $global; + //! To store browser info + var $browser; //! To store if javascript/ajax is enabked public $use_javascript_ajax; @@ -97,7 +99,7 @@ class Conf // First level object // TODO Remove this part. $this->expedition_bon = new stdClass(); - $this->livraison_bon = new stdClass(); + $this->livraison_bon = new stdClass(); $this->fournisseur = new stdClass(); $this->product = new stdClass(); $this->service = new stdClass(); @@ -107,12 +109,13 @@ class Conf $this->propal = new stdClass(); $this->facture = new stdClass(); $this->contrat = new stdClass(); - $this->usergroup = new stdClass(); + $this->usergroup = new stdClass(); $this->adherent = new stdClass(); $this->bank = new stdClass(); $this->notification = new stdClass(); $this->mailing = new stdClass(); - $this->expensereport = new stdClass(); + $this->expensereport = new stdClass(); + $this->productbatch = new stdClass(); } @@ -315,17 +318,20 @@ class Conf $this->user->dir_output=$rootforuser."/users"; $this->user->dir_temp=$rootforuser."/users/temp"; - // UserGroup + // For usergroup storage $this->usergroup->dir_output=$rootforuser."/usergroups"; $this->usergroup->dir_temp=$rootforuser."/usergroups/temp"; - // For propal storage + // For proposal storage + $this->propal->multidir_output = array($this->entity => $rootfordata."/propale"); + $this->propal->multidir_temp = array($this->entity => $rootfordata."/propale/temp"); + // For backward compatibility $this->propal->dir_output=$rootfordata."/propale"; $this->propal->dir_temp=$rootfordata."/propale/temp"; // For medias storage $this->medias->multidir_output = array($this->entity => $rootfordata."/medias"); - $this->medias->multidir_temp = array($this->entity => $rootfordata."/medias/temp"); + $this->medias->multidir_temp = array($this->entity => $rootfordata."/medias/temp"); // Exception: Some dir are not the name of module. So we keep exception here for backward compatibility. @@ -378,16 +384,24 @@ class Conf $this->service->dir_output=$rootfordata."/produit"; $this->service->dir_temp =$rootfordata."/produit/temp"; + // Module productbatch + $this->productbatch->multidir_output=array($this->entity => $rootfordata."/produitlot"); + $this->productbatch->multidir_temp =array($this->entity => $rootfordata."/produitlot/temp"); + // Module contrat - $this->contrat->dir_output=$rootfordata."/contracts"; - $this->contrat->dir_temp =$rootfordata."/contracts/temp"; + $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract"); + $this->contrat->multidir_temp = array($this->entity => $rootfordata."/contract/temp"); + // For backward compatibility + $this->contrat->dir_output=$rootfordata."/contract"; + $this->contrat->dir_temp =$rootfordata."/contract/temp"; + // Module bank $this->bank->dir_output=$rootfordata."/bank"; $this->bank->dir_temp =$rootfordata."/bank/temp"; // Set some default values - + //$this->global->MAIN_LIST_FILTER_ON_DAY=1; // On filter that show date, we must show input field for day before or after month $this->global->MAIN_ACTIVATE_HTML5=1; $this->global->MAIN_MAIL_USE_MULTI_PART=1; @@ -488,13 +502,13 @@ class Conf // Default pdf option if (! isset($this->global->MAIN_PDF_DASH_BETWEEN_LINES)) $this->global->MAIN_PDF_DASH_BETWEEN_LINES=1; // use dash between lines - if (! isset($this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) $this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT=1; // allow html content into free footer text + if (! isset($this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) $this->global->PDF_ALLOW_HTML_FOR_FREE_TEXT=1; // allow html content into free footer text // Set default value to MAIN_SHOW_LOGO if (! isset($this->global->MAIN_SHOW_LOGO)) $this->global->MAIN_SHOW_LOGO=1; // Default max file size for upload - $this->maxfilesize = (empty($this->global->MAIN_UPLOAD_DOC) ? 0 : $this->global->MAIN_UPLOAD_DOC * 1024); + $this->maxfilesize = (empty($this->global->MAIN_UPLOAD_DOC) ? 0 : (int) $this->global->MAIN_UPLOAD_DOC * 1024); // By default, we propagate contacts if (! isset($this->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) $this->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN='*'; // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented) @@ -507,6 +521,10 @@ class Conf // 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,blockedlog'; // '' means 'all'. Note that contact is added here as it should be a module later. + if (! empty($this->modules_parts['moduleforexternal'])) // Module part to include an external module into the MAIN_MODULES_FOR_EXTERNAL list + { + foreach($this->modules_parts['moduleforexternal'] as $key=>$value) $this->global->MAIN_MODULES_FOR_EXTERNAL.=",".$key; + } // Enable select2 if (empty($this->global->MAIN_USE_JQUERY_MULTISELECT) || $this->global->MAIN_USE_JQUERY_MULTISELECT == '1') $this->global->MAIN_USE_JQUERY_MULTISELECT='select2'; @@ -592,6 +610,8 @@ class Conf $this->global->AGENDA_DEFAULT_FILTER_TYPE='0'; // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on. } + if (! isset($this->global->MAIN_EXTRAFIELDS_IN_ONE_TD)) $this->global->MAIN_EXTRAFIELDS_IN_ONE_TD = 1; + $this->global->MAIN_MODULE_DOLISTORE_API_SRV='https://www.dolistore.com'; $this->global->MAIN_MODULE_DOLISTORE_API_KEY='dolistorecatalogpublickey1234567'; diff --git a/htdocs/core/class/cookie.class.php b/htdocs/core/class/cookie.class.php deleted file mode 100644 index 1d28861a44e..00000000000 --- a/htdocs/core/class/cookie.class.php +++ /dev/null @@ -1,142 +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/cookie.class.php - * \ingroup core - * \brief File of class to manage cookies - */ - - -/** - * Class to manage cookies. - * This class is used by external module multicompany but will be removed soon only and must not be used by - * - * @deprecated PHP already provide function to read/store a cookie. No need to use a dedicated class. Also storing sensitive information into cookie is forbidden, so encryption is useless. - * If a data is sensitive, it must be stored into database (if we need a long term retention) or into session. - */ -class DolCookie -{ - private $_myKey; - private $_iv; - - var $myCookie; - var $myValue; - var $myExpire; - var $myPath; - var $myDomain; - var $mySecure; - var $cookie; - - /** - * Constructor - * - * @param string $key Personnal key - * @deprecated - */ - function __construct($key = '') - { - $this->_myKey = hash('sha256', $key, TRUE); - $this->_iv = md5(md5($this->_myKey)); - $this->cookie = ""; - $this->myCookie = ""; - $this->myValue = ""; - } - - - /** - * Encrypt en create the cookie - * - * @return void - */ - private function _cryptCookie() - { - if (!empty($this->_myKey) && !empty($this->_iv)) - { - $valuecrypt = base64_encode($this->myValue); - $this->cookie = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->_myKey, $valuecrypt, MCRYPT_MODE_CBC, $this->_iv)); - } - else - { - $this->cookie = $this->myValue; - } - - setcookie($this->myCookie, $this->cookie, $this->myExpire, $this->myPath, $this->myDomain, $this->mySecure); - } - - /** - * Decrypt the cookie - * - * @return string - */ - private function _decryptCookie() - { - if (!empty($this->_myKey) && !empty($this->_iv)) - { - $this->cookie = $_COOKIE[$this->myCookie]; - $this->myValue = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->_myKey, base64_decode($this->cookie), MCRYPT_MODE_CBC, $this->_iv)); - - return(base64_decode($this->myValue)); - } - else - { - return($_COOKIE[$this->myCookie]); - } - } - - /** - * Set and create the cookie - * - * @param string $cookie Cookie name - * @param string $value Cookie value - * @param integer $expire Expiration - * @param string $path Path of cookie - * @param string $domain Domain name - * @param int $secure 0 or 1 - * @return void - */ - public function setCookie($cookie, $value, $expire=0, $path="/", $domain="", $secure=0) - { - $this->myCookie = $cookie; - $this->myValue = $value; - $this->myExpire = $expire; - $this->myPath = $path; - $this->myDomain = $domain; - $this->mySecure = $secure; - - //print 'key='.$this->myKey.' name='.$this->myCookie.' value='.$this->myValue.' expire='.$this->myExpire; - - $this->_cryptCookie(); - } - - /** - * Get the cookie - * - * @param string $cookie Cookie name - * @return string Decrypted value - */ - public function getCookie($cookie) - { - $this->myCookie = $cookie; - - $decryptValue = $this->_decryptCookie(); - - return $decryptValue; - } - -} - diff --git a/htdocs/core/class/ctyperesource.class.php b/htdocs/core/class/ctyperesource.class.php index 1de616210e4..a5a6ea879ce 100644 --- a/htdocs/core/class/ctyperesource.class.php +++ b/htdocs/core/class/ctyperesource.class.php @@ -48,14 +48,14 @@ class Ctyperesource /** */ - + public $code; public $label; public $active; /** */ - + /** * Constructor @@ -82,7 +82,7 @@ class Ctyperesource $error = 0; // Clean parameters - + if (isset($this->code)) { $this->code = trim($this->code); } @@ -93,26 +93,26 @@ class Ctyperesource $this->active = trim($this->active); } - + // Check parameters // Put here code to add control on parameters values // Insert request $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '('; - + $sql.= 'code,'; $sql.= 'label'; $sql.= 'active'; - + $sql .= ') VALUES ('; - + $sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").','; $sql .= ' '.(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").','; $sql .= ' '.(! isset($this->active)?'NULL':$this->active); - + $sql .= ')'; $this->db->begin(); @@ -165,18 +165,18 @@ class Ctyperesource $sql = 'SELECT'; $sql .= ' t.rowid,'; - + $sql .= " t.code,"; $sql .= " t.label,"; $sql .= " t.active"; - + $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; if ($id) $sql.= " WHERE t.id = ".$id; elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'"; elseif ($label) $sql.= " WHERE t.label = '".$this->db->escape($label)."'"; - - + + $resql = $this->db->query($sql); if ($resql) { $numrows = $this->db->num_rows($resql); @@ -184,25 +184,20 @@ class Ctyperesource $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; - + $this->code = $obj->code; $this->label = $obj->label; $this->active = $obj->active; - + } - + // Retrieve all extrafields for invoice // fetch optionals attributes and labels - /* - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields=new ExtraFields($this->db); - $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); - $this->fetch_optionals($this->id,$extralabels); - */ - + // $this->fetch_optionals(); + // $this->fetch_lines(); - + $this->db->free($resql); if ($numrows) { @@ -236,12 +231,12 @@ class Ctyperesource $sql = 'SELECT'; $sql .= ' t.rowid,'; - + $sql .= " t.code,"; $sql .= " t.label,"; $sql .= " t.active"; - + $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t'; // Manage filter @@ -251,7 +246,7 @@ class Ctyperesource $sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\''; } } - + if (count($sqlwhere) > 0) { $sql .= ' WHERE ' . implode(' '.$filtermode.' ', $sqlwhere); } @@ -270,12 +265,12 @@ class Ctyperesource $line = new self($this->db); $line->id = $obj->rowid; - + $line->code = $obj->code; $line->label = $obj->label; $line->active = $obj->active; - + } $this->db->free($resql); @@ -303,7 +298,7 @@ class Ctyperesource dol_syslog(__METHOD__, LOG_DEBUG); // Clean parameters - + if (isset($this->code)) { $this->code = trim($this->code); } @@ -319,12 +314,12 @@ class Ctyperesource // Update request $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET'; - + $sql .= ' code = '.(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").','; $sql .= ' label = '.(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").','; $sql .= ' active = '.(isset($this->active)?$this->active:"null"); - + $sql .= ' WHERE rowid=' . $this->id; $this->db->begin(); @@ -387,7 +382,7 @@ class Ctyperesource } // If you need to delete child tables to, you can insert them here - + if (!$error) { $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element; $sql .= ' WHERE rowid=' . $this->id; @@ -468,7 +463,7 @@ class Ctyperesource public function initAsSpecimen() { $this->id = 0; - + $this->code = ''; $this->label = ''; $this->active = ''; @@ -488,7 +483,7 @@ class CtyperesourceLine /** * @var mixed Sample line property 1 */ - + public $code; public $label; public $active; @@ -496,5 +491,5 @@ class CtyperesourceLine /** * @var mixed Sample line property 2 */ - + } diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index 37dedea8b6b..5cb7d3e6882 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2009 Laurent Destailleur + * Copyright (C) 2004-2018 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 @@ -24,8 +24,7 @@ /** - * \class DiscountAbsolute - * \brief Class to manage absolute discounts + * Class to manage absolute discounts */ class DiscountAbsolute { @@ -34,6 +33,7 @@ class DiscountAbsolute public $id; // Id discount public $fk_soc; + public $discount_type; // 0 => customer discount, 1 => supplier discount public $amount_ht; // public $amount_tva; // public $amount_ttc; // @@ -45,6 +45,7 @@ class DiscountAbsolute public $fk_facture; // Id invoice when a discount line is used into an invoice (for credit note) public $fk_facture_source; // Id facture avoir a l'origine de la remise public $ref_facture_source; // Ref facture avoir a l'origine de la remise + public $ref_invoice_supplier_source; /** * Constructor @@ -60,33 +61,36 @@ class DiscountAbsolute /** * Load object from database into memory * - * @param int $rowid id discount to load - * @param int $fk_facture_source fk_facture_source - * @return int <0 if KO, =0 if not found, >0 if OK + * @param int $rowid id discount to load + * @param int $fk_facture_source fk_facture_source + * @param int $fk_invoice_supplier_source fk_invoice_supplier_source + * @return int <0 if KO, =0 if not found, >0 if OK */ - function fetch($rowid, $fk_facture_source=0) + function fetch($rowid, $fk_facture_source=0, $fk_invoice_supplier_source=0) { global $conf; // Check parameters - if (! $rowid && ! $fk_facture_source) + if (! $rowid && ! $fk_facture_source && ! $fk_invoice_supplier_source) { $this->error='ErrorBadParameters'; return -1; } - $sql = "SELECT sr.rowid, sr.fk_soc,"; + $sql = "SELECT sr.rowid, sr.fk_soc, sr.discount_type,"; $sql.= " sr.fk_user,"; $sql.= " sr.amount_ht, sr.amount_tva, sr.amount_ttc, sr.tva_tx,"; $sql.= " sr.multicurrency_amount_ht, sr.multicurrency_amount_tva, sr.multicurrency_amount_ttc,"; - $sql.= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.description,"; + $sql.= " sr.fk_facture_line, sr.fk_facture, sr.fk_facture_source, sr.fk_invoice_supplier_line, sr.fk_invoice_supplier, sr.fk_invoice_supplier_source, sr.description,"; $sql.= " sr.datec,"; - $sql.= " f.facnumber as ref_facture_source"; + $sql.= " f.facnumber as ref_facture_source, fsup.facnumber as ref_invoice_supplier_source"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fsup ON sr.fk_invoice_supplier_source = fsup.rowid"; $sql.= " WHERE sr.entity = " . $conf->entity; if ($rowid) $sql.= " AND sr.rowid=".$rowid; if ($fk_facture_source) $sql.= " AND sr.fk_facture_source=".$fk_facture_source; + if ($fk_invoice_supplier_source) $sql.= " AND sr.fk_invoice_supplier_source=".$fk_invoice_supplier_source; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -98,6 +102,7 @@ class DiscountAbsolute $this->id = $obj->rowid; $this->fk_soc = $obj->fk_soc; + $this->discount_type = $obj->discount_type; $this->amount_ht = $obj->amount_ht; $this->amount_tva = $obj->amount_tva; @@ -113,6 +118,10 @@ class DiscountAbsolute $this->fk_facture = $obj->fk_facture; $this->fk_facture_source = $obj->fk_facture_source; // Id avoir source $this->ref_facture_source = $obj->ref_facture_source; // Ref avoir source + $this->fk_invoice_supplier_line = $obj->fk_invoice_supplier_line; + $this->fk_invoice_supplier = $obj->fk_invoice_supplier; + $this->fk_invoice_supplier_source = $obj->fk_invoice_supplier_source; // Id avoir source + $this->ref_invoice_supplier_source = $obj->ref_invoice_supplier_source; // Ref avoir source $this->description = $obj->description; $this->datec = $this->db->jdate($obj->datec); @@ -159,13 +168,14 @@ class DiscountAbsolute // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except"; - $sql.= " (entity, datec, fk_soc, fk_user, description,"; + $sql.= " (entity, datec, fk_soc, discount_type, fk_user, description,"; $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,"; - $sql.= " fk_facture_source"; + $sql.= " fk_facture_source, fk_invoice_supplier_source"; $sql.= ")"; - $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',"; + $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".(empty($this->discount_type)?0:intval($this->discount_type)).", ".$user->id.", '".$this->db->escape($this->description)."',"; $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.","; - $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null"); + $sql.= " ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'":"null").","; + $sql.= " ".($this->fk_invoice_supplier_source ? "'".$this->db->escape($this->fk_invoice_supplier_source)."'":"null"); $sql.= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); @@ -221,14 +231,45 @@ class DiscountAbsolute } } + // Check if we can remove the discount + if ($this->fk_invoice_supplier_source) + { + $sql="SELECT COUNT(rowid) as nb"; + $sql.=" FROM ".MAIN_DB_PREFIX."societe_remise_except"; + $sql.=" WHERE (fk_invoice_supplier_line IS NOT NULL"; // Not used as absolute simple discount + $sql.=" OR fk_invoice_supplier IS NOT NULL)"; // Not used as credit note and not used as deposit + $sql.=" AND fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; + //$sql.=" AND rowid != ".$this->id; + + dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + if ($obj->nb > 0) + { + $this->error='ErrorThisPartOrAnotherIsAlreadyUsedSoDiscountSerieCantBeRemoved'; + return -2; + } + } + else + { + dol_print_error($this->db); + return -1; + } + } + $this->db->begin(); // Delete but only if not used $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except "; if ($this->fk_facture_source) $sql.= " WHERE fk_facture_source = ".$this->fk_facture_source; // Delete all lines of same serie + elseif ($this->fk_invoice_supplier_source) $sql.= " WHERE fk_invoice_supplier_source = ".$this->fk_invoice_supplier_source; // Delete all lines of same serie else $sql.= " WHERE rowid = ".$this->id; // Delete only line $sql.= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount $sql.= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit + $sql.= " AND (fk_invoice_supplier_line IS NULL"; // Not used as absolute simple discount + $sql.= " AND fk_invoice_supplier IS NULL)"; // Not used as credit note and not used as deposit dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG); $result=$this->db->query($sql); @@ -255,6 +296,26 @@ class DiscountAbsolute return -1; } } + elseif($this->fk_invoice_supplier_source) { + + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; + $sql.=" set paye=0, fk_statut=1"; + $sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_invoice_supplier_source; + + dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); + $result=$this->db->query($sql); + if ($result) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } else { $this->db->commit(); @@ -295,16 +356,26 @@ class DiscountAbsolute } $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - if ($rowidline) $sql.=" SET fk_facture_line = ".$rowidline; - if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice; + if(! empty($this->discount_type)) { + if ($rowidline) $sql.=" SET fk_invoice_supplier_line = ".$rowidline; + if ($rowidinvoice) $sql.=" SET fk_invoice_supplier = ".$rowidinvoice; + } else { + if ($rowidline) $sql.=" SET fk_facture_line = ".$rowidline; + if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice; + } $sql.=" WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $this->fk_facture_line=$rowidline; - $this->fk_facture=$rowidinvoice; + if(! empty($this->discount_type)) { + $this->fk_invoice_supplier_line=$rowidline; + $this->fk_invoice_supplier=$rowidinvoice; + } else { + $this->fk_facture_line=$rowidline; + $this->fk_facture=$rowidinvoice; + } return 1; } else @@ -324,7 +395,11 @@ class DiscountAbsolute function unlink_invoice() { $sql ="UPDATE ".MAIN_DB_PREFIX."societe_remise_except"; - $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; + if(! empty($this->discount_type)) { + $sql.=" SET fk_invoice_supplier_line = NULL, fk_invoice_supplier = NULL"; + } else { + $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; + } $sql.=" WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG); @@ -344,14 +419,14 @@ class DiscountAbsolute /** * Return amount (with tax) of discounts currently available for a company, user or other criteria * - * @param Societe $company Object third party for filter - * @param User $user Filtre sur un user auteur des remises - * @param string $filter Filtre autre - * @param int $maxvalue Filter on max value for discount - * @param string $mode 'customer' = discounts the customer has, 'supplier' = discount i have at this supplier + * @param Societe $company Object third party for filter + * @param User $user Filtre sur un user auteur des remises + * @param string $filter Filtre autre + * @param int $maxvalue Filter on max value for discount + * @param int $discount_type 0 => customer discount, 1 => supplier discount * @return int <0 if KO, amount otherwise */ - function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $mode='customer') + function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0, $discount_type=0) { global $conf; @@ -359,8 +434,12 @@ class DiscountAbsolute //$sql = "SELECT rc.amount_ttc as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc"; $sql.= " WHERE rc.entity = " . $conf->entity; - if ($mode != 'supplier') $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available - else $sql.= " AND (rc.fk_suppler_invoice IS NULL AND rc.fk_supplier_invoice IS NULL)"; // Available + $sql.= " AND rc.discount_type=".intval($discount_type); + if (! empty($discount_type)) { + $sql.= " AND (rc.fk_invoice_supplier IS NULL AND rc.fk_invoice_supplier_line IS NULL)"; // Available from supplier + } else { + $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)"; // Available to customer + } if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id; if (is_object($user)) $sql.= " AND rc.fk_user = ".$user->id; if ($filter) $sql.=' AND ('.$filter.')'; @@ -452,7 +531,7 @@ class DiscountAbsolute $sql = 'SELECT sum(rc.amount_ttc) as amount, sum(rc.multicurrency_amount_ttc) as multicurrency_amount'; $sql.= ' FROM '.MAIN_DB_PREFIX.'societe_remise_except as rc, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql.= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.$invoice->id; - $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received + $sql.= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess paid } else { @@ -489,10 +568,12 @@ class DiscountAbsolute $result=''; if ($option == 'invoice') { + $facid=! empty($this->discount_type)?$this->fk_invoice_supplier_source:$this->fk_facture_source; + $link=! empty($this->discount_type)?'/fourn/facture/card.php':'/compta/facture/card.php'; $label=$langs->trans("ShowDiscount").': '.$this->ref_facture_source; - $link = ''; + $link = ''; $linkend=''; - $ref=$this->ref_facture_source; + $ref=! empty($this->discount_type)?$this->ref_invoice_supplier_source:$this->ref_facture_source; $picto='bill'; } if ($option == 'discount') { diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index aa500ab64df..860d89afea8 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -153,7 +153,7 @@ class DolEditor { global $conf,$langs; - $fullpage=False; + $fullpage=false; if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT)) { $disallowAnyContent=empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed or all diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index 329383160aa..f40d30f389e 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -594,7 +594,7 @@ class DolGraph * @param string $fileurl Url path to show image if saved onto disk * @return integer|null */ - function draw($file,$fileurl='') + function draw($file, $fileurl='') { if (empty($file)) { @@ -602,12 +602,17 @@ class DolGraph dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR); return -2; } - if (! is_array($this->data) || count($this->data) < 1) + if (! is_array($this->data)) { $this->error="Call to draw method was made but SetData was not called or called with an empty dataset for parameters"; dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR); return -1; } + if (count($this->data) < 1) + { + $this->error="Call to draw method was made but SetData was is an empty dataset"; + dol_syslog(get_class($this)."::draw ".$this->error, LOG_WARNING); + } $call = "draw_".$this->_library; call_user_func_array(array($this,$call), array($file,$fileurl)); } @@ -669,7 +674,7 @@ class DolGraph $group->setPadding($paddleft, $paddright); // Width on left and right for Y axis values $group->legend->setSpace(0); $group->legend->setPadding(2,2,2,2); - $group->legend->setPosition(NULL,0.1); + $group->legend->setPosition(null, 0.1); $group->legend->setBackgroundColor($colorsemitrans); if (is_array($this->bgcolorgrid)) $group->grid->setBackgroundColor($bgcolorgrid); @@ -729,7 +734,7 @@ class DolGraph $plot->barShadow->setSize($this->SetShading); $plot->barShadow->setPosition(SHADOW_RIGHT_TOP); $plot->barShadow->setColor(new Color(160, 160, 160, 50)); - $plot->barShadow->smooth(TRUE); + $plot->barShadow->smooth(true); //$plot->setSize(1, 0.96); //$plot->setCenter(0.5, 0.52); @@ -822,7 +827,7 @@ class DolGraph $legends=array(); $nblot=count($this->data[0])-1; // -1 to remove legend - if ($nblot < 0) dol_print_error('', 'Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw'); + if ($nblot < 0) dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING); $firstlot=0; // Works with line but not with bars //if ($nblot > 2) $firstlot = ($nblot - 2); // We limit nblot to 2 because jflot can't manage more than 2 bars on same x @@ -875,10 +880,17 @@ class DolGraph $this->stringtoshow.=''; + + if ($acceptdelayedhtml) + { + $delayedhtmlcontent.=$outdelayed; + } + else + { + $out.=$outdelayed; + } + return $out; + } + /** * Show a multiselect form from an array. * @@ -5766,7 +5936,7 @@ class Form -
+